text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using LinqToTwitter; using System.Diagnostics; namespace TUBES_STIMA_3 { public partial class WebForm1 : System.Web.UI.Page { Program tw = new Program(); public class Program { public class keyword//This is nested class for grouping keyword by category, e.g : Dinas kebersihan, etc. { public int id; public string str; public keyword() { id = 0; str = ""; } } private const int UNDEF = 5;//for now, Forget about it private List<keyword> key = new List<keyword>();//List of keyword for some category of organization e.g : Dinas kebersihan : Sampah; private List<List<Status>> cat = new List<List<Status>>(UNDEF);//This list used for container of tweet private List<Status> tweets;//Container of tweet which is retrieved from twitter.com public List<keyword> getkey() { return key; } public List<List<Status>> getcat() { return cat; } public List<Status> gettweets() { return tweets; } //Authorize user to access API private SingleUserAuthorizer authorizer = new SingleUserAuthorizer { CredentialStore = new SingleUserInMemoryCredentialStore { //You can get this code from your twiiter account ConsumerKey = "wlb7bXrkknmUhqev3FFGyG3Ce", ConsumerSecret = "54KzL3Tt0OBFvD9Ah2tiRCHMT3xClg1MSE0iPNd3ccvw1R5Rw1", AccessToken = "167988305-idP2UDH5ral2b0LVKrsaunE886cZivEAR8pKLdTz", AccessTokenSecret = "TRjpdubS7JmY1sXv9VMOmxQr1fNFk8HnafB1g1d2YKeau" } }; //Search tweet public void SearchTweets(string searchpat) { var twitterContext = new TwitterContext(authorizer); var srch = Enumerable.SingleOrDefault(from search in twitterContext.Search where search.Type == SearchType.Search && search.Query == searchpat && search.Count == 200 select search ); if (srch != null && srch.Statuses != null) { tweets = srch.Statuses.ToList(); } } //Add keyword to List and group it public void setKeyword(List<string> keywor) { for (int i = 0; i < keywor.Count; i++) { int startidx = 0; for (int j = 0; j < keywor[i].Length; j++) { if (keywor[i][j] == ';') { keyword keytemp = new keyword(); keytemp.str = keywor[i].Substring(startidx, j - startidx); keytemp.id = i; key.Add(keytemp); startidx = j + 1; } } } } //Knuth Morris Prat preprocess Algorithm private List<int> fail_func(string pat) { List<int> arrOfBorder = new List<int>(pat.Length); int i, j, k; //initialize arrOfBorder with 0 for (i = 0; i < pat.Length; i++) { arrOfBorder.Add(0); } i = 1;//i = 1 because the arrOfBorder[0] always 0 while (i < pat.Length) { j = i; k = 0; while (j > 0 && pat[k] == pat[j]) {//Checking if the pattern has same prefix and suffix arrOfBorder[i] += 1; k++; j--; } i++; } return arrOfBorder; } //This is the main Algorith of Knuth Morris Prat public void kmp() { List<List<int>> ListOfBorder = new List<List<int>>(key.Count); //initialization list of list for (int ct = 0; ct < UNDEF; ct++) { cat.Add(new List<Status>()); } //set the list of list for (int br = 0; br < key.Count; br++) { ListOfBorder.Add(fail_func(key[br].str)); } int i = 0, k, j, l, m; bool found; Status st = new Status(); while (i < tweets.Count) { found = false; j = k = l = m = 0; st = tweets[i];//assign st with information on list of tweets, such as userID, user.ScreenName, Tweets, etc. while (j < st.Text.Length && !found) { if (key[m].str[k] != st.Text[j]) { if (k == 0) {//if mismatch from start, it will cause the text shift by one character to right, like bruteforce j++; k = 0; } else if (k > 0) { j += k - ListOfBorder[m][k - 1] - 1; k -= k - ListOfBorder[m][k - 1]; } } else { k++; j++; } //if k = length of keyword then insert tweet data to list of category, and quit from loop if (k == key[m].str.Length) { if (key[m].id == 0) { cat[0].Add(st); } else if (key[m].id == 1) { cat[1].Add(st); } found = true; } //if k = length of keyword, j = length of tweet and m < Length of list of key -1 than insert it to unknown category if (!found && j == st.Text.Length && m < key.Count - 1) { m++; j = 0; } //if k = length of keyword and j = length of tweet m < Length of list of key -1 than insert it to unknown category else if (!found && j == st.Text.Length && m == key.Count - 1) { cat[UNDEF - 1].Add(st); } } i++; } } void printTweet() { for (int i = 0; i < UNDEF; i++) { if (i == 0) { Console.WriteLine("Dinas Kebersihan"); Console.WriteLine("Jumlah : {0}", cat[i].Count); } else if (i == 1) { Console.WriteLine("Dinas Kesehatan"); Console.WriteLine("Jumlah : {0}", cat[i].Count); } else if (i == 4) { Console.WriteLine("Unknown"); Console.WriteLine("Jumlah : {0}", cat[i].Count); } for (int j = 0; j < cat[i].Count; j++) { if (cat[i][j] != null) { Console.WriteLine("User : {0}, Tweet : {1}", cat[i][j].User.ScreenNameResponse, cat[i][j].Text); } else break; } Console.WriteLine(); } } //testing list of keyword, forget it void printKeyword() { for (int i = 0; i < key.Count; i++) { Console.Write("ID : {0}, TEXT : {1}", key[i].id, key[i].str); Console.WriteLine(); } } /* //Main program //follow instruction below //1. Fill "Keyword twitter : " with keyword which we want the search on twitter.com e.g : #pemkot //2. Fill "Dinas kebersihan : " with a word or many, separated with ';', ending with ';' too. e.g Sampah;TPS;. No white space between ';' and keyword static void Main(string[] args) { string input, keyword; List<string> lstring = new List<string>(); Console.Write("Keyword Twitter : "); input = Console.ReadLine(); Console.Write("Dinas kebersihan : "); keyword = Console.ReadLine(); lstring.Add(keyword); Console.Write("Dinas kesehatan : "); keyword = Console.ReadLine(); lstring.Add(keyword); Program tw = new Program(); tw.setKeyword(33..lstring); tw.SearchTweets(input); tw.kmp(); tw.printTweet(); } */ } protected void Page_Load(object sender, EventArgs e) { ScriptResourceDefinition myScriptResDef = new ScriptResourceDefinition(); myScriptResDef.Path = "~/Scripts/jquery-1.10.2.js"; myScriptResDef.DebugPath = "~/Scripts/jquery-1.10.2.js"; myScriptResDef.CdnPath = "http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js"; myScriptResDef.CdnDebugPath = "http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.js"; ScriptManager.ScriptResourceMapping.AddDefinition("jquery", null, myScriptResDef); } void printTweet() { Literal1.Mode = LiteralMode.PassThrough; for (int i = 0; i < 5; i++) { if (i == 0) { Literal1.Text += "<h3>Dinas Kebersihan</h3>"; Literal1.Text += "<p>Jumlah : " + Convert.ToString(tw.getcat()[i].Count) + "</p>"; // Console.WriteLine("Dinas Kebersihan"); // Console.WriteLine("Jumlah : {0}", cat[i].Count); } else if (i == 1) { Literal1.Text += "<h3>Dinas Kesehatan</h3> "; Literal1.Text += "<p>Jumlah : " + Convert.ToString(tw.getcat()[i].Count) + "</p>"; //Console.WriteLine("Dinas Kesehatan"); //Console.WriteLine("Jumlah : {0}", cat[i].Count); } else if (i == 4) { Literal1.Text += "<h3>Unknown</h3> "; Literal1.Text += "<p>Jumlah : " + Convert.ToString(tw.getcat()[i].Count) + "</p>"; //Console.WriteLine("Unknown"); //Console.WriteLine("Jumlah : {0}", cat[i].Count); } for (int j = 0; j < tw.getcat()[i].Count; j++) { if (tw.getcat()[i][j] != null) { if (j % 2 == 0) { Literal1.Text += "<div class='row bg-darkest-gray'><font color='white'> <br />"; } Literal1.Text += "<div class = 'col-sm-2' ><img class = 'img-rounded img-centered ' src=" + Convert.ToString(tw.getcat()[i][j].User.ProfileImageUrlHttps) + " > </img></div>"; Literal1.Text += "<div class = 'col-sm-4' ><p>User : <a href='http://twitter.com/" + Convert.ToString(tw.getcat()[i][j].User.ScreenNameResponse)+ "' target='_blank'>@"+ Convert.ToString(tw.getcat()[i][j].User.ScreenNameResponse) + "</a>" + "</p><p> Tweet : " + Convert.ToString(tw.getcat()[i][j].Text) + "</p> </div>"; if (j%2 == 1 || j == tw.getcat()[i].Count - 1) { Literal1.Text += "</font></div> <br />"; } // Console.WriteLine("User : {0}, Tweet : {1}", cat[i][j].User.ScreenNameResponse, cat[i][j].Text); } else break; } // Literal1.Text += "test dulu< br />"; //Console.WriteLine(); } } protected void Run_Click(object sender, EventArgs e) { if (IsValid && TextBox1.Text != "" && TextBox2.Text != "" && TextBox3.Text != "") { /* string url = HttpContext.Current.Request.Url.AbsoluteUri + "#Tweet"; System.Diagnostics.Process.Start(url);*/ Literal1.Text = ""; string input = Convert.ToString(TextBox1.Text); tw.SearchTweets(input); List<string> lstring = new List<string>(); string keyword = Convert.ToString(TextBox2.Text); lstring.Add(keyword); keyword = Convert.ToString(TextBox3.Text); lstring.Add(keyword); tw.setKeyword(lstring); tw.kmp(); Literal1.Mode = LiteralMode.PassThrough; printTweet(); } } } }
using System.Threading.Tasks; using Domain.Entitys; namespace Domain.DomainServices { public interface IOrderService { Task OrderBuild(Order order); Task Pay(Order order); } }
using MyOnlineShop.DataAccess.Context; using MyOnlineShop.DataAccess.Models; using MyOnlineShop.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MyOnlineShop.Context { public class Seeder { public static void Initialize(OnlineShopContext context) { context.Database.EnsureCreated(); var customer = new Customer() { FirstName = "Jok", LastName = "Garcia", Email = "jok@email.com", ContactNumber = "888777", IsActive = true }; context.Customers.Add(customer); context.SaveChanges(); var customer2 = new Customer() { FirstName = "Lebron", LastName = "James", Email = "lbj@email.com", ContactNumber = "31231231", }; context.Customers.Add(customer2); context.SaveChanges(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; using System.Diagnostics; using System.IO; using System.Xml; using DocGen.ObjectModel; using System.Xml.Schema; using DocGen.OOXML; //Select from IText or OOXML, have to add external interface once IText is complete namespace DocGen { /// <summary> /// Main class for generating documents given the XML input. /// </summary> public class Generator { private XDocument document; private DocGen.ObjectModel.IDocument resultDoc; private ElementGenerator generator; private String InputFileURI { get; set; } public Generator(String xmlFilePath, String outputFileName, String defaultsXmlPath) { Element.DefaultsXml = defaultsXmlPath; generator = new ElementGenerator(); try { this.InputFileURI = xmlFilePath; document = XDocument.Load(InputFileURI); resultDoc = new Document(outputFileName); } catch (XmlException e) { throw new InvalidInputException("Malformed XML", e); } } private void ValidateXml() { XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.Add(null,"PdfGen.xsd"); document.Validate(schemaSet, ValidationErrorHandler); } private void ValidationErrorHandler(object sender, ValidationEventArgs e) { throw new InvalidInputException("Input XML is Invalid: " + e.Message); } public void Generate() { //TODO: Add all to xsd and enable //ValidateXml(); try { FileInfo outputFile = new FileInfo(InputFileURI); ProcessAttribues(); foreach (var element in GetMainTags()) { AddToDocument(element); } resultDoc.Save(); } catch (InvalidOperationException ex) { throw new InvalidInputException("Input XML is Invalid", ex); } catch (FileNotFoundException e) { throw new InvalidInputException("Input XML is Invalid, " + e.Message, e); } } private void ProcessAttribues() { XElement root = document.Root; XAttribute autoGenerateTOC = root.Attribute("autoGenerateToc"); if (autoGenerateTOC != null) { if ("true".Equals(autoGenerateTOC.Value)) { resultDoc.AutoGenerateTOC = true; } } } private IEnumerable<XElement> GetMainTags() { XElement root = document.Root; IEnumerable<XElement> childElements = root.Elements(); return childElements; } public void AddToDocument(XElement element) { Element generatedElement = generator.GetElement(element); if (generatedElement == null) return; //TODO:Remove and add exception resultDoc.AddElement(generatedElement); } } }
using System; using org.ogre; namespace SharpEngine.Editor.Widget { public partial class OgreImage { private double _resourceItemScalar; private double _currentProcess; protected virtual void CallResourceItemLoaded(ResourceLoadEventArgs e) { Dispatcher.Invoke((MethodInvoker)(() => OnResourceItemLoaded(e))); } protected virtual void OnResourceItemLoaded(ResourceLoadEventArgs e) { ResourceLoadItemProgress?.Invoke(this, e); } private void InitResourceLoad() { GroupEventListener rgl = new GroupEventListener(); rgl.ResourceGroupLoadStarted += Singleton_ResourceGroupLoadStarted; rgl.ResourceGroupScriptingStarted += Singleton_ResourceGroupScriptingStarted; rgl.ScriptParseStarted += Singleton_ScriptParseStarted; rgl.ResourceLoadStarted += Singleton_ResourceLoadStarted; rgl.WorldGeometryStageStarted += Singleton_WorldGeometryStageStarted; ResourceGroupManager.getSingleton().addResourceGroupListener(rgl); _currentProcess = 0; } private void Singleton_WorldGeometryStageStarted(string description) { _currentProcess += _resourceItemScalar; CallResourceItemLoaded(new ResourceLoadEventArgs(description, _currentProcess)); } private void Singleton_ResourceLoadStarted(ResourcePtr resource) { _currentProcess += _resourceItemScalar; CallResourceItemLoaded(new ResourceLoadEventArgs(resource.getName(), _currentProcess)); } private void Singleton_ScriptParseStarted(string scriptName) { _currentProcess += _resourceItemScalar; CallResourceItemLoaded(new ResourceLoadEventArgs(scriptName, _currentProcess)); } private void Singleton_ResourceGroupScriptingStarted(string groupName, uint scriptCount) { _resourceItemScalar = (scriptCount > 0) ? 0.4d / scriptCount : 0; } private void Singleton_ResourceGroupLoadStarted(string groupName, uint resourceCount) { _resourceItemScalar = (resourceCount > 0) ? 0.6d / resourceCount : 0; } public event EventHandler<ResourceLoadEventArgs> ResourceLoadItemProgress; class GroupEventListener : ResourceGroupListener { public Action<string, uint> ResourceGroupLoadStarted; public Action<string, uint> ResourceGroupScriptingStarted; public Action<ResourcePtr> ResourceLoadStarted; public Action<string> ScriptParseStarted; public Action<string> WorldGeometryStageStarted; public override void resourceGroupLoadStarted(string groupName, uint resourceCount) => ResourceGroupLoadStarted?.Invoke(groupName, resourceCount); public override void resourceGroupScriptingStarted(string groupName, uint scriptCount) => ResourceGroupScriptingStarted?.Invoke(groupName, scriptCount); public override void resourceLoadStarted(ResourcePtr resource) => ResourceLoadStarted?.Invoke(resource); public override void scriptParseStarted(string scriptName, SWIGTYPE_p_bool skipThisScript) => ScriptParseStarted?.Invoke(scriptName); public override void worldGeometryStageStarted(string description) => WorldGeometryStageStarted?.Invoke(description); } } public class ResourceLoadEventArgs : EventArgs { public ResourceLoadEventArgs(string name, double progress) { this.Name = name; this.Progress = progress; } public string Name { get; private set; } public double Progress { get; private set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Integer.Domain.Agenda; using Raven.Client; using System.Linq.Expressions; using Integer.Infrastructure.LINQExpressions; using Integer.Domain.Acesso; namespace Integer.Infrastructure.Repository { public class UsuarioTokenRepository : UsuarioTokens { private IDocumentSession documentSession; public UsuarioTokenRepository(IDocumentSession documentSession) { this.documentSession = documentSession; } public UsuarioToken Com(Expression<Func<UsuarioToken, bool>> condicao) { return documentSession.Query<UsuarioToken>().FirstOrDefault(condicao); } public void Salvar(UsuarioToken usuarioToken) { documentSession.Store(usuarioToken); } } }
using PlayFab.ClientModels; using PlayFab.Internal; using PlayFab.Json; using System; using System.Threading.Tasks; namespace PlayFab { /// <summary> /// APIs which provide the full range of PlayFab features available to the client - authentication, account and data management, inventory, friends, matchmaking, reporting, and platform-specific functionality /// </summary> public class PlayFabClientAPI { /// <summary> /// Gets a Photon custom authentication token that can be used to securely join the player into a Photon room. See https://api.playfab.com/docs/using-photon-with-playfab/ for more details. /// </summary> public static async Task<PlayFabResult<GetPhotonAuthenticationTokenResult>> GetPhotonAuthenticationTokenAsync(GetPhotonAuthenticationTokenRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetPhotonAuthenticationToken", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetPhotonAuthenticationTokenResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetPhotonAuthenticationTokenResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetPhotonAuthenticationTokenResult> { Result = result, CustomData = customData }; } /// <summary> /// Signs the user in using the Android device identifier, returning a session identifier that can subsequently be used for API calls which require an authenticated user /// </summary> public static async Task<PlayFabResult<LoginResult>> LoginWithAndroidDeviceIDAsync(LoginWithAndroidDeviceIDRequest request, object customData = null) { request.TitleId = PlayFabSettings.TitleId ?? request.TitleId; if(request.TitleId == null) throw new Exception ("Must be have PlayFabSettings.TitleId set to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/LoginWithAndroidDeviceID", request, null, null); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<LoginResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<LoginResult>>(resultRawJson); var result = resultData.data; _authKey = result.SessionTicket ?? _authKey; await MultiStepClientLogin(result.SettingsForUser.NeedsAttribution); return new PlayFabResult<LoginResult> { Result = result, CustomData = customData }; } /// <summary> /// Signs the user in using a custom unique identifier generated by the title, returning a session identifier that can subsequently be used for API calls which require an authenticated user /// </summary> public static async Task<PlayFabResult<LoginResult>> LoginWithCustomIDAsync(LoginWithCustomIDRequest request, object customData = null) { request.TitleId = PlayFabSettings.TitleId ?? request.TitleId; if(request.TitleId == null) throw new Exception ("Must be have PlayFabSettings.TitleId set to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/LoginWithCustomID", request, null, null); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<LoginResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<LoginResult>>(resultRawJson); var result = resultData.data; _authKey = result.SessionTicket ?? _authKey; await MultiStepClientLogin(result.SettingsForUser.NeedsAttribution); return new PlayFabResult<LoginResult> { Result = result, CustomData = customData }; } /// <summary> /// Signs the user into the PlayFab account, returning a session identifier that can subsequently be used for API calls which require an authenticated user /// </summary> public static async Task<PlayFabResult<LoginResult>> LoginWithEmailAddressAsync(LoginWithEmailAddressRequest request, object customData = null) { request.TitleId = PlayFabSettings.TitleId ?? request.TitleId; if(request.TitleId == null) throw new Exception ("Must be have PlayFabSettings.TitleId set to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/LoginWithEmailAddress", request, null, null); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<LoginResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<LoginResult>>(resultRawJson); var result = resultData.data; _authKey = result.SessionTicket ?? _authKey; await MultiStepClientLogin(result.SettingsForUser.NeedsAttribution); return new PlayFabResult<LoginResult> { Result = result, CustomData = customData }; } /// <summary> /// Signs the user in using a Facebook access token, returning a session identifier that can subsequently be used for API calls which require an authenticated user /// </summary> public static async Task<PlayFabResult<LoginResult>> LoginWithFacebookAsync(LoginWithFacebookRequest request, object customData = null) { request.TitleId = PlayFabSettings.TitleId ?? request.TitleId; if(request.TitleId == null) throw new Exception ("Must be have PlayFabSettings.TitleId set to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/LoginWithFacebook", request, null, null); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<LoginResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<LoginResult>>(resultRawJson); var result = resultData.data; _authKey = result.SessionTicket ?? _authKey; await MultiStepClientLogin(result.SettingsForUser.NeedsAttribution); return new PlayFabResult<LoginResult> { Result = result, CustomData = customData }; } /// <summary> /// Signs the user in using an iOS Game Center player identifier, returning a session identifier that can subsequently be used for API calls which require an authenticated user /// </summary> public static async Task<PlayFabResult<LoginResult>> LoginWithGameCenterAsync(LoginWithGameCenterRequest request, object customData = null) { request.TitleId = PlayFabSettings.TitleId ?? request.TitleId; if(request.TitleId == null) throw new Exception ("Must be have PlayFabSettings.TitleId set to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/LoginWithGameCenter", request, null, null); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<LoginResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<LoginResult>>(resultRawJson); var result = resultData.data; _authKey = result.SessionTicket ?? _authKey; await MultiStepClientLogin(result.SettingsForUser.NeedsAttribution); return new PlayFabResult<LoginResult> { Result = result, CustomData = customData }; } /// <summary> /// Signs the user in using a Google account access token(https://developers.google.com/android/reference/com/google/android/gms/auth/GoogleAuthUtil#public-methods), returning a session identifier that can subsequently be used for API calls which require an authenticated user /// </summary> public static async Task<PlayFabResult<LoginResult>> LoginWithGoogleAccountAsync(LoginWithGoogleAccountRequest request, object customData = null) { request.TitleId = PlayFabSettings.TitleId ?? request.TitleId; if(request.TitleId == null) throw new Exception ("Must be have PlayFabSettings.TitleId set to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/LoginWithGoogleAccount", request, null, null); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<LoginResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<LoginResult>>(resultRawJson); var result = resultData.data; _authKey = result.SessionTicket ?? _authKey; await MultiStepClientLogin(result.SettingsForUser.NeedsAttribution); return new PlayFabResult<LoginResult> { Result = result, CustomData = customData }; } /// <summary> /// Signs the user in using the vendor-specific iOS device identifier, returning a session identifier that can subsequently be used for API calls which require an authenticated user /// </summary> public static async Task<PlayFabResult<LoginResult>> LoginWithIOSDeviceIDAsync(LoginWithIOSDeviceIDRequest request, object customData = null) { request.TitleId = PlayFabSettings.TitleId ?? request.TitleId; if(request.TitleId == null) throw new Exception ("Must be have PlayFabSettings.TitleId set to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/LoginWithIOSDeviceID", request, null, null); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<LoginResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<LoginResult>>(resultRawJson); var result = resultData.data; _authKey = result.SessionTicket ?? _authKey; await MultiStepClientLogin(result.SettingsForUser.NeedsAttribution); return new PlayFabResult<LoginResult> { Result = result, CustomData = customData }; } /// <summary> /// Signs the user in using a Kongregate player account. /// </summary> public static async Task<PlayFabResult<LoginResult>> LoginWithKongregateAsync(LoginWithKongregateRequest request, object customData = null) { request.TitleId = PlayFabSettings.TitleId ?? request.TitleId; if(request.TitleId == null) throw new Exception ("Must be have PlayFabSettings.TitleId set to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/LoginWithKongregate", request, null, null); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<LoginResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<LoginResult>>(resultRawJson); var result = resultData.data; _authKey = result.SessionTicket ?? _authKey; await MultiStepClientLogin(result.SettingsForUser.NeedsAttribution); return new PlayFabResult<LoginResult> { Result = result, CustomData = customData }; } /// <summary> /// Signs the user into the PlayFab account, returning a session identifier that can subsequently be used for API calls which require an authenticated user. Unlike other login API calls, LoginWithEmailAddress does not permit the creation of new accounts via the CreateAccountFlag. Email accounts must be created using the RegisterPlayFabUser API or added to existing accounts using AddUsernamePassword. /// </summary> public static async Task<PlayFabResult<LoginResult>> LoginWithPlayFabAsync(LoginWithPlayFabRequest request, object customData = null) { request.TitleId = PlayFabSettings.TitleId ?? request.TitleId; if(request.TitleId == null) throw new Exception ("Must be have PlayFabSettings.TitleId set to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/LoginWithPlayFab", request, null, null); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<LoginResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<LoginResult>>(resultRawJson); var result = resultData.data; _authKey = result.SessionTicket ?? _authKey; await MultiStepClientLogin(result.SettingsForUser.NeedsAttribution); return new PlayFabResult<LoginResult> { Result = result, CustomData = customData }; } /// <summary> /// Signs the user in using a Steam authentication ticket, returning a session identifier that can subsequently be used for API calls which require an authenticated user /// </summary> public static async Task<PlayFabResult<LoginResult>> LoginWithSteamAsync(LoginWithSteamRequest request, object customData = null) { request.TitleId = PlayFabSettings.TitleId ?? request.TitleId; if(request.TitleId == null) throw new Exception ("Must be have PlayFabSettings.TitleId set to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/LoginWithSteam", request, null, null); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<LoginResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<LoginResult>>(resultRawJson); var result = resultData.data; _authKey = result.SessionTicket ?? _authKey; await MultiStepClientLogin(result.SettingsForUser.NeedsAttribution); return new PlayFabResult<LoginResult> { Result = result, CustomData = customData }; } /// <summary> /// Signs the user in using a Twitch access token. /// </summary> public static async Task<PlayFabResult<LoginResult>> LoginWithTwitchAsync(LoginWithTwitchRequest request, object customData = null) { request.TitleId = PlayFabSettings.TitleId ?? request.TitleId; if(request.TitleId == null) throw new Exception ("Must be have PlayFabSettings.TitleId set to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/LoginWithTwitch", request, null, null); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<LoginResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<LoginResult>>(resultRawJson); var result = resultData.data; _authKey = result.SessionTicket ?? _authKey; await MultiStepClientLogin(result.SettingsForUser.NeedsAttribution); return new PlayFabResult<LoginResult> { Result = result, CustomData = customData }; } /// <summary> /// Registers a new Playfab user account, returning a session identifier that can subsequently be used for API calls which require an authenticated user. You must supply either a username or an email address. /// </summary> public static async Task<PlayFabResult<RegisterPlayFabUserResult>> RegisterPlayFabUserAsync(RegisterPlayFabUserRequest request, object customData = null) { request.TitleId = PlayFabSettings.TitleId ?? request.TitleId; if(request.TitleId == null) throw new Exception ("Must be have PlayFabSettings.TitleId set to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/RegisterPlayFabUser", request, null, null); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<RegisterPlayFabUserResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<RegisterPlayFabUserResult>>(resultRawJson); var result = resultData.data; _authKey = result.SessionTicket ?? _authKey; await MultiStepClientLogin(result.SettingsForUser.NeedsAttribution); return new PlayFabResult<RegisterPlayFabUserResult> { Result = result, CustomData = customData }; } /// <summary> /// Adds the specified generic service identifier to the player's PlayFab account. This is designed to allow for a PlayFab ID lookup of any arbitrary service identifier a title wants to add. This identifier should never be used as authentication credentials, as the intent is that it is easily accessible by other players. /// </summary> public static async Task<PlayFabResult<AddGenericIDResult>> AddGenericIDAsync(AddGenericIDRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/AddGenericID", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<AddGenericIDResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<AddGenericIDResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<AddGenericIDResult> { Result = result, CustomData = customData }; } /// <summary> /// Adds playfab username/password auth to an existing account created via an anonymous auth method, e.g. automatic device ID login. /// </summary> public static async Task<PlayFabResult<AddUsernamePasswordResult>> AddUsernamePasswordAsync(AddUsernamePasswordRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/AddUsernamePassword", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<AddUsernamePasswordResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<AddUsernamePasswordResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<AddUsernamePasswordResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves the user's PlayFab account details /// </summary> public static async Task<PlayFabResult<GetAccountInfoResult>> GetAccountInfoAsync(GetAccountInfoRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetAccountInfo", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetAccountInfoResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetAccountInfoResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetAccountInfoResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves all of the user's different kinds of info. /// </summary> public static async Task<PlayFabResult<GetPlayerCombinedInfoResult>> GetPlayerCombinedInfoAsync(GetPlayerCombinedInfoRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetPlayerCombinedInfo", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetPlayerCombinedInfoResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetPlayerCombinedInfoResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetPlayerCombinedInfoResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves the unique PlayFab identifiers for the given set of Facebook identifiers. /// </summary> public static async Task<PlayFabResult<GetPlayFabIDsFromFacebookIDsResult>> GetPlayFabIDsFromFacebookIDsAsync(GetPlayFabIDsFromFacebookIDsRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetPlayFabIDsFromFacebookIDs", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetPlayFabIDsFromFacebookIDsResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetPlayFabIDsFromFacebookIDsResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetPlayFabIDsFromFacebookIDsResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves the unique PlayFab identifiers for the given set of Game Center identifiers (referenced in the Game Center Programming Guide as the Player Identifier). /// </summary> public static async Task<PlayFabResult<GetPlayFabIDsFromGameCenterIDsResult>> GetPlayFabIDsFromGameCenterIDsAsync(GetPlayFabIDsFromGameCenterIDsRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetPlayFabIDsFromGameCenterIDs", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetPlayFabIDsFromGameCenterIDsResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetPlayFabIDsFromGameCenterIDsResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetPlayFabIDsFromGameCenterIDsResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves the unique PlayFab identifiers for the given set of generic service identifiers. A generic identifier is the service name plus the service-specific ID for the player, as specified by the title when the generic identifier was added to the player account. /// </summary> public static async Task<PlayFabResult<GetPlayFabIDsFromGenericIDsResult>> GetPlayFabIDsFromGenericIDsAsync(GetPlayFabIDsFromGenericIDsRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetPlayFabIDsFromGenericIDs", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetPlayFabIDsFromGenericIDsResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetPlayFabIDsFromGenericIDsResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetPlayFabIDsFromGenericIDsResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves the unique PlayFab identifiers for the given set of Google identifiers. The Google identifiers are the IDs for the user accounts, available as "id" in the Google+ People API calls. /// </summary> public static async Task<PlayFabResult<GetPlayFabIDsFromGoogleIDsResult>> GetPlayFabIDsFromGoogleIDsAsync(GetPlayFabIDsFromGoogleIDsRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetPlayFabIDsFromGoogleIDs", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetPlayFabIDsFromGoogleIDsResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetPlayFabIDsFromGoogleIDsResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetPlayFabIDsFromGoogleIDsResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves the unique PlayFab identifiers for the given set of Kongregate identifiers. The Kongregate identifiers are the IDs for the user accounts, available as "user_id" from the Kongregate API methods(ex: http://developers.kongregate.com/docs/client/getUserId). /// </summary> public static async Task<PlayFabResult<GetPlayFabIDsFromKongregateIDsResult>> GetPlayFabIDsFromKongregateIDsAsync(GetPlayFabIDsFromKongregateIDsRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetPlayFabIDsFromKongregateIDs", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetPlayFabIDsFromKongregateIDsResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetPlayFabIDsFromKongregateIDsResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetPlayFabIDsFromKongregateIDsResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves the unique PlayFab identifiers for the given set of Steam identifiers. The Steam identifiers are the profile IDs for the user accounts, available as SteamId in the Steamworks Community API calls. /// </summary> public static async Task<PlayFabResult<GetPlayFabIDsFromSteamIDsResult>> GetPlayFabIDsFromSteamIDsAsync(GetPlayFabIDsFromSteamIDsRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetPlayFabIDsFromSteamIDs", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetPlayFabIDsFromSteamIDsResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetPlayFabIDsFromSteamIDsResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetPlayFabIDsFromSteamIDsResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves the unique PlayFab identifiers for the given set of Twitch identifiers. The Twitch identifiers are the IDs for the user accounts, available as "_id" from the Twitch API methods (ex: https://github.com/justintv/Twitch-API/blob/master/v3_resources/users.md#get-usersuser). /// </summary> public static async Task<PlayFabResult<GetPlayFabIDsFromTwitchIDsResult>> GetPlayFabIDsFromTwitchIDsAsync(GetPlayFabIDsFromTwitchIDsRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetPlayFabIDsFromTwitchIDs", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetPlayFabIDsFromTwitchIDsResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetPlayFabIDsFromTwitchIDsResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetPlayFabIDsFromTwitchIDsResult> { Result = result, CustomData = customData }; } /// <summary> /// NOTE: This call will be deprecated soon. For fetching the data for a given user use GetPlayerCombinedInfo. For looking up users from the client api, we are in the process of adding a new api call. Once that call is ready, this one will be deprecated. Retrieves all requested data for a user in one unified request. By default, this API returns all data for the locally signed-in user. The input parameters may be used to limit the data retrieved to any subset of the available data, as well as retrieve the available data for a different user. Note that certain data, including inventory, virtual currency balances, and personally identifying information, may only be retrieved for the locally signed-in user. In the example below, a request is made for the account details, virtual currency balances, and specified user data for the locally signed-in user. /// </summary> [Obsolete("Use 'GetPlayerCombinedInfo' instead", true)] public static async Task<PlayFabResult<GetUserCombinedInfoResult>> GetUserCombinedInfoAsync(GetUserCombinedInfoRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetUserCombinedInfo", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetUserCombinedInfoResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetUserCombinedInfoResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetUserCombinedInfoResult> { Result = result, CustomData = customData }; } /// <summary> /// Links the Android device identifier to the user's PlayFab account /// </summary> public static async Task<PlayFabResult<LinkAndroidDeviceIDResult>> LinkAndroidDeviceIDAsync(LinkAndroidDeviceIDRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/LinkAndroidDeviceID", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<LinkAndroidDeviceIDResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<LinkAndroidDeviceIDResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<LinkAndroidDeviceIDResult> { Result = result, CustomData = customData }; } /// <summary> /// Links the custom identifier, generated by the title, to the user's PlayFab account /// </summary> public static async Task<PlayFabResult<LinkCustomIDResult>> LinkCustomIDAsync(LinkCustomIDRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/LinkCustomID", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<LinkCustomIDResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<LinkCustomIDResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<LinkCustomIDResult> { Result = result, CustomData = customData }; } /// <summary> /// Links the Facebook account associated with the provided Facebook access token to the user's PlayFab account /// </summary> public static async Task<PlayFabResult<LinkFacebookAccountResult>> LinkFacebookAccountAsync(LinkFacebookAccountRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/LinkFacebookAccount", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<LinkFacebookAccountResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<LinkFacebookAccountResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<LinkFacebookAccountResult> { Result = result, CustomData = customData }; } /// <summary> /// Links the Game Center account associated with the provided Game Center ID to the user's PlayFab account /// </summary> public static async Task<PlayFabResult<LinkGameCenterAccountResult>> LinkGameCenterAccountAsync(LinkGameCenterAccountRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/LinkGameCenterAccount", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<LinkGameCenterAccountResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<LinkGameCenterAccountResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<LinkGameCenterAccountResult> { Result = result, CustomData = customData }; } /// <summary> /// Links the currently signed-in user account to the Google account specified by the Google account access token (https://developers.google.com/android/reference/com/google/android/gms/auth/GoogleAuthUtil#public-methods). /// </summary> public static async Task<PlayFabResult<LinkGoogleAccountResult>> LinkGoogleAccountAsync(LinkGoogleAccountRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/LinkGoogleAccount", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<LinkGoogleAccountResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<LinkGoogleAccountResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<LinkGoogleAccountResult> { Result = result, CustomData = customData }; } /// <summary> /// Links the vendor-specific iOS device identifier to the user's PlayFab account /// </summary> public static async Task<PlayFabResult<LinkIOSDeviceIDResult>> LinkIOSDeviceIDAsync(LinkIOSDeviceIDRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/LinkIOSDeviceID", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<LinkIOSDeviceIDResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<LinkIOSDeviceIDResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<LinkIOSDeviceIDResult> { Result = result, CustomData = customData }; } /// <summary> /// Links the Kongregate identifier to the user's PlayFab account /// </summary> public static async Task<PlayFabResult<LinkKongregateAccountResult>> LinkKongregateAsync(LinkKongregateAccountRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/LinkKongregate", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<LinkKongregateAccountResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<LinkKongregateAccountResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<LinkKongregateAccountResult> { Result = result, CustomData = customData }; } /// <summary> /// Links the Steam account associated with the provided Steam authentication ticket to the user's PlayFab account /// </summary> public static async Task<PlayFabResult<LinkSteamAccountResult>> LinkSteamAccountAsync(LinkSteamAccountRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/LinkSteamAccount", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<LinkSteamAccountResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<LinkSteamAccountResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<LinkSteamAccountResult> { Result = result, CustomData = customData }; } /// <summary> /// Links the Twitch account associated with the token to the user's PlayFab account. /// </summary> public static async Task<PlayFabResult<LinkTwitchAccountResult>> LinkTwitchAsync(LinkTwitchAccountRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/LinkTwitch", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<LinkTwitchAccountResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<LinkTwitchAccountResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<LinkTwitchAccountResult> { Result = result, CustomData = customData }; } /// <summary> /// Removes the specified generic service identifier from the player's PlayFab account. /// </summary> public static async Task<PlayFabResult<RemoveGenericIDResult>> RemoveGenericIDAsync(RemoveGenericIDRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/RemoveGenericID", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<RemoveGenericIDResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<RemoveGenericIDResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<RemoveGenericIDResult> { Result = result, CustomData = customData }; } /// <summary> /// Submit a report for another player (due to bad bahavior, etc.), so that customer service representatives for the title can take action concerning potentially toxic players. /// </summary> public static async Task<PlayFabResult<ReportPlayerClientResult>> ReportPlayerAsync(ReportPlayerClientRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/ReportPlayer", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<ReportPlayerClientResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<ReportPlayerClientResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<ReportPlayerClientResult> { Result = result, CustomData = customData }; } /// <summary> /// Forces an email to be sent to the registered email address for the user's account, with a link allowing the user to change the password /// </summary> public static async Task<PlayFabResult<SendAccountRecoveryEmailResult>> SendAccountRecoveryEmailAsync(SendAccountRecoveryEmailRequest request, object customData = null) { var httpResult = await PlayFabHttp.DoPost("/Client/SendAccountRecoveryEmail", request, null, null); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<SendAccountRecoveryEmailResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<SendAccountRecoveryEmailResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<SendAccountRecoveryEmailResult> { Result = result, CustomData = customData }; } /// <summary> /// Unlinks the related Android device identifier from the user's PlayFab account /// </summary> public static async Task<PlayFabResult<UnlinkAndroidDeviceIDResult>> UnlinkAndroidDeviceIDAsync(UnlinkAndroidDeviceIDRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/UnlinkAndroidDeviceID", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<UnlinkAndroidDeviceIDResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<UnlinkAndroidDeviceIDResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<UnlinkAndroidDeviceIDResult> { Result = result, CustomData = customData }; } /// <summary> /// Unlinks the related custom identifier from the user's PlayFab account /// </summary> public static async Task<PlayFabResult<UnlinkCustomIDResult>> UnlinkCustomIDAsync(UnlinkCustomIDRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/UnlinkCustomID", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<UnlinkCustomIDResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<UnlinkCustomIDResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<UnlinkCustomIDResult> { Result = result, CustomData = customData }; } /// <summary> /// Unlinks the related Facebook account from the user's PlayFab account /// </summary> public static async Task<PlayFabResult<UnlinkFacebookAccountResult>> UnlinkFacebookAccountAsync(UnlinkFacebookAccountRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/UnlinkFacebookAccount", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<UnlinkFacebookAccountResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<UnlinkFacebookAccountResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<UnlinkFacebookAccountResult> { Result = result, CustomData = customData }; } /// <summary> /// Unlinks the related Game Center account from the user's PlayFab account /// </summary> public static async Task<PlayFabResult<UnlinkGameCenterAccountResult>> UnlinkGameCenterAccountAsync(UnlinkGameCenterAccountRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/UnlinkGameCenterAccount", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<UnlinkGameCenterAccountResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<UnlinkGameCenterAccountResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<UnlinkGameCenterAccountResult> { Result = result, CustomData = customData }; } /// <summary> /// Unlinks the related Google account from the user's PlayFab account (https://developers.google.com/android/reference/com/google/android/gms/auth/GoogleAuthUtil#public-methods). /// </summary> public static async Task<PlayFabResult<UnlinkGoogleAccountResult>> UnlinkGoogleAccountAsync(UnlinkGoogleAccountRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/UnlinkGoogleAccount", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<UnlinkGoogleAccountResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<UnlinkGoogleAccountResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<UnlinkGoogleAccountResult> { Result = result, CustomData = customData }; } /// <summary> /// Unlinks the related iOS device identifier from the user's PlayFab account /// </summary> public static async Task<PlayFabResult<UnlinkIOSDeviceIDResult>> UnlinkIOSDeviceIDAsync(UnlinkIOSDeviceIDRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/UnlinkIOSDeviceID", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<UnlinkIOSDeviceIDResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<UnlinkIOSDeviceIDResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<UnlinkIOSDeviceIDResult> { Result = result, CustomData = customData }; } /// <summary> /// Unlinks the related Kongregate identifier from the user's PlayFab account /// </summary> public static async Task<PlayFabResult<UnlinkKongregateAccountResult>> UnlinkKongregateAsync(UnlinkKongregateAccountRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/UnlinkKongregate", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<UnlinkKongregateAccountResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<UnlinkKongregateAccountResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<UnlinkKongregateAccountResult> { Result = result, CustomData = customData }; } /// <summary> /// Unlinks the related Steam account from the user's PlayFab account /// </summary> public static async Task<PlayFabResult<UnlinkSteamAccountResult>> UnlinkSteamAccountAsync(UnlinkSteamAccountRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/UnlinkSteamAccount", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<UnlinkSteamAccountResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<UnlinkSteamAccountResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<UnlinkSteamAccountResult> { Result = result, CustomData = customData }; } /// <summary> /// Unlinks the related Twitch account from the user's PlayFab account. /// </summary> public static async Task<PlayFabResult<UnlinkTwitchAccountResult>> UnlinkTwitchAsync(UnlinkTwitchAccountRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/UnlinkTwitch", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<UnlinkTwitchAccountResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<UnlinkTwitchAccountResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<UnlinkTwitchAccountResult> { Result = result, CustomData = customData }; } /// <summary> /// Updates the title specific display name for the user /// </summary> public static async Task<PlayFabResult<UpdateUserTitleDisplayNameResult>> UpdateUserTitleDisplayNameAsync(UpdateUserTitleDisplayNameRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/UpdateUserTitleDisplayName", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<UpdateUserTitleDisplayNameResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<UpdateUserTitleDisplayNameResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<UpdateUserTitleDisplayNameResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves a list of ranked friends of the current player for the given statistic, starting from the indicated point in the leaderboard /// </summary> public static async Task<PlayFabResult<GetLeaderboardResult>> GetFriendLeaderboardAsync(GetFriendLeaderboardRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetFriendLeaderboard", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetLeaderboardResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetLeaderboardResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetLeaderboardResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves a list of ranked friends of the current player for the given statistic, centered on the requested PlayFab user. If PlayFabId is empty or null will return currently logged in user. /// </summary> public static async Task<PlayFabResult<GetFriendLeaderboardAroundPlayerResult>> GetFriendLeaderboardAroundPlayerAsync(GetFriendLeaderboardAroundPlayerRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetFriendLeaderboardAroundPlayer", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetFriendLeaderboardAroundPlayerResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetFriendLeaderboardAroundPlayerResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetFriendLeaderboardAroundPlayerResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves a list of ranked users for the given statistic, starting from the indicated point in the leaderboard /// </summary> public static async Task<PlayFabResult<GetLeaderboardResult>> GetLeaderboardAsync(GetLeaderboardRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetLeaderboard", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetLeaderboardResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetLeaderboardResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetLeaderboardResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves a list of ranked users for the given statistic, centered on the requested player. If PlayFabId is empty or null will return currently logged in user. /// </summary> public static async Task<PlayFabResult<GetLeaderboardAroundPlayerResult>> GetLeaderboardAroundPlayerAsync(GetLeaderboardAroundPlayerRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetLeaderboardAroundPlayer", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetLeaderboardAroundPlayerResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetLeaderboardAroundPlayerResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetLeaderboardAroundPlayerResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves the indicated statistics (current version and values for all statistics, if none are specified), for the local player. /// </summary> public static async Task<PlayFabResult<GetPlayerStatisticsResult>> GetPlayerStatisticsAsync(GetPlayerStatisticsRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetPlayerStatistics", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetPlayerStatisticsResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetPlayerStatisticsResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetPlayerStatisticsResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves the information on the available versions of the specified statistic. /// </summary> public static async Task<PlayFabResult<GetPlayerStatisticVersionsResult>> GetPlayerStatisticVersionsAsync(GetPlayerStatisticVersionsRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetPlayerStatisticVersions", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetPlayerStatisticVersionsResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetPlayerStatisticVersionsResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetPlayerStatisticVersionsResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves the title-specific custom data for the user which is readable and writable by the client /// </summary> public static async Task<PlayFabResult<GetUserDataResult>> GetUserDataAsync(GetUserDataRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetUserData", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetUserDataResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetUserDataResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetUserDataResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves the publisher-specific custom data for the user which is readable and writable by the client /// </summary> public static async Task<PlayFabResult<GetUserDataResult>> GetUserPublisherDataAsync(GetUserDataRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetUserPublisherData", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetUserDataResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetUserDataResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetUserDataResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves the publisher-specific custom data for the user which can only be read by the client /// </summary> public static async Task<PlayFabResult<GetUserDataResult>> GetUserPublisherReadOnlyDataAsync(GetUserDataRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetUserPublisherReadOnlyData", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetUserDataResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetUserDataResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetUserDataResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves the title-specific custom data for the user which can only be read by the client /// </summary> public static async Task<PlayFabResult<GetUserDataResult>> GetUserReadOnlyDataAsync(GetUserDataRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetUserReadOnlyData", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetUserDataResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetUserDataResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetUserDataResult> { Result = result, CustomData = customData }; } /// <summary> /// Updates the values of the specified title-specific statistics for the user. By default, clients are not permitted to update statistics. Developers may override this setting in the Game Manager > Settings > API Features. /// </summary> public static async Task<PlayFabResult<UpdatePlayerStatisticsResult>> UpdatePlayerStatisticsAsync(UpdatePlayerStatisticsRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/UpdatePlayerStatistics", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<UpdatePlayerStatisticsResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<UpdatePlayerStatisticsResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<UpdatePlayerStatisticsResult> { Result = result, CustomData = customData }; } /// <summary> /// Creates and updates the title-specific custom data for the user which is readable and writable by the client /// </summary> public static async Task<PlayFabResult<UpdateUserDataResult>> UpdateUserDataAsync(UpdateUserDataRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/UpdateUserData", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<UpdateUserDataResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<UpdateUserDataResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<UpdateUserDataResult> { Result = result, CustomData = customData }; } /// <summary> /// Creates and updates the publisher-specific custom data for the user which is readable and writable by the client /// </summary> public static async Task<PlayFabResult<UpdateUserDataResult>> UpdateUserPublisherDataAsync(UpdateUserDataRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/UpdateUserPublisherData", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<UpdateUserDataResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<UpdateUserDataResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<UpdateUserDataResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves the specified version of the title's catalog of virtual goods, including all defined properties /// </summary> public static async Task<PlayFabResult<GetCatalogItemsResult>> GetCatalogItemsAsync(GetCatalogItemsRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetCatalogItems", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetCatalogItemsResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetCatalogItemsResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetCatalogItemsResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves the key-value store of custom publisher settings /// </summary> public static async Task<PlayFabResult<GetPublisherDataResult>> GetPublisherDataAsync(GetPublisherDataRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetPublisherData", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetPublisherDataResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetPublisherDataResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetPublisherDataResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves the set of items defined for the specified store, including all prices defined /// </summary> public static async Task<PlayFabResult<GetStoreItemsResult>> GetStoreItemsAsync(GetStoreItemsRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetStoreItems", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetStoreItemsResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetStoreItemsResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetStoreItemsResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves the current server time /// </summary> public static async Task<PlayFabResult<GetTimeResult>> GetTimeAsync(GetTimeRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetTime", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetTimeResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetTimeResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetTimeResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves the key-value store of custom title settings /// </summary> public static async Task<PlayFabResult<GetTitleDataResult>> GetTitleDataAsync(GetTitleDataRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetTitleData", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetTitleDataResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetTitleDataResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetTitleDataResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves the title news feed, as configured in the developer portal /// </summary> public static async Task<PlayFabResult<GetTitleNewsResult>> GetTitleNewsAsync(GetTitleNewsRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetTitleNews", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetTitleNewsResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetTitleNewsResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetTitleNewsResult> { Result = result, CustomData = customData }; } /// <summary> /// Increments the user's balance of the specified virtual currency by the stated amount /// </summary> public static async Task<PlayFabResult<ModifyUserVirtualCurrencyResult>> AddUserVirtualCurrencyAsync(AddUserVirtualCurrencyRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/AddUserVirtualCurrency", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<ModifyUserVirtualCurrencyResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<ModifyUserVirtualCurrencyResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<ModifyUserVirtualCurrencyResult> { Result = result, CustomData = customData }; } /// <summary> /// Confirms with the payment provider that the purchase was approved (if applicable) and adjusts inventory and virtual currency balances as appropriate /// </summary> public static async Task<PlayFabResult<ConfirmPurchaseResult>> ConfirmPurchaseAsync(ConfirmPurchaseRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/ConfirmPurchase", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<ConfirmPurchaseResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<ConfirmPurchaseResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<ConfirmPurchaseResult> { Result = result, CustomData = customData }; } /// <summary> /// Consume uses of a consumable item. When all uses are consumed, it will be removed from the player's inventory. /// </summary> public static async Task<PlayFabResult<ConsumeItemResult>> ConsumeItemAsync(ConsumeItemRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/ConsumeItem", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<ConsumeItemResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<ConsumeItemResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<ConsumeItemResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves the specified character's current inventory of virtual goods /// </summary> public static async Task<PlayFabResult<GetCharacterInventoryResult>> GetCharacterInventoryAsync(GetCharacterInventoryRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetCharacterInventory", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetCharacterInventoryResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetCharacterInventoryResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetCharacterInventoryResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves a completed purchase along with its current PlayFab status. /// </summary> public static async Task<PlayFabResult<GetPurchaseResult>> GetPurchaseAsync(GetPurchaseRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetPurchase", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetPurchaseResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetPurchaseResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetPurchaseResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves the user's current inventory of virtual goods /// </summary> public static async Task<PlayFabResult<GetUserInventoryResult>> GetUserInventoryAsync(GetUserInventoryRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetUserInventory", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetUserInventoryResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetUserInventoryResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetUserInventoryResult> { Result = result, CustomData = customData }; } /// <summary> /// Selects a payment option for purchase order created via StartPurchase /// </summary> public static async Task<PlayFabResult<PayForPurchaseResult>> PayForPurchaseAsync(PayForPurchaseRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/PayForPurchase", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<PayForPurchaseResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<PayForPurchaseResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<PayForPurchaseResult> { Result = result, CustomData = customData }; } /// <summary> /// Buys a single item with virtual currency. You must specify both the virtual currency to use to purchase, as well as what the client believes the price to be. This lets the server fail the purchase if the price has changed. /// </summary> public static async Task<PlayFabResult<PurchaseItemResult>> PurchaseItemAsync(PurchaseItemRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/PurchaseItem", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<PurchaseItemResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<PurchaseItemResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<PurchaseItemResult> { Result = result, CustomData = customData }; } /// <summary> /// Adds the virtual goods associated with the coupon to the user's inventory. Coupons can be generated via the Economy->Catalogs tab in the PlayFab Game Manager. /// </summary> public static async Task<PlayFabResult<RedeemCouponResult>> RedeemCouponAsync(RedeemCouponRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/RedeemCoupon", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<RedeemCouponResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<RedeemCouponResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<RedeemCouponResult> { Result = result, CustomData = customData }; } /// <summary> /// Creates an order for a list of items from the title catalog /// </summary> public static async Task<PlayFabResult<StartPurchaseResult>> StartPurchaseAsync(StartPurchaseRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/StartPurchase", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<StartPurchaseResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<StartPurchaseResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<StartPurchaseResult> { Result = result, CustomData = customData }; } /// <summary> /// Decrements the user's balance of the specified virtual currency by the stated amount /// </summary> public static async Task<PlayFabResult<ModifyUserVirtualCurrencyResult>> SubtractUserVirtualCurrencyAsync(SubtractUserVirtualCurrencyRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/SubtractUserVirtualCurrency", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<ModifyUserVirtualCurrencyResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<ModifyUserVirtualCurrencyResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<ModifyUserVirtualCurrencyResult> { Result = result, CustomData = customData }; } /// <summary> /// Opens the specified container, with the specified key (when required), and returns the contents of the opened container. If the container (and key when relevant) are consumable (RemainingUses > 0), their RemainingUses will be decremented, consistent with the operation of ConsumeItem. /// </summary> public static async Task<PlayFabResult<UnlockContainerItemResult>> UnlockContainerInstanceAsync(UnlockContainerInstanceRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/UnlockContainerInstance", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<UnlockContainerItemResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<UnlockContainerItemResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<UnlockContainerItemResult> { Result = result, CustomData = customData }; } /// <summary> /// Searches target inventory for an ItemInstance matching the given CatalogItemId, if necessary unlocks it using an appropriate key, and returns the contents of the opened container. If the container (and key when relevant) are consumable (RemainingUses > 0), their RemainingUses will be decremented, consistent with the operation of ConsumeItem. /// </summary> public static async Task<PlayFabResult<UnlockContainerItemResult>> UnlockContainerItemAsync(UnlockContainerItemRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/UnlockContainerItem", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<UnlockContainerItemResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<UnlockContainerItemResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<UnlockContainerItemResult> { Result = result, CustomData = customData }; } /// <summary> /// Adds the PlayFab user, based upon a match against a supplied unique identifier, to the friend list of the local user. At least one of FriendPlayFabId,FriendUsername,FriendEmail, or FriendTitleDisplayName should be initialized. /// </summary> public static async Task<PlayFabResult<AddFriendResult>> AddFriendAsync(AddFriendRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/AddFriend", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<AddFriendResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<AddFriendResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<AddFriendResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves the current friend list for the local user, constrained to users who have PlayFab accounts. Friends from linked accounts (Facebook, Steam) are also included. You may optionally exclude some linked services' friends. /// </summary> public static async Task<PlayFabResult<GetFriendsListResult>> GetFriendsListAsync(GetFriendsListRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetFriendsList", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetFriendsListResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetFriendsListResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetFriendsListResult> { Result = result, CustomData = customData }; } /// <summary> /// Removes a specified user from the friend list of the local user /// </summary> public static async Task<PlayFabResult<RemoveFriendResult>> RemoveFriendAsync(RemoveFriendRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/RemoveFriend", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<RemoveFriendResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<RemoveFriendResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<RemoveFriendResult> { Result = result, CustomData = customData }; } /// <summary> /// Updates the tag list for a specified user in the friend list of the local user /// </summary> public static async Task<PlayFabResult<SetFriendTagsResult>> SetFriendTagsAsync(SetFriendTagsRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/SetFriendTags", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<SetFriendTagsResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<SetFriendTagsResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<SetFriendTagsResult> { Result = result, CustomData = customData }; } /// <summary> /// Registers the iOS device to receive push notifications /// </summary> public static async Task<PlayFabResult<RegisterForIOSPushNotificationResult>> RegisterForIOSPushNotificationAsync(RegisterForIOSPushNotificationRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/RegisterForIOSPushNotification", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<RegisterForIOSPushNotificationResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<RegisterForIOSPushNotificationResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<RegisterForIOSPushNotificationResult> { Result = result, CustomData = customData }; } /// <summary> /// Restores all in-app purchases based on the given refresh receipt. /// </summary> public static async Task<PlayFabResult<RestoreIOSPurchasesResult>> RestoreIOSPurchasesAsync(RestoreIOSPurchasesRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/RestoreIOSPurchases", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<RestoreIOSPurchasesResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<RestoreIOSPurchasesResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<RestoreIOSPurchasesResult> { Result = result, CustomData = customData }; } /// <summary> /// Validates with the Apple store that the receipt for an iOS in-app purchase is valid and that it matches the purchased catalog item /// </summary> public static async Task<PlayFabResult<ValidateIOSReceiptResult>> ValidateIOSReceiptAsync(ValidateIOSReceiptRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/ValidateIOSReceipt", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<ValidateIOSReceiptResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<ValidateIOSReceiptResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<ValidateIOSReceiptResult> { Result = result, CustomData = customData }; } /// <summary> /// Get details about all current running game servers matching the given parameters. /// </summary> public static async Task<PlayFabResult<CurrentGamesResult>> GetCurrentGamesAsync(CurrentGamesRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetCurrentGames", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<CurrentGamesResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<CurrentGamesResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<CurrentGamesResult> { Result = result, CustomData = customData }; } /// <summary> /// Get details about the regions hosting game servers matching the given parameters. /// </summary> public static async Task<PlayFabResult<GameServerRegionsResult>> GetGameServerRegionsAsync(GameServerRegionsRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetGameServerRegions", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GameServerRegionsResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GameServerRegionsResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GameServerRegionsResult> { Result = result, CustomData = customData }; } /// <summary> /// Attempts to locate a game session matching the given parameters. If the goal is to match the player into a specific active session, only the LobbyId is required. Otherwise, the BuildVersion, GameMode, and Region are all required parameters. Note that parameters specified in the search are required (they are not weighting factors). If a slot is found in a server instance matching the parameters, the slot will be assigned to that player, removing it from the availabe set. In that case, the information on the game session will be returned, otherwise the Status returned will be GameNotFound. Note that EnableQueue is deprecated at this time. /// </summary> public static async Task<PlayFabResult<MatchmakeResult>> MatchmakeAsync(MatchmakeRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/Matchmake", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<MatchmakeResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<MatchmakeResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<MatchmakeResult> { Result = result, CustomData = customData }; } /// <summary> /// Start a new game server with a given configuration, add the current player and return the connection information. /// </summary> public static async Task<PlayFabResult<StartGameResult>> StartGameAsync(StartGameRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/StartGame", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<StartGameResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<StartGameResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<StartGameResult> { Result = result, CustomData = customData }; } /// <summary> /// Registers the Android device to receive push notifications /// </summary> public static async Task<PlayFabResult<AndroidDevicePushNotificationRegistrationResult>> AndroidDevicePushNotificationRegistrationAsync(AndroidDevicePushNotificationRegistrationRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/AndroidDevicePushNotificationRegistration", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<AndroidDevicePushNotificationRegistrationResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<AndroidDevicePushNotificationRegistrationResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<AndroidDevicePushNotificationRegistrationResult> { Result = result, CustomData = customData }; } /// <summary> /// Validates a Google Play purchase and gives the corresponding item to the player. /// </summary> public static async Task<PlayFabResult<ValidateGooglePlayPurchaseResult>> ValidateGooglePlayPurchaseAsync(ValidateGooglePlayPurchaseRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/ValidateGooglePlayPurchase", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<ValidateGooglePlayPurchaseResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<ValidateGooglePlayPurchaseResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<ValidateGooglePlayPurchaseResult> { Result = result, CustomData = customData }; } /// <summary> /// Writes a character-based event into PlayStream. /// </summary> public static async Task<PlayFabResult<WriteEventResponse>> WriteCharacterEventAsync(WriteClientCharacterEventRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/WriteCharacterEvent", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<WriteEventResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<WriteEventResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<WriteEventResponse> { Result = result, CustomData = customData }; } /// <summary> /// Writes a player-based event into PlayStream. /// </summary> public static async Task<PlayFabResult<WriteEventResponse>> WritePlayerEventAsync(WriteClientPlayerEventRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/WritePlayerEvent", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<WriteEventResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<WriteEventResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<WriteEventResponse> { Result = result, CustomData = customData }; } /// <summary> /// Writes a title-based event into PlayStream. /// </summary> public static async Task<PlayFabResult<WriteEventResponse>> WriteTitleEventAsync(WriteTitleEventRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/WriteTitleEvent", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<WriteEventResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<WriteEventResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<WriteEventResponse> { Result = result, CustomData = customData }; } /// <summary> /// Adds users to the set of those able to update both the shared data, as well as the set of users in the group. Only users in the group can add new members. /// </summary> public static async Task<PlayFabResult<AddSharedGroupMembersResult>> AddSharedGroupMembersAsync(AddSharedGroupMembersRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/AddSharedGroupMembers", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<AddSharedGroupMembersResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<AddSharedGroupMembersResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<AddSharedGroupMembersResult> { Result = result, CustomData = customData }; } /// <summary> /// Requests the creation of a shared group object, containing key/value pairs which may be updated by all members of the group. Upon creation, the current user will be the only member of the group. /// </summary> public static async Task<PlayFabResult<CreateSharedGroupResult>> CreateSharedGroupAsync(CreateSharedGroupRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/CreateSharedGroup", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<CreateSharedGroupResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<CreateSharedGroupResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<CreateSharedGroupResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves data stored in a shared group object, as well as the list of members in the group. Non-members of the group may use this to retrieve group data, including membership, but they will not receive data for keys marked as private. /// </summary> public static async Task<PlayFabResult<GetSharedGroupDataResult>> GetSharedGroupDataAsync(GetSharedGroupDataRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetSharedGroupData", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetSharedGroupDataResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetSharedGroupDataResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetSharedGroupDataResult> { Result = result, CustomData = customData }; } /// <summary> /// Removes users from the set of those able to update the shared data and the set of users in the group. Only users in the group can remove members. If as a result of the call, zero users remain with access, the group and its associated data will be deleted. /// </summary> public static async Task<PlayFabResult<RemoveSharedGroupMembersResult>> RemoveSharedGroupMembersAsync(RemoveSharedGroupMembersRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/RemoveSharedGroupMembers", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<RemoveSharedGroupMembersResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<RemoveSharedGroupMembersResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<RemoveSharedGroupMembersResult> { Result = result, CustomData = customData }; } /// <summary> /// Adds, updates, and removes data keys for a shared group object. If the permission is set to Public, all fields updated or added in this call will be readable by users not in the group. By default, data permissions are set to Private. Regardless of the permission setting, only members of the group can update the data. /// </summary> public static async Task<PlayFabResult<UpdateSharedGroupDataResult>> UpdateSharedGroupDataAsync(UpdateSharedGroupDataRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/UpdateSharedGroupData", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<UpdateSharedGroupDataResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<UpdateSharedGroupDataResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<UpdateSharedGroupDataResult> { Result = result, CustomData = customData }; } /// <summary> /// Executes a CloudScript function, with the 'currentPlayerId' set to the PlayFab ID of the authenticated player. /// </summary> public static async Task<PlayFabResult<ExecuteCloudScriptResult>> ExecuteCloudScriptAsync(ExecuteCloudScriptRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/ExecuteCloudScript", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<ExecuteCloudScriptResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<ExecuteCloudScriptResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<ExecuteCloudScriptResult> { Result = result, CustomData = customData }; } /// <summary> /// This API retrieves a pre-signed URL for accessing a content file for the title. A subsequent HTTP GET to the returned URL will attempt to download the content. A HEAD query to the returned URL will attempt to retrieve the metadata of the content. Note that a successful result does not guarantee the existence of this content - if it has not been uploaded, the query to retrieve the data will fail. See this post for more information: https://community.playfab.com/hc/en-us/community/posts/205469488-How-to-upload-files-to-PlayFab-s-Content-Service /// </summary> public static async Task<PlayFabResult<GetContentDownloadUrlResult>> GetContentDownloadUrlAsync(GetContentDownloadUrlRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetContentDownloadUrl", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetContentDownloadUrlResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetContentDownloadUrlResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetContentDownloadUrlResult> { Result = result, CustomData = customData }; } /// <summary> /// Lists all of the characters that belong to a specific user. CharacterIds are not globally unique; characterId must be evaluated with the parent PlayFabId to guarantee uniqueness. /// </summary> public static async Task<PlayFabResult<ListUsersCharactersResult>> GetAllUsersCharactersAsync(ListUsersCharactersRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetAllUsersCharacters", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<ListUsersCharactersResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<ListUsersCharactersResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<ListUsersCharactersResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves a list of ranked characters for the given statistic, starting from the indicated point in the leaderboard /// </summary> public static async Task<PlayFabResult<GetCharacterLeaderboardResult>> GetCharacterLeaderboardAsync(GetCharacterLeaderboardRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetCharacterLeaderboard", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetCharacterLeaderboardResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetCharacterLeaderboardResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetCharacterLeaderboardResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves the details of all title-specific statistics for the user /// </summary> public static async Task<PlayFabResult<GetCharacterStatisticsResult>> GetCharacterStatisticsAsync(GetCharacterStatisticsRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetCharacterStatistics", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetCharacterStatisticsResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetCharacterStatisticsResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetCharacterStatisticsResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves a list of ranked characters for the given statistic, centered on the requested Character ID /// </summary> public static async Task<PlayFabResult<GetLeaderboardAroundCharacterResult>> GetLeaderboardAroundCharacterAsync(GetLeaderboardAroundCharacterRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetLeaderboardAroundCharacter", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetLeaderboardAroundCharacterResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetLeaderboardAroundCharacterResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetLeaderboardAroundCharacterResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves a list of all of the user's characters for the given statistic. /// </summary> public static async Task<PlayFabResult<GetLeaderboardForUsersCharactersResult>> GetLeaderboardForUserCharactersAsync(GetLeaderboardForUsersCharactersRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetLeaderboardForUserCharacters", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetLeaderboardForUsersCharactersResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetLeaderboardForUsersCharactersResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetLeaderboardForUsersCharactersResult> { Result = result, CustomData = customData }; } /// <summary> /// Grants the specified character type to the user. CharacterIds are not globally unique; characterId must be evaluated with the parent PlayFabId to guarantee uniqueness. /// </summary> public static async Task<PlayFabResult<GrantCharacterToUserResult>> GrantCharacterToUserAsync(GrantCharacterToUserRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GrantCharacterToUser", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GrantCharacterToUserResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GrantCharacterToUserResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GrantCharacterToUserResult> { Result = result, CustomData = customData }; } /// <summary> /// Updates the values of the specified title-specific statistics for the specific character. By default, clients are not permitted to update statistics. Developers may override this setting in the Game Manager > Settings > API Features. /// </summary> public static async Task<PlayFabResult<UpdateCharacterStatisticsResult>> UpdateCharacterStatisticsAsync(UpdateCharacterStatisticsRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/UpdateCharacterStatistics", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<UpdateCharacterStatisticsResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<UpdateCharacterStatisticsResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<UpdateCharacterStatisticsResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves the title-specific custom data for the character which is readable and writable by the client /// </summary> public static async Task<PlayFabResult<GetCharacterDataResult>> GetCharacterDataAsync(GetCharacterDataRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetCharacterData", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetCharacterDataResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetCharacterDataResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetCharacterDataResult> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves the title-specific custom data for the character which can only be read by the client /// </summary> public static async Task<PlayFabResult<GetCharacterDataResult>> GetCharacterReadOnlyDataAsync(GetCharacterDataRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetCharacterReadOnlyData", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetCharacterDataResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetCharacterDataResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetCharacterDataResult> { Result = result, CustomData = customData }; } /// <summary> /// Creates and updates the title-specific custom data for the user's character which is readable and writable by the client /// </summary> public static async Task<PlayFabResult<UpdateCharacterDataResult>> UpdateCharacterDataAsync(UpdateCharacterDataRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/UpdateCharacterData", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<UpdateCharacterDataResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<UpdateCharacterDataResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<UpdateCharacterDataResult> { Result = result, CustomData = customData }; } /// <summary> /// Validates with Amazon that the receipt for an Amazon App Store in-app purchase is valid and that it matches the purchased catalog item /// </summary> public static async Task<PlayFabResult<ValidateAmazonReceiptResult>> ValidateAmazonIAPReceiptAsync(ValidateAmazonReceiptRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/ValidateAmazonIAPReceipt", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<ValidateAmazonReceiptResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<ValidateAmazonReceiptResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<ValidateAmazonReceiptResult> { Result = result, CustomData = customData }; } /// <summary> /// Accepts an open trade. If the call is successful, the offered and accepted items will be swapped between the two players' inventories. /// </summary> public static async Task<PlayFabResult<AcceptTradeResponse>> AcceptTradeAsync(AcceptTradeRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/AcceptTrade", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<AcceptTradeResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<AcceptTradeResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<AcceptTradeResponse> { Result = result, CustomData = customData }; } /// <summary> /// Cancels an open trade. /// </summary> public static async Task<PlayFabResult<CancelTradeResponse>> CancelTradeAsync(CancelTradeRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/CancelTrade", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<CancelTradeResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<CancelTradeResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<CancelTradeResponse> { Result = result, CustomData = customData }; } /// <summary> /// Gets all trades the player has either opened or accepted, optionally filtered by trade status. /// </summary> public static async Task<PlayFabResult<GetPlayerTradesResponse>> GetPlayerTradesAsync(GetPlayerTradesRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetPlayerTrades", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetPlayerTradesResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetPlayerTradesResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetPlayerTradesResponse> { Result = result, CustomData = customData }; } /// <summary> /// Gets the current status of an existing trade. /// </summary> public static async Task<PlayFabResult<GetTradeStatusResponse>> GetTradeStatusAsync(GetTradeStatusRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetTradeStatus", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetTradeStatusResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetTradeStatusResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetTradeStatusResponse> { Result = result, CustomData = customData }; } /// <summary> /// Opens a new outstanding trade. /// </summary> public static async Task<PlayFabResult<OpenTradeResponse>> OpenTradeAsync(OpenTradeRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/OpenTrade", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<OpenTradeResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<OpenTradeResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<OpenTradeResponse> { Result = result, CustomData = customData }; } /// <summary> /// Attributes an install for advertisment. /// </summary> public static async Task<PlayFabResult<AttributeInstallResult>> AttributeInstallAsync(AttributeInstallRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/AttributeInstall", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<AttributeInstallResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<AttributeInstallResult>>(resultRawJson); var result = resultData.data; // Modify AdvertisingIdType: Prevents us from sending the id multiple times, and allows automated tests to determine id was sent successfully PlayFabSettings.AdvertisingIdType += "_Successful"; return new PlayFabResult<AttributeInstallResult> { Result = result, CustomData = customData }; } /// <summary> /// List all segments that a player currently belongs to at this moment in time. /// </summary> public static async Task<PlayFabResult<GetPlayerSegmentsResult>> GetPlayerSegmentsAsync(GetPlayerSegmentsRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetPlayerSegments", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetPlayerSegmentsResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetPlayerSegmentsResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetPlayerSegmentsResult> { Result = result, CustomData = customData }; } /// <summary> /// Get all tags with a given Namespace (optional) from a player profile. /// </summary> public static async Task<PlayFabResult<GetPlayerTagsResult>> GetPlayerTagsAsync(GetPlayerTagsRequest request, object customData = null) { if (_authKey == null) throw new Exception ("Must be logged in to call this method"); var httpResult = await PlayFabHttp.DoPost("/Client/GetPlayerTags", request, "X-Authorization", _authKey); if(httpResult is PlayFabError) { var error = (PlayFabError)httpResult; if (PlayFabSettings.GlobalErrorHandler != null) PlayFabSettings.GlobalErrorHandler(error); return new PlayFabResult<GetPlayerTagsResult> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = JsonWrapper.DeserializeObject<PlayFabJsonSuccess<GetPlayerTagsResult>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetPlayerTagsResult> { Result = result, CustomData = customData }; } private static string _authKey; // Determine if the _authKey is set, without actually making it public public static bool IsClientLoggedIn() { return !string.IsNullOrEmpty(_authKey); } private static async Task<PlayFabResult<AttributeInstallResult>> MultiStepClientLogin(bool needsAttribution) { if (needsAttribution && !PlayFabSettings.DisableAdvertising && !string.IsNullOrEmpty(PlayFabSettings.AdvertisingIdType) && !string.IsNullOrEmpty(PlayFabSettings.AdvertisingIdValue)) { var request = new AttributeInstallRequest(); if (PlayFabSettings.AdvertisingIdType == PlayFabSettings.AD_TYPE_IDFA) request.Idfa = PlayFabSettings.AdvertisingIdValue; else if (PlayFabSettings.AdvertisingIdType == PlayFabSettings.AD_TYPE_ANDROID_ID) request.Adid = PlayFabSettings.AdvertisingIdValue; else return null; return await AttributeInstallAsync(request); } return null; } } }
namespace Bakery { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Startup { static void Main(string[] args) { var ctx = new BakeryContext(); var products = ctx.Products .Where(CheckDistributor) .ToList(); products.ForEach(p => Console.WriteLine(p.Name)); } static bool CheckDistributor(Product p) { var distributorId = p.Ingredients .FirstOrDefault() .DistributorId; return p.Ingredients.All(i => i.DistributorId == distributorId); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; namespace ClaimDi.DataAccess.Entity { public class ClaimCauseOfLoss { public int Id { get; set; } public string TaskId { get; set; } public string CauseId { get; set; } public DateTime? CreateDate { get; set; } public DateTime? UpdateDate { get; set; } public string CreateBy { get; set; } public string UpdateBy { get; set; } public virtual CauseOfLoss CauseOfLoss { get; set; } } public class ClaimCauseOfLossConfig : EntityTypeConfiguration<ClaimCauseOfLoss> { public ClaimCauseOfLossConfig() { // Table & Column Mappings ToTable("ClaimCauseOfLoss"); Property(t => t.Id).HasColumnName("id").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); ; Property(t => t.TaskId).HasColumnName("task_Id"); Property(t => t.CauseId).HasColumnName("cause_Id"); Property(t => t.CreateDate).HasColumnName("create_date"); Property(t => t.UpdateDate).HasColumnName("update_date"); Property(t => t.CreateBy).HasColumnName("create_by"); Property(t => t.UpdateBy).HasColumnName("update_by"); // Primary Key HasKey(t => t.Id); HasOptional(t => t.CauseOfLoss).WithMany().HasForeignKey(f => f.CauseId); } } }
using System.Data; using System.Web.Mvc; using com.Sconit.Web.Util; using Telerik.Web.Mvc; using com.Sconit.Web.Models.SearchModels.SI.SAP; using System.Data.SqlClient; using System; using System.Linq; using com.Sconit.Web.Models; using System.Collections.Generic; using com.Sconit.Entity.SAP.TRANS; using com.Sconit.Service; using System.ComponentModel; using System.Reflection; using com.Sconit.Entity.SAP.ORD; namespace com.Sconit.Web.Controllers.SI.SAP { public class SAPPostDOController : WebAppBaseController { // // GET: /SequenceOrder/ private static string selectCountStatement = "select count(*) from PostDO as p"; /// <summary> /// /// </summary> private static string selectStatement = "select p from PostDO as p"; public SAPPostDOController() { } //public IQueryMgr siMgr { get { return GetService<IQueryMgr>("siMgr"); } } [SconitAuthorize(Permissions = "Url_SI_SAP_PostDO_View")] public ActionResult Index() { return View(); } [GridAction] [SconitAuthorize(Permissions = "Url_SI_SAP_PostDO_View")] public ActionResult List(GridCommand command, PostDOSearchModel searchModel) { TempData["PostDOSearchModel"] = searchModel; ViewBag.PageSize = 20; return View(); } [GridAction(EnableCustomBinding = true)] [SconitAuthorize(Permissions = "Url_SI_SAP_PostDO_View")] public ActionResult _AjaxList(GridCommand command, PostDOSearchModel searchModel) { SearchStatementModel searchStatementModel = PrepareSearchStatement(command, searchModel); GridModel<PostDO> gridlist = GetAjaxPageData<PostDO>(searchStatementModel, command); foreach (PostDO inv in gridlist.Data) { inv.StatusName = GetEnumDescription(inv.Status); } return PartialView(gridlist); //return PartialView(GetAjaxPageData<ReceiptMaster>(searchStatementModel, command)); } private SearchStatementModel PrepareSearchStatement(GridCommand command, PostDOSearchModel searchModel) { string whereStatement = ""; IList<object> param = new List<object>(); HqlStatementHelper.AddLikeStatement("OrderNo", searchModel.OrderNo, HqlStatementHelper.LikeMatchMode.Start, "p", ref whereStatement, param); HqlStatementHelper.AddLikeStatement("ReceiptNo", searchModel.ReceiptNo, HqlStatementHelper.LikeMatchMode.Start, "p", ref whereStatement, param); HqlStatementHelper.AddEqStatement("Status", searchModel.Status, "p", ref whereStatement, param); if (searchModel.StartDate != null & searchModel.EndDate != null) { HqlStatementHelper.AddBetweenStatement("CreateDate", searchModel.StartDate, searchModel.EndDate, "p", ref whereStatement, param); } else if (searchModel.StartDate != null & searchModel.EndDate == null) { HqlStatementHelper.AddGeStatement("CreateDate", searchModel.StartDate, "p", ref whereStatement, param); } else if (searchModel.StartDate == null & searchModel.EndDate != null) { HqlStatementHelper.AddLeStatement("CreateDate", searchModel.EndDate, "p", ref whereStatement, param); } string sortingStatement = HqlStatementHelper.GetSortingStatement(command.SortDescriptors); if (command.SortDescriptors.Count == 0) { sortingStatement = " order by p.CreateDate desc"; } SearchStatementModel searchStatementModel = new SearchStatementModel(); searchStatementModel.SelectCountStatement = selectCountStatement; searchStatementModel.SelectStatement = selectStatement; searchStatementModel.WhereStatement = whereStatement; searchStatementModel.SortingStatement = sortingStatement; searchStatementModel.Parameters = param.ToArray<object>(); return searchStatementModel; } public static string GetEnumDescription(object enumSubitem) { enumSubitem = (Enum)enumSubitem; string strValue = enumSubitem.ToString(); FieldInfo fieldinfo = enumSubitem.GetType().GetField(strValue); if (fieldinfo != null) { Object[] objs = fieldinfo.GetCustomAttributes(typeof(DescriptionAttribute), false); if (objs == null || objs.Length == 0) { return strValue; } else { DescriptionAttribute da = (DescriptionAttribute)objs[0]; return da.Description; } } else { return "未找到的状态"; } } } }
// <copyright file="IndexData.cs" company="WaterTrans"> // © 2020 WaterTrans // </copyright> using System.Collections.Generic; namespace WaterTrans.GlyphLoader.Internal.OpenType.CFF { /// <summary> /// The Compact FontFormat Specification INDEX Data. /// </summary> internal class IndexData { /// <summary> /// Initializes a new instance of the <see cref="IndexData"/> class. /// </summary> /// <param name="reader">The <see cref="TypefaceReader"/>.</param> internal IndexData(TypefaceReader reader) { Count = reader.ReadUInt16(); if (Count == 0) { return; } OffsetSize = reader.ReadByte(); for (int i = 0; i < Count + 1; i++) { Offsets.Add(reader.ReadOffset(OffsetSize)); } for (int i = 0; i < Offsets.Count - 1; i++) { Objects.Add(reader.ReadBytes((int)(Offsets[i + 1] - Offsets[i]))); } } /// <summary> /// Gets a Number of objects stored in INDEX. /// </summary> public ushort Count { get; } /// <summary> /// Gets an offset array element size. /// </summary> public byte OffsetSize { get; } /// <summary> /// Gets a list of offset. /// </summary> public List<uint> Offsets { get; } = new List<uint>(); /// <summary> /// Gets a lisy of object. /// </summary> public List<byte[]> Objects { get; } = new List<byte[]>(); } }
using LoowooTech.Stock.Common; using LoowooTech.Stock.Models; using System; using System.Collections.Generic; using System.Data.OleDb; using System.Linq; using System.Text; namespace LoowooTech.Stock.Tool { public class ValueNullTool:ValueBaseTool, ITool { public string[] CheckFields { get; set; } public string Key { get; set; } public string WhereCaluse { get; set; } public bool Is_Nullable { get; set; }//true 为空 false 必填 public string[] WhereFields { get; set; } public string Split { get; set; } public List<string> WhereList { get; set; } public string Name { get { return string.IsNullOrEmpty(WhereCaluse) ? string.Format("规则{0}:表‘{1}’中字段‘{2}’{3}", ID, TableName, string.Join("、", CheckFields), Is_Nullable ? "为空" : "必填") : string.Format("规则{0}:表‘{1}’ 当‘{2}’时,字段‘{3}’{4}", ID, TableName, WhereCaluse, string.Join("、", CheckFields), Is_Nullable ? "为空" : "必填"); } } public string[] LocationFields { get; set; } private bool CheckWhereFields(OleDbConnection connection) { var reader = ADOSQLHelper.ExecuteReader(connection, string.IsNullOrEmpty(WhereCaluse) ? ( LocationFields == null ? string.Format("Select {0},{1},{2} from {3}", Key, string.Join(",", CheckFields), string.Join(",", WhereFields), TableName) : string.Format("Select {0},{1},{2},{3} from {4}", Key, string.Join(",", CheckFields), string.Join(",", WhereFields), string.Join(",", LocationFields), TableName) ) : ( LocationFields == null ? string.Format("Select {0},{1},{2} from {3} where {4}", Key, string.Join(",", CheckFields), string.Join(",", WhereFields), TableName, WhereCaluse) : string.Format("Select {0},{1},{2},{3} from {4} where {5}", Key, string.Join(",", CheckFields), string.Join(",", WhereFields), string.Join(",", LocationFields), TableName, WhereCaluse) ) ); if (reader != null) { var array = new string[WhereFields.Length]; var str = string.Empty; var info = string.Empty; while (reader.Read()) { for(var i = 0; i < WhereFields.Length; i++) { array[i] = reader[i + 1 + CheckFields.Length].ToString(); } var key = string.Join(Split, array); if (WhereList.Contains(key)) { str = string.Empty; for(var i = 0; i < CheckFields.Length; i++) { var a = reader[i + 1].ToString().Trim(); if (Is_Nullable ^ string.IsNullOrEmpty(a)) { str += CheckFields[i] + ","; } } if (!string.IsNullOrEmpty(str)) { info = string.Format("{0}对应的字段:{1}与要求的{2}不符,图斑信息:行政村代码:【{3}】图斑编号:【{4}】", reader[0].ToString().Trim(), str, Is_Nullable ? "为空" : "必填",array[0],array[1]); _questions.Add( new Question { Code = "5101", Name = Name, Project = CheckProject.图层内属性一致性, TableName = TableName, BSM = reader[0].ToString(), Description = info, RelationClassName = RelationName, ShowType = ShowType.Space, WhereClause = LocationFields == null ? string.Format("[{0}] ='{1}'", Key, reader[0].ToString()) : ADOSQLHelper.GetWhereClause(LocationFields, ADOSQLHelper.GetValues(reader, 1 + CheckFields.Length+WhereFields.Length, LocationFields.Length)) }); Messages.Add(info); } } } QuestionManager.AddRange(_questions); return true; } return false; } private bool CheckNoWhereFields(OleDbConnection connection) { var reader = ADOSQLHelper.ExecuteReader(connection, string.IsNullOrEmpty(WhereCaluse) ? ( LocationFields == null ? string.Format("Select {0},{1} from {2}", string.Join(",", CheckFields), Key, TableName) : string.Format("Select {0},{1},{2} from {3}", string.Join(",", CheckFields), Key, string.Join(",", LocationFields), TableName) ) : ( LocationFields == null ? string.Format("Select {0},{1} from {2} where {3}", string.Join(",", CheckFields), Key, TableName, WhereCaluse) : string.Format("Select {0},{1},{2} from {3} where {4}", string.Join(",", CheckFields), Key, string.Join(",", LocationFields), TableName, WhereCaluse) ) ); if (reader != null) { var str = string.Empty; var info = string.Empty; while (reader.Read()) { str = string.Empty; for (var i = 0; i < CheckFields.Count(); i++) { var a = reader[i].ToString().Trim(); if (Is_Nullable ^ string.IsNullOrEmpty(a))//异或 Is_NULLable ture 为空 字段不为空或者 Is_NULLable false 必填 字段为空 矛盾 { str += CheckFields[i] + ","; } } if (!string.IsNullOrEmpty(str)) { info = string.Format("{0}对应的字段:{1}与要求的{2}不符", reader[CheckFields.Count()], str, Is_Nullable ? "为空" : "必填"); _questions.Add( new Question { Code = "5101", Name = Name, Project = CheckProject.图层内属性一致性, TableName = TableName, BSM = reader[CheckFields.Count()].ToString(), Description = info, RelationClassName = RelationName, ShowType = ShowType.Space, WhereClause = LocationFields == null ? string.Format("[{0}] ='{1}'", Key, reader[CheckFields.Count()].ToString()) : ADOSQLHelper.GetWhereClause(LocationFields, ADOSQLHelper.GetValues(reader, 1 + CheckFields.Length, LocationFields.Length)) }); Messages.Add(info); } } QuestionManager.AddRange(_questions); return true; } return false; } public bool Check(OleDbConnection connection) { if (WhereFields != null) { return CheckWhereFields(connection); } return CheckNoWhereFields(connection); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Basement : Story { public Basement(int identifier) : base(identifier) { } protected override void GenerateLandingRoom(Board board, Vector2Int stairway, Verticality verticality) { landing = new BasementLanding(); rooms.Add(landing); landing.SetupRoom(stairway, verticality, board.startingDoorwayDirection, identifier); landing.TestRoomValidity(board); } protected override Room RandomRoom() { int rng = roomRngIdentifiers[0]; switch (rng) { case 0: return new Catacomb(); case 1: return new Catacomb(); case 2: return new Catacomb(); case 3: return new Catacomb(); case 4: return new Catacomb(); case 5: return new Catacomb(); case 6: return new Cellar(); case 7: return new BoilerRoom(); case 8: return new PanicRoom(); default: return new Room(); } } }
using System.Collections.Generic; using Jypeli.Controls; namespace Jypeli { public partial class Widget { private ListenContext context = new ListenContext(); /// <summary> /// Tähän listaan lisätyt kuuntelijat tuhotaan automaattisesti /// kun Widget poistetaan pelistä. /// </summary> internal List<Listener> associatedListeners = new List<Listener>(); /// <summary> /// Tämän Widgetin ohjainkuuntelijoiden konteksti /// </summary> public ListenContext ControlContext { get { return context; } } /// <summary> /// Jos <c>true</c>, pelin sekä ikkunan alla olevien widgettien /// ohjaimet eivät ole käytössä kun ikkuna on näkyvissä. /// </summary> public bool IsModal { get; set; } /// <summary> /// Kaappaako hiiren, eli meneekö hiiren tapahtumat tämän alla sijaitsevalle oliolle /// </summary> public bool CapturesMouse { get; set; } /// <summary> /// Kaappaako hiirtä tällä hetkellä, eli: /// <c>CapturesMouse</c> on true ja hiiri on tämän olion päällä, tai /// Jokin tämän lapsista kaappaa hiirtä. /// </summary> public bool IsCapturingMouse { get { //if (CapturesMouse && Game.Mouse.IsCursorOn(this)) // return true; foreach (var o in Objects) { if (o is Widget w && w.IsCapturingMouse) return true; } return false; } } /// <summary> /// Alustaa Widgetin ohjaimet käyttöön. /// Sinun ei tarvitse kutsua tätä /// </summary> public void InitControl() { if (ControlContext == null || ControlContext.IsDestroyed) context = new ListenContext(); Objects.ItemAdded += InitChildContext; Objects.ItemRemoved += ResetChildContext; Removed += RemoveListeners; } private void InitChildContext(GameObject child) { ControlContexted ctxChild = child as ControlContexted; if (ctxChild == null) return; ctxChild.ControlContext.dynamicParent = true; ctxChild.ControlContext.parentObject = this; } private void ResetChildContext(GameObject child) { ControlContexted ctxChild = child as ControlContexted; if (ctxChild == null) return; ctxChild.ControlContext.parentObject = null; ctxChild.ControlContext.parentContext = null; } private void RemoveListeners() { associatedListeners.ForEach(l => l.Destroy()); associatedListeners.Clear(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlrStatus : MonoBehaviour { public float health; public bool isDead; public GameObject ragdoll; // Use this for initialization void Start () { isDead = false; } // Update is called once per frame void Update () { if(health <= 0) { health = 0; isDead = true; Die(); } } public void TakeDamage(float damage) { health -= damage; } public void Die() { Vector3 hitPos = transform.position; Quaternion hitRot = transform.rotation; var _ragdoll = Instantiate(ragdoll, hitPos, hitRot); var _ragRigidBody = _ragdoll.GetComponent<Rigidbody>(); _ragRigidBody.mass = 0.5f; _ragRigidBody.AddForce(Vector3.up * 1000f); Destroy(gameObject); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ZC_IT_TimeTracking.Models { public partial class AssignGoal { public int[] ResourceID { get; set; } public int Goal_MasterID { get; set; } public int weight { get; set; } } }
using FluentValidation; using SnowBLL.Models.Users; namespace SnowBLL.Validators.Users { public class UserCreateModelValidator : AbstractValidator<UserCreateModel> { public UserCreateModelValidator() { RuleFor(user => user.Email).NotEmpty().WithMessage(UserMessages.EMAIL_NOTEMPTY); RuleFor(user => user.Email).EmailAddress().WithMessage(UserMessages.EMAIL_VALIDFORMAT); RuleFor(user => user.Password).NotEmpty().WithMessage(UserMessages.PASSWORD_NOTEMPTY); RuleFor(user => user.Password).Length(6,100).WithMessage(UserMessages.PASSWORD_LENGTH); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class MovingPlatformPhysics : MonoBehaviour { private float xMove, yMove, prevX, prevY; bool contact; private GameObject player; private void OnTriggerEnter(Collider other) { if (other.gameObject.CompareTag("Player")) { GetPos(); print("contact"); contact = true; player = other.gameObject; } } private void OnTriggerExit(Collider other) { if (other.gameObject.CompareTag("Player")) { print("contact nulled"); contact = false; } } private void Update() { if(contact) { MoveSync(); GetPos(); } } private void GetPos() { prevX = this.transform.position.x; prevY = this.transform.position.y; } private void MoveSync() { xMove = this.transform.position.x - prevX ; yMove = this.transform.position.y - prevY ; player.transform.Translate(xMove, yMove, 0,Space.World); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Accueil : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnCreerDevis_Click(object sender, EventArgs e) { Response.Redirect("NouveauDevis.aspx"); } protected void btnBrouillonDevis_Click(object sender, EventArgs e) { } protected void btnNouveauClientDevis_Click(object sender, EventArgs e) { Response.Redirect("NouveauClient.aspx"); } protected void btnEditFicheClientDevis_Click(object sender, EventArgs e) { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PEImageDebugSample { class EnumerableExtention<T> : IEnumerable<T> { private readonly IEnumerable<T> _self; private readonly Func<Exception, bool> _onError; public EnumerableExtention(IEnumerable<T> target, Func<Exception, bool> onError) { if (target == null) { throw new ArgumentNullException("target"); } _self = target; _onError = onError; } public IEnumerator<T> GetEnumerator() { var enumrator = new EnumeratorExtention<T>(_self.GetEnumerator(), _onError); return enumrator; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { var enumrator = new EnumeratorExtention<T>(_self.GetEnumerator(), _onError); return enumrator; } } class EnumeratorExtention<T> : IEnumerator<T> { private readonly IEnumerator<T> _self; private readonly Func<Exception, bool> _onError; public EnumeratorExtention(IEnumerator<T> target, Func<Exception, bool> onError) { if (target == null) { throw new ArgumentNullException("target"); } _self = target; _onError = onError; } public T Current { get { return _self.Current; } } public void Dispose() { _self.Dispose(); } object System.Collections.IEnumerator.Current { get { return _self.Current; } } public bool MoveNext() { try { return _self.MoveNext(); } catch (Exception ex) { if (_onError != null) { var br = _onError(ex); if (!br) { throw; } } return _self.MoveNext(); } } public void Reset() { _self.Reset(); } } }
using System; using System.IO; using System.Data; using System.Collections.Generic; namespace ResilienceClasses { public class clsProperty { #region Enums and Static Values public static string strPropertyPath = "/Volumes/GoogleDrive/Shared Drives/Resilience/tblProperty.csv"; //public static string strPropertyPath = "/Volumes/GoogleDrive/Team Drives/Resilience/tblProperty.csv"; // "/Users/" + Environment.UserName + "/Documents/Professional/Resilience/tblProperty.csv"; public static int TownColumn = 1; public static int CountyColumn = 2; public static int StateColumn = 3; public static int AddressColumn = 4; public static int BPOColumn = 5; public static int NickNameColumn = 6; #endregion #region Properties private int iPropertyID; private string strAddress; private string strTown; private string strCounty; private string strState; private double dBPO; private string strNickname; #endregion #region Static Methods public static List<string> AddressList() { List<string> returnValue = new List<string>(); clsCSVTable tbl = new clsCSVTable(clsProperty.strPropertyPath); int streetNumber; string streetName; // compile list as [street name] [8 digit street number] for (int i = 0; i < tbl.Length(); i++) { string s = tbl.Value(i, clsProperty.AddressColumn); streetNumber = Int32.Parse(System.Text.RegularExpressions.Regex.Match(s, @"\d+").Value); streetName = System.Text.RegularExpressions.Regex.Replace(s, streetNumber.ToString(), "").Trim(); returnValue.Add(streetName + " " + streetNumber.ToString("00000000")); } // sort list, so it's alphabetical by street name and then street number returnValue.Sort(); // put list back to [street number] [street name] for (int i = 0; i < returnValue.Count; i++) { streetNumber = Int32.Parse(returnValue[i].Substring(returnValue[i].Length - 8)); streetName = returnValue[i].Substring(0, returnValue[i].Length - 9); returnValue[i] = streetNumber.ToString() + " " + streetName; } return returnValue; } public static int IDFromAddress(string address) { clsCSVTable tbl = new clsCSVTable(clsProperty.strPropertyPath); int id = -1; for (int i = 0; i < tbl.Length(); i++) { if (tbl.Value(i, clsProperty.AddressColumn) == address) id = i; } return id; } #endregion #region Constructors public clsProperty(int propertyID) { this._Load(propertyID, new clsCSVTable(clsProperty.strPropertyPath)); } public clsProperty(int propertyID, clsCSVTable tbl) { this._Load(propertyID, tbl); } public clsProperty(string address) { this._Load(clsProperty.IDFromAddress(address), new clsCSVTable(clsProperty.strPropertyPath)); } public clsProperty(string address, clsCSVTable tbl) { this._Load(clsProperty.IDFromAddress(address), tbl); } public clsProperty(string address, string town, string county, string state, double bpo, string nickname) { this.iPropertyID = _NewPropertyID(); this.strAddress = address; this.strTown = town; this.strCounty = county; this.strState = state; this.dBPO = bpo; this.strNickname = nickname; } #endregion #region Property Accessors public int ID() { return this.iPropertyID; } public int PropertyID() { return this.iPropertyID; } public string Address() { return this.strAddress; } public string Town() { return this.strTown; } public string County() { return this.strCounty; } public string State() { return this.strState; } public double BPO() { return this.dBPO; } public string Name() { return this.strNickname; } #endregion #region DB Methods private bool _Load(int propertyID, clsCSVTable tbl) { if (propertyID < tbl.Length()) { this.iPropertyID = propertyID; this.strAddress = tbl.Value(propertyID, clsProperty.AddressColumn); this.strTown = tbl.Value(propertyID, clsProperty.TownColumn); this.strCounty = tbl.Value(propertyID, clsProperty.CountyColumn); this.strState = tbl.Value(propertyID, clsProperty.StateColumn); if (!double.TryParse(tbl.Value(propertyID, clsProperty.BPOColumn), out this.dBPO)) { this.dBPO = 0; } // this.dBPO = Double.Parse(tbl.Value(propertyID, clsProperty.BPOColumn)); this.strNickname = tbl.Value(propertyID, clsProperty.NickNameColumn); return true; } else { return false; } } public bool Save() { return this.Save(clsProperty.strPropertyPath); } public bool Save(string path) { clsCSVTable tbl = new clsCSVTable(path); if (this.iPropertyID == tbl.Length()) { string[] strValues = new string[tbl.Width() - 1]; strValues[clsProperty.AddressColumn - 1] = this.strAddress; strValues[clsProperty.BPOColumn - 1] = this.dBPO.ToString(); strValues[clsProperty.CountyColumn - 1] = this.strCounty; strValues[clsProperty.TownColumn - 1] = this.strTown; strValues[clsProperty.NickNameColumn - 1] = this.strNickname; strValues[clsProperty.StateColumn - 1] = this.strState; tbl.New(strValues); return tbl.Save(); } else { if ((this.iPropertyID < tbl.Length()) && (this.iPropertyID >= 0)) { if ( tbl.Update(this.iPropertyID, clsProperty.AddressColumn, this.strAddress) && tbl.Update(this.iPropertyID, clsProperty.BPOColumn, this.dBPO.ToString()) && tbl.Update(this.iPropertyID, clsProperty.CountyColumn, this.strCounty) && tbl.Update(this.iPropertyID, clsProperty.TownColumn, this.strTown) && tbl.Update(this.iPropertyID, clsProperty.NickNameColumn, this.strNickname) && tbl.Update(this.iPropertyID, clsProperty.StateColumn, this.strState)) { return tbl.Save(); } else { return false; } } else { return false; } } } private int _NewPropertyID() { clsCSVTable tbl = new clsCSVTable(clsProperty.strPropertyPath); return tbl.Length(); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.Principal; using System.Collections; namespace EasyDev.Security { /// <summary> /// 用户身份识别对象 /// </summary> public sealed class UserIdentity : GenericIdentity { private IDictionary context = null; //private bool isAuthenticated = true; //public void SetIsAuthenticated() //{ // this.isAuthenticated = true; //} /// <summary> /// 包含用户身份相关的信息集合 /// </summary> public IDictionary Context { get { return this.context; } set { this.context = value; } } public UserIdentity(string userName) : base(userName) { context = new Hashtable(); } public UserIdentity(string userName, string type) : base(userName, type) { context = new Hashtable(); } } }
using System.Xml.Linq; namespace Piovra.Svg; public abstract class Drawing { public abstract XElement ToSvg(); protected static readonly XNamespace NS = @"http://www.w3.org/2000/svg"; protected static XElement NewXElement(string tag, params object[] content) => new(NS + tag, content); }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using Otiport.API.Contract.Models; using Otiport.API.Data; using Otiport.API.Data.Entities.Medicine; namespace Otiport.API.Repositories.Implementations { public class MedicineRepository : IMedicineRepository { private readonly OtiportDbContext _dbContext; private readonly ILogger<IMedicineRepository> _logger; public MedicineRepository(OtiportDbContext dbContext, ILogger<IMedicineRepository> logger) { _dbContext = dbContext; _logger = logger; } public void Dispose() { _dbContext?.Dispose(); } public async Task<bool> SaveAsync() { try { await _dbContext.SaveChangesAsync(); return true; } catch (Exception e) { _logger.LogError(e, "Something went wrong"); return false; } } public async Task<IEnumerable<MedicineEntity>> GetMedicinesAsync() { return await _dbContext.Medicines.ToListAsync(); } public async Task<bool> AddMedicineAsync(MedicineEntity entity) { await _dbContext.Medicines.AddAsync(entity); return await SaveAsync(); } public async Task<bool> DeleteMedicineAsync(MedicineEntity entity) { _dbContext.Medicines.Remove(entity); return await SaveAsync(); } public async Task<MedicineEntity> GetMedicineById(int id) { var medicineEntity = await _dbContext.Medicines.FindAsync(id); return medicineEntity; } public async Task<bool> UpdateMedicinesAsync(MedicineEntity entity) { _dbContext.Medicines.Update(entity); return await SaveAsync(); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace MSt.Data.Entity { /// <summary> /// Role that can have a user /// </summary> public class Role { /// <summary> /// Role ID /// </summary> [Key] public Guid Guid { get; set; } /// <summary> /// Name of Role /// </summary> [Required] public string Name { get; set; } /// <summary> /// If Role is deleted /// </summary> public bool IsDeleted { get; set; } /// <summary> /// Collection of roles that have a user /// </summary> public ICollection<UserRole> UserRoles { get; set; } /// <summary> /// Collection of role claims of the user /// </summary> public ICollection<RoleClaim> RoleClaims { get; set; } } }
using Fragenkatalog.Model; namespace Fragenkatalog.Datenhaltung.DB.MySql { class DbSchueler : Schueler { // Rollen-Login für Schüler static private readonly string rollenLoginName = "fragenkatalog_schueler"; static private readonly string rollenPasswort = "SdfgrP12&qwf3a"; static public Connector Connector { get; private set; } public DbSchueler(uint benutzer_nr, string login_name, string email_adresse, string passwort) : base(benutzer_nr, login_name, email_adresse, passwort) { Connector = new Connector(rollenLoginName, rollenPasswort); } // nur zum Testen public DbFrage ReadFrage(uint frage_nr) { return DbFrage.Read(Connector, frage_nr); } public Schueler Read(Connector connector, uint benutzer_nr) { return (Schueler)DbBenutzer.Read(connector, benutzer_nr); } public void Update(Connector connector) { DbBenutzer updateBenutzer = new DbBenutzer(Benutzer_nr, Login_name, Email_adresse, Passwort, Rollen_nr); updateBenutzer.Update(connector); } public void Delete(Connector connector) { DbBenutzer deleteBenutzer = new DbBenutzer(Benutzer_nr, Login_name, Email_adresse, Passwort, Rollen_nr); deleteBenutzer.Delete(connector); } } }
using System; using System.Text; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json; using System.IO; using Hl7.Fhir.Model; using Hl7.Fhir.Serializers; using System.Xml.Linq; using System.Xml; using Hl7.Fhir.Support; using Hl7.Fhir.Parsers; using Hl7.Fhir.Client; namespace Hl7.Fhir.Tests { [TestClass] public class SerializerTests { [TestMethod] public void SerializeElement() { Identifier id = new Identifier { InternalId = "3141", Use = Identifier.IdentifierUse.Official, Label = "SSN", System = new Uri("http://hl7.org/fhir/sid/us-ssn"), Id = "000111111", Period = new Period() { Start = new FhirDateTime(2001, 1, 2), End = new FhirDateTime(2010, 3, 4) }, Assigner = new ResourceReference { Type = "Organization", Url = new Uri("../organization/@123", UriKind.Relative), Display = "HL7, Inc" } }; Assert.AreEqual(@"<?xml version=""1.0"" encoding=""utf-16""?>" + @"<element id=""3141"" xmlns=""http://hl7.org/fhir"">" + @"<use value=""official"" />" + @"<label value=""SSN"" />" + @"<system value=""http://hl7.org/fhir/sid/us-ssn"" />" + @"<id value=""000111111"" />" + @"<period><start value=""2001-01-02"" /><end value=""2010-03-04"" /></period>" + @"<assigner><type value=""Organization"" /><url value=""../organization/@123"" /><display value=""HL7, Inc"" /></assigner>" + @"</element>", FhirSerializer.SerializeElementAsXml(id)); Assert.AreEqual( @"{""_id"":""3141"",""use"":{""value"":""official""},""label"":{""value"":""SSN""}," + @"""system"":{""value"":""http://hl7.org/fhir/sid/us-ssn""},""id"":{""value"":""000111111""}," + @"""period"":{""start"":{""value"":""2001-01-02""},""end"":{""value"":""2010-03-04""}}," + @"""assigner"":{""type"":{""value"":""Organization""},""url"":{""value"":""../organization/@123""}," + @"""display"":{""value"":""HL7, Inc""}}}", FhirSerializer.SerializeElementAsJson(id)); } [TestMethod] public void PolymorphAndArraySerialization() { Extension ext = new Extension() { Url = new Uri("http://hl7.org/fhir/profiles/@3141#test"), Value = new FhirBoolean(true), NestedExtension = new List<Extension>() { new Extension() { Value = new Coding() { Code = "R51", System = new Uri("http://hl7.org/fhir/sid/icd-10") } } } }; Assert.AreEqual(@"<?xml version=""1.0"" encoding=""utf-16""?>" + @"<element xmlns=""http://hl7.org/fhir""><url value=""http://hl7.org/fhir/profiles/@3141#test"" /><valueBoolean value=""true"" />" + @"<extension><valueCoding><system value=""http://hl7.org/fhir/sid/icd-10"" /><code value=""R51"" /></valueCoding></extension>" + @"</element>", FhirSerializer.SerializeElementAsXml(ext)); Assert.AreEqual( @"{""url"":{""value"":""http://hl7.org/fhir/profiles/@3141#test""},""valueBoolean"":{""value"":""true""}," + @"""extension"":[{""valueCoding"":{""system"":{""value"":""http://hl7.org/fhir/sid/icd-10""},""code"":{""value"":""R51""}}}]}", FhirSerializer.SerializeElementAsJson(ext)); } [TestMethod] public void ResourceWithExtensionAndNarrative() { Patient p = new Patient() { InternalId = "Ab4", Identifier = new List<Identifier> { new Identifier() { Id = "3141" } }, Details = new Demographics() { BirthDate = new FhirDateTime(1972, 11, 30), Name = new List<HumanName> { new HumanName() { Given = new List<FhirString>() { "Wouter", "Gert" }, Family = new List<FhirString>() { new FhirString() { Contents = "van der", Extension = new List<Extension> { new Extension { Url= new Uri("http://hl7.org/fhir/profile/@iso-21090#name-qualifier"), Value = new Code("VV") } } }, "Vlies" } } } }, Text = new Narrative() { Status = Narrative.NarrativeStatus.Generated, Div = "<div xmlns='http://www.w3.org/1999/xhtml'>Patient 3141 - Wouter Gert, nov. 30th, 1972</div>" }, Contained = new List<Resource>() { new List() { Mode = List.ListMode.Snapshot } } }; Assert.AreEqual(@"<?xml version=""1.0"" encoding=""utf-16""?>" + @"<Patient id=""Ab4"" xmlns=""http://hl7.org/fhir"">" + @"<text><status value=""generated"" /><div xmlns='http://www.w3.org/1999/xhtml'>Patient 3141 - Wouter Gert, nov. 30th, 1972</div></text>" + @"<contained><List><mode value=""snapshot"" /></List></contained>" + @"<identifier><id value=""3141"" /></identifier>" + @"<details><name>" + @"<family value=""van der"">" + @"<extension><url value=""http://hl7.org/fhir/profile/@iso-21090#name-qualifier"" /><valueCode value=""VV"" /></extension>" + @"</family><family value=""Vlies"" /><given value=""Wouter"" /><given value=""Gert"" /></name>" + @"<birthDate value=""1972-11-30"" /></details>" + @"</Patient>", FhirSerializer.SerializeResourceAsXml(p)); Assert.AreEqual(@"{""Patient"":{""_id"":""Ab4""," + @"""text"":{""status"":{""value"":""generated""},""div"":""<div xmlns='http://www.w3.org/1999/xhtml'>" + @"Patient 3141 - Wouter Gert, nov. 30th, 1972</div>""},"+ @"""contained"":[{""List"":{""mode"":{""value"":""snapshot""}}}],"+ @"""identifier"":[{""id"":{""value"":""3141""}}]," + @"""details"":{""name"":[{""family"":[{""value"":""van der""," + @"""extension"":[{""url"":{""value"":""http://hl7.org/fhir/profile/@iso-21090#name-qualifier""},""valueCode"":{""value"":""VV""}}]}," + @"{""value"":""Vlies""}],""given"":[{""value"":""Wouter""},{""value"":""Gert""}]}],""birthDate"":{""value"":""1972-11-30""}}" + @"}}", FhirSerializer.SerializeResourceAsJson(p)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using SSDAssignmentBOX.Models; using Microsoft.AspNetCore.Authorization; namespace SSDAssignmentBOX.Pages.Roles { [Authorize(Roles = "Admin")] public class DetailsModel : PageModel { private readonly RoleManager<ApplicationRole> _roleManager; public DetailsModel(RoleManager<ApplicationRole> roleManager) { _roleManager = roleManager; } public ApplicationRole ApplicationRole { get; set; } public Book Book { get; set; } public async Task<IActionResult> OnGetAsync(string id) { if (id == null) { return NotFound(); } ApplicationRole = await _roleManager.FindByIdAsync(id); //The method _rolemanager.FindByIdAsync(id) retrieve an application role object based on the id as parameter. if (ApplicationRole == null) { return NotFound(); } Book.Availability = "Not Available"; return Page(); } } }
using Effigy.Service; using Effigy.Utility; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Effigy.Entity.DBContext; using System.Web.Services; using Effigy.Entity.Entity; using System.Text; namespace Effigy.Web.MasterPage { public partial class UserRoleMenuMapper : BasePage { protected void Page_Load(object sender, EventArgs e) { try { if (!IsPostBack) { } } catch (Exception ex) { Logger.Error(ex); } } [WebMethod] public static IList<Entity.Entity.UserRoleMaster> GetUserRoleList() { try { IMasterService objMstService = new MasterService(); return objMstService.GetUserRoleList(); } catch (Exception ex) { Logger.Error(ex); return null; } } [WebMethod] public static int?[] GetSelectedMenus(int roleId) { try { IMasterService objMstService = new MasterService(); return objMstService.GetSelectedMenus(roleId); } catch (Exception ex) { Logger.Error(ex); return null; } } [WebMethod] public static string SaveMenuRoleMapping(MenuRoleMapper objMenuRoleMapper) { IMasterService objService = new MasterService(); objMenuRoleMapper.CreatedBy = SessionWrapper.UserId; objMenuRoleMapper.CreatedDate = DateTime.Now; objService.SaveMenuRoleMapping(objMenuRoleMapper); return "success"; } [WebMethod] public static IList<MenuDetails> GetMenuList() { IMasterService objService = new MasterService(); IList<MenuDetails> objMenuDetailsLst = objService.GetMenuList(); return objMenuDetailsLst; } } }
using Catalog.Core.Entities; using Catalog.Core.Interfaces; using MongoDB.Driver; namespace Catalog.Infrastructure.Data { public class CatalogContext : ICatalogContext { public CatalogContext(IMongoDbConfig config) { var client = new MongoClient(config.ConnectionString); var database = client.GetDatabase(config.DatabaseName); Products = database.GetCollection<Product>(config.CollectionName); CatalogContextSeed.SeedData(Products).Wait(); } public IMongoCollection<Product> Products { get; } } }
using CsvHelper; using PopulationFitness.Models; using System; using System.IO; using System.Linq; namespace PopulationFitness.Output { public class GenerationsWriter { private static String FilePath(int parallel_run, int series_run, int number_of_runs, Config config) { return "generations" + "-" + parallel_run + "-" + series_run + "of" + number_of_runs + "-" + config.GenesFactory.FitnessFunction + "-genes" + config.NumberOfGenes + "x" + config.SizeOfEachGene + "-pop" + config.InitialPopulation + "-mut" + config.MutationsPerGene + "-" + config.Id.Replace(":", "-") + ".csv"; } private static void WriteCsv(int parallel_run, int series_run, int number_of_runs, Generations generations, Tuning tuning) { WriteCsv(FilePath(parallel_run, series_run, number_of_runs, generations.Config), generations, tuning); } public static String WriteCsv(String filePath, Generations generations, Tuning tuning) { using (var file = CreateCsvWriter(filePath)) { var records = generations.History.Select(generation => { return CreateRecord(generation); }); var writer = new CsvWriter(file); writer.WriteRecords(records); } return filePath; } private static object CreateRecord(GenerationStatistics generation) { return new { EpochStartYear = generation.Epoch.StartYear, EpochEndYear = generation.Epoch.EndYear, EpochEnvironmentCapacity = generation.Epoch.CapacityForYear(generation.Year), EpochEnableFitness = generation.Epoch.IsFitnessEnabled, EpochBreedingProbability = generation.Epoch.BreedingProbability(), Year = generation.Year, EpochFitnessFactor = generation.Epoch.Fitness(), EpochExpectedMaxPopulation = generation.Epoch.ExpectedMaxPopulation, Population = generation.Population, NumberBorn = generation.NumberBorn, NumberKilled = generation.NumberKilled, BornElapsed = generation.BornElapsedInHundredths(), KillElapsed = generation.KillElapsedInHundredths(), AvgFitness = generation.AverageFitness, FitnessDeviation = generation.FitnessDeviation, AverageAge = generation.AverageAge, CapacityFactor = generation.CapacityFactor, AvgFactoredFitness = generation.AverageFactoredFitness, AvgMutations = generation.AverageMutations, AvgLifeExpectancy = generation.AverageLifeExpectancy, }; } private static StreamWriter CreateCsvWriter(String filePath) { try { return new StreamWriter(filePath); } catch (Exception e) { Console.WriteLine(e.StackTrace); return new StreamWriter(TryTemporaryVersionOf(filePath)); } } private static String TryTemporaryVersionOf(String filePath) { return "~tmp." + filePath; } /** * Adds the two generation histories together and writes the result as a CSV file. * * @param parallelRun * @param seriesRun * @param current * @param total * @param tuning * @return * @throws IOException */ public static Generations CombineGenerationsAndWriteResult(int parallelRun, int seriesRun, Generations current, Generations total, Tuning tuning) { total = (total == null ? current : Generations.Add(total, current)); WriteCsv(parallelRun, seriesRun, tuning.SeriesRuns * tuning.ParallelRuns, total, tuning); return total; } /** * Creates a result file name from the file id. * * @param id * @return the resulting file name */ public static String CreateResultFileName(String id) { return "allgenerations" + "-" + id + ".csv"; } } }
using NBitcoin; using System; using System.Collections.Generic; using System.Text; using Xunit; namespace WalletWasabi.Tests.UnitTests { public class NBitcoinTests { [Fact] public void DefaultPortsMatch() { Assert.Equal(Helpers.Constants.DefaultMainNetBitcoinCoreRpcPort, Network.Main.RPCPort); Assert.Equal(Helpers.Constants.DefaultTestNetBitcoinCoreRpcPort, Network.TestNet.RPCPort); Assert.Equal(Helpers.Constants.DefaultRegTestBitcoinCoreRpcPort, Network.RegTest.RPCPort); Assert.Equal(Helpers.Constants.DefaultMainNetBitcoinP2pPort, Network.Main.DefaultPort); Assert.Equal(Helpers.Constants.DefaultTestNetBitcoinP2pPort, Network.TestNet.DefaultPort); Assert.Equal(Helpers.Constants.DefaultRegTestBitcoinP2pPort, Network.RegTest.DefaultPort); } } }
using Newtonsoft.Json; using Pathoschild.Stardew.Common; using StardewModdingAPI; namespace Pathoschild.Stardew.NoclipMode.Framework { /// <summary>The mod configuration.</summary> internal class ModConfig { /********* ** Accessors *********/ /// <summary>The button which toggles noclip mode.</summary> [JsonConverter(typeof(StringEnumArrayConverter))] public SButton[] ToggleKey { get; set; } = { SButton.F11 }; } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using Salle.Model.Salle; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestSalle { [TestClass()] public class RangTests { int nbreTables; int[] nbrPlacesParTable = new int[6] { 1, 2, 3, 4, 5, 6, }; private List<Table> Tables; [TestMethod()] public void RangTest() { Tables = new List<Table>(); for (int i = 0; i < nbreTables; i++) { Tables.Add(new Table(nbrPlacesParTable[i])); } Assert.IsNotNull(Tables); } [TestMethod()] public void TableDisponible() { List<Table> tableDispo = new List<Table>(); foreach (Table table in Tables) { if (table.getGroupeClient() == null) { tableDispo.Add(table); } } Assert.IsNotNull(tableDispo); } } }
using System.Collections; using Microsoft.AspNetCore.Mvc; using template.Data; using template.Extensions; using template.Models; using System.Linq; using System.Collections.Generic; using System; using Microsoft.Extensions.Primitives; namespace template.Controllers { [Route("api/models")] public class ModellController : Controller { [HttpGet] [Route("")] public IActionResult GetAllModels([FromQuery] int pageNumber = 1, int pageSize = 10) { string header = Request.Headers["Accept-Language"]; header = (header == null || header != "de-DE") ? "en-US" : header; // if (header == null) // { // header = "en-US"; // } Envelope<ModelDTO> envelope = new Envelope<ModelDTO>(); envelope.PageNumber = pageNumber; envelope.PageSize = pageSize; List<ModelDTO> temp = new List<ModelDTO>(); DataContext.Models.ToLightWeight(header).ForEach(m => { m.Links.AddReference("self", $"http://localhost:5000/api/models/{m.Id}"); temp.Add(m); }); envelope.Items = temp.Skip((pageNumber - 1) * pageSize).Take(pageSize); double maxPages = (double)temp.Count() / (double)pageSize; envelope.MaxPages = (int)Math.Ceiling(maxPages); return Ok(envelope); } [HttpGet] [Route("{id:int}")] public IActionResult GetModelById(int id) { string header = Request.Headers["Accept-Language"]; ModelDetailsDTO model = DataContext.Models.ToDetails(header).FirstOrDefault(m => m.Id == id); model.Links.AddReference("self", $"http://localhost:5000/api/models/{id}"); return Ok(model); } } }
using SFA.DAS.Authorization.ModelBinding; namespace SFA.DAS.ProviderCommitments.Web.Models.Apprentice { public class DeleteConfirmationRequest : IAuthorizationContextModel { public long ProviderId { get; set; } public string DraftApprenticeshipHashedId { get; set; } public string CohortReference { get; set; } } }
using System; namespace PocetDelitelnychCisel { class Program { static void Main(string[] args) { int pocet = 0; for(int i = 100; i <= 200; i++) if (i % 3 == 0) pocet++; Console.WriteLine("Čísel je: " + pocet); Console.ReadKey(true); } } }
#if UNITY_2019_1_OR_NEWER using UnityEditor; using UnityAtoms.Editor; namespace UnityAtoms.BaseAtoms.Editor { /// <summary> /// Event property drawer of type `CollisionPair`. Inherits from `AtomDrawer&lt;CollisionPairEvent&gt;`. Only availble in `UNITY_2019_1_OR_NEWER`. /// </summary> [CustomPropertyDrawer(typeof(CollisionPairEvent))] public class CollisionPairEventDrawer : AtomDrawer<CollisionPairEvent> { } } #endif
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp11 { public abstract class IteratorAggregate : IEnumerable { public abstract IEnumerator GetEnumerator(); } }
/* * Nuget Api Key:oy2io4u6paunfxf3x6capdfwhlfcjasezgdqjjywpnze3e * Ms Account:18972226647 or 171331668@qq.com * Pwd:Faz612123456 */ using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Runtime.CompilerServices; using Atomic.DbProvider; using Atomic.Dependency; namespace Atomic { /// <summary> /// Atomic内核調用入口 /// </summary> public static class AtomicKernel { #region Variable /// <summary> /// 数据库缓存操作KEY /// </summary> private static readonly object s_dbProviderKey = new object(); /// <summary> /// 数据库操作实例缓存 /// </summary> private static readonly Dictionary<Type, object> s_dbProviderCache = new Dictionary<Type, object>(); /// <summary> /// 允许的数据库类型 /// </summary> private static readonly string[] s_allowDbType = new string[] { DatabaseType.Mssql2008, DatabaseType.Mysql, DatabaseType.SQLite }; #endregion #region Propertys /// <summary> /// 依赖注入解析者 /// </summary> public static IDependencyResolver Dependency { get; private set; } #endregion #region Methods /// <summary> /// 获取数据驱动接口实例 /// </summary> /// <typeparam name="M"></typeparam> /// <param name="decryptAlgorithm">解密算法</param> /// <returns></returns> public static IDbProvider<M> GetDbProvider<M>(IDecryptAlgorithm decryptAlgorithm = null) where M : IDbModel, new() { IDbProvider<M> instance = null; Type MT = typeof(M); if (!s_dbProviderCache.ContainsKey(MT)) { lock (s_dbProviderKey) { if (!s_dbProviderCache.ContainsKey(MT)) { //解析数据模型映射接口实例 IDbMappingHandler dbMapper = AtomicKernel.Dependency.Resolve<IDbMappingHandler>(); if (null == dbMapper) throw new Exception("未能解析出IDbMappingHandler接口实例"); //获取数据库链接 string dbName = dbMapper.GetDatabaseName(typeof(M)); ConnectionStringSettings connectionSetting = ConfigurationManager.ConnectionStrings[dbName]; if (null == connectionSetting) throw new Exception("connection 节点中未配置" + dbName); if (string.IsNullOrEmpty(connectionSetting.ProviderName)) throw new Exception("ProviderName is null,检查检点是否配置了providerName属性"); if (!s_allowDbType.Any(d => d.Equals(connectionSetting.ProviderName))) throw new Exception("ProviderName is illegal"); //执行解密 string connStr = null; if (null == decryptAlgorithm) connStr = connectionSetting.ConnectionString; else connStr = decryptAlgorithm.Decrypt(connectionSetting.ConnectionString); //开始构造DAL(使用构造函数一) Dictionary<string, object> paramDic = new Dictionary<string, object> { { "dbConnQuery", connStr }, { "dbMappingHandler", dbMapper } }; instance = AtomicKernel.Dependency.Resolve<IDbProvider<M>>(connectionSetting.ProviderName, paramDic.ToArray()); s_dbProviderCache.Add(MT, instance); } else { instance = s_dbProviderCache[MT] as IDbProvider<M>; } } } else { instance = s_dbProviderCache[MT] as IDbProvider<M>; } return instance; } /// <summary> /// 获取数据驱动接口实例 /// </summary> /// <typeparam name="M"></typeparam> /// <param name="dbType">数据库类型 DatabaseType</param> /// <param name="conn">数据库连结接口实例</param> /// <param name="decryptAlgorithm">解密算法</param> /// <returns></returns> public static IDbProvider<M> GetDbProvider<M>(string dbType, IDbConnectionString conn, IDecryptAlgorithm decryptAlgorithm = null) where M : IDbModel, new() { IDbProvider<M> instance = null; Type MT = typeof(M); if (!s_dbProviderCache.ContainsKey(MT)) { lock (s_dbProviderKey) { if (!s_dbProviderCache.ContainsKey(MT)) { if (!AtomicKernel.Dependency.IsRegistered<IDbProvider<M>>(dbType)) throw new Exception("dbType is illegal"); if (null == conn) throw new ArgumentNullException("conn"); //解析数据模型映射接口实例 IDbMappingHandler dbMapper = AtomicKernel.Dependency.Resolve<IDbMappingHandler>(); if (null == dbMapper) throw new Exception("未能解析出IDbMappingHandler接口实例"); //执行解密 string connStr = null; if (null == decryptAlgorithm) connStr = conn.GetConnection(); else connStr = decryptAlgorithm.Decrypt(conn.GetConnection()); //开始构造DAL(使用构造函数一) Dictionary<string, object> paramDic = new Dictionary<string, object> { { "dbConnQuery", connStr }, { "dbMappingHandler", dbMapper } }; instance = AtomicKernel.Dependency.Resolve<IDbProvider<M>>(dbType, paramDic.ToArray()); s_dbProviderCache.Add(MT, instance); } else { instance = s_dbProviderCache[MT] as IDbProvider<M>; } } } else { instance = s_dbProviderCache[MT] as IDbProvider<M>; } return instance; } /// <summary> /// 初始化函数 /// </summary> [MethodImpl(MethodImplOptions.Synchronized)] public static void Initialize() { //Ioc Init DependencyManager dependency = new DependencyManager(); dependency.Initialize(); AtomicKernel.Dependency = dependency; } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using DelftTools.Functions.Conversion; using DelftTools.Utils.Collections; using DelftTools.Utils.Data; namespace DelftTools.Functions.Generic { public class ConvertedArray<TTarget, TSource> : Unique<long>, IMultiDimensionalArray<TTarget>, IMultiDimensionalArray where TTarget : IComparable where TSource : IComparable { private readonly IMultiDimensionalArray<TSource> source; private readonly Func<TSource, TTarget> toTarget; private readonly Func<TTarget, TSource> toSource; public ConvertedArray(IMultiDimensionalArray<TSource> source, Func<TTarget, TSource> toSource, Func<TSource, TTarget> toTarget) { this.toSource = toSource; this.toTarget = toTarget; this.source = source; } public IEnumerator<TTarget> GetEnumerator() { return new ConvertedEnumerator<TTarget, TSource>(source.GetEnumerator(), toTarget); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void CopyTo(Array array, int index) { throw new NotImplementedException(); } public bool Remove(TTarget item) { return source.Remove(toSource(item)); } public int Count { get { return source.Count; } } public bool IsReadOnly { get { return ((IList)source).IsReadOnly; } } IMultiDimensionalArrayView IMultiDimensionalArray.Select(int[] start, int[] end) { return Select(start, end); } IMultiDimensionalArrayView IMultiDimensionalArray.Select(int dimension, int start, int end) { return Select(dimension, start, end); } IMultiDimensionalArrayView IMultiDimensionalArray.Select(int dimension, int[] indexes) { return Select(dimension, indexes); } public IMultiDimensionalArrayView<TTarget> Select(int dimension, int[] indexes) { return new ConvertedArray<TTarget, TSource>(source, toSource, toTarget).Select(dimension, indexes); } public IMultiDimensionalArrayView<TTarget> Select(int[] start, int[] end) { return new ConvertedArray<TTarget, TSource>(source, toSource, toTarget).Select(start,end); } int IMultiDimensionalArray.Count { get { return Count; } } public void Resize(params int[] newShape) { source.Resize(newShape); } public TTarget this[params int[] indexes] { get { return toTarget(source[indexes]); } set { source[indexes] = toSource(value); } } object IMultiDimensionalArray.this[params int[] index] { get { return this[index]; } set { this[index]= (TTarget) value; } } #if MONO object IMultiDimensionalArray.this[int index] { get { return this[index]; } set { this[index]= (TTarget) value; } } #endif int ICollection.Count { get { return Count; } } public object SyncRoot { get { return source.SyncRoot; } } public bool IsSynchronized { get { return source.IsSynchronized; } } public int Add(object value) { return source.Add((object)toSource((TTarget) value)); } public bool Contains(object value) { return source.Contains(toSource((TTarget) value)); } public void Add(TTarget item) { source.Add(toSource(item)); } public void Clear() { source.Clear(); } public bool Contains(TTarget item) { return source.Contains(toSource(item)); } public void CopyTo(TTarget[] array, int arrayIndex) { throw new NotImplementedException(); } public int IndexOf(TTarget item) { return source.IndexOf(toSource(item)); } public void Insert(int index, TTarget item) { source.Insert(index,toSource(item)); } public void RemoveAt(int index) { source.RemoveAt(index); } TTarget IList<TTarget>.this[int index] { get { return this[index]; } set { this[index] = value; } } #if MONO TTarget IMultiDimensionalArray<TTarget>.this[int index] { get { return this[index]; } set { this[index] = value; } } #endif public IMultiDimensionalArray<TTarget> Clone() { throw new NotImplementedException(); } void IMultiDimensionalArray.Clear() { Clear(); } void IMultiDimensionalArray.RemoveAt(int index) { RemoveAt(index); } public object DefaultValue { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public int[] Shape { get {return source.Shape; } } public int[] Stride { get { return source.Stride; } } public int Rank { get { return source.Rank; } } public IMultiDimensionalArrayView<TTarget> Select(int dimension, int start, int end) { return new ConvertedArray<TTarget, TSource>(source, toSource, toTarget).Select(dimension, start, end); } public void RemoveAt(int dimension, int index) { source.RemoveAt(dimension,index); } public void RemoveAt(int dimension, int index, int length) { source.RemoveAt(dimension,index,length); } public void InsertAt(int dimension, int index) { source.InsertAt(dimension,index); } public void InsertAt(int dimension, int index, int length) { source.InsertAt(dimension,index,length); } public void Move(int dimension, int index, int length, int newIndex) { source.Move(dimension,index,length,newIndex); } public bool FireEvents { get { return source.FireEvents; } set { source.FireEvents = value; } } public void AddRange(IList values) { //foreach?? //source.AddRange(values); throw new NotImplementedException(); } public object MaxValue { get { return toTarget((TSource) source.MaxValue); } } public object MinValue { get { return toTarget((TSource)source.MinValue); } } public bool IsAutoSorted { get { return source.IsAutoSorted; } set { throw new NotImplementedException(); } } public IVariable Owner { get; set; } void IList.Clear() { Clear(); } public int IndexOf(object value) { return source.IndexOf(toSource((TTarget) value)); } public void Insert(int index, object value) { source.Insert(index,toSource((TTarget) value)); } public void Remove(object value) { source.Remove(toSource((TTarget) value)); } void IList.RemoveAt(int index) { RemoveAt(index); } object IList.this[int index] { get { return this[index]; } set { this[index] = (TTarget) value; } } bool IList.IsReadOnly { get { return IsReadOnly; } } public bool IsFixedSize { get { return source.IsFixedSize; } } object ICloneable.Clone() { throw new NotImplementedException(); } public event EventHandler<MultiDimensionalArrayChangingEventArgs> CollectionChanged; public int InsertAt(int dimension, int index, int length, IList valuesToInsert) { throw new NotImplementedException(); } public event EventHandler<MultiDimensionalArrayChangingEventArgs> CollectionChanging; public event PropertyChangingEventHandler PropertyChanging; public event PropertyChangedEventHandler PropertyChanged; public override string ToString() { return MultiDimensionalArrayHelper.ToString(this); } } }
using Quiz.View; using System; using System.Windows; using System.Windows.Threading; namespace Quiz { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { public App() { ApplicationInitialize = _applicationInitialize; } public static new App Current { get { return Application.Current as App; } } internal delegate void ApplicationInitializeDelegate(SplashScreenView splashWindow); internal ApplicationInitializeDelegate ApplicationInitialize; private void _applicationInitialize(SplashScreenView splashWindow) { // fake workload, but with progress updates. /* Thread.Sleep(500); splashWindow.SetProgress(0.2); Thread.Sleep(500); splashWindow.SetProgress(0.4); Thread.Sleep(500); splashWindow.SetProgress(0.6); Thread.Sleep(500); splashWindow.SetProgress(0.8); Thread.Sleep(500); splashWindow.SetProgress(1); */ // Create the main window, but on the UI thread. Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate { MainWindow = new MainWindow(); MainWindow.Show(); })); } } }
using UnityEngine; namespace DChild.Gameplay.Player { [System.Serializable] public struct PlayerSensors { [SerializeField] private RaycastSensor m_wallSensor; [SerializeField] private RaycastSensor m_groundSensor; [SerializeField] private RaycastSensor m_headSensor; [SerializeField] private RaycastSensor m_waterSensor; public RaycastSensor wallSensor { get { return m_wallSensor; } } public RaycastSensor groundSensor { get { return m_groundSensor; } } public RaycastSensor headSensor { get { return m_headSensor; } } public RaycastSensor waterSensor { get { return m_waterSensor; } } public void CastRays() { m_wallSensor.CastRays(); m_groundSensor.CastRays(); m_headSensor.CastRays(); m_waterSensor.CastRays(); } } }
using ND.FluentTaskScheduling.Domain.interfacelayer; using ND.FluentTaskScheduling.Helper; using ND.FluentTaskScheduling.Model; using ND.FluentTaskScheduling.Model.enums; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; //********************************************************************** // // 文件名称(File Name):MonitorPluginMonitor.CS // 功能描述(Description): // 作者(Author):Aministrator // 日期(Create Date): 2017-05-27 15:47:40 // // 修改记录(Revision History): // R1: // 修改作者: // 修改日期:2017-05-27 15:47:40 // 修改理由: //********************************************************************** namespace ND.FluentTaskScheduling.WebApi.Monitor { /// <summary> /// 监控所有节点下的监控插件运行情况 /// </summary> public class MonitorPluginMonitor : AbsMonitor { private INodeRepository nodeRep; private IUserRepository userRep; private INodeMonitorRepository nodemonitorRep; private static object lockObj = new object(); private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); public MonitorPluginMonitor(INodeRepository noderespostory, IUserRepository userrespostory,INodeMonitorRepository nodemonitorrepostory) { nodeRep = noderespostory; userRep = userrespostory; nodemonitorRep = nodemonitorrepostory; } /// <summary> /// 监控间隔15s时间(ms为单位) /// </summary> public override int Interval { get { return 15000; } } protected override void Run() { lock (lockObj) { int monitorstatus=(int)MonitorStatus.Monitoring; List<tb_nodemonitor> nodemonitorlist = nodemonitorRep.Find(x => x.isdel == 0 && x.monitorstatus == monitorstatus).ToList(); List<tb_user> userList = userRep.Find(x => x.isdel == 0).ToList(); StringBuilder strLog = new StringBuilder(); nodemonitorlist.ForEach(x => { try { tb_node node=nodeRep.FindSingle(m => m.id == x.nodeid); List<int> uidlist = node.alarmuserid.ConvertToList(); List<tb_user> userlist = userList.Where(m => uidlist.Contains(m.id)).ToList(); string alaramperson = node.alarmtype == (int)AlarmType.Email ? string.Join(",", userlist.Select(m => m.useremail).ToArray()) : string.Join(",", userlist.Select(m => m.usermobile).ToArray()); if (x.monitorstatus == (int)MonitorStatus.Monitoring)//运行中 { #region 检测心跳 double totalsecond = Math.Abs(x.lastmonitortime.Subtract(DateTime.Now).TotalSeconds); if (totalsecond > (20+x.interval/1000) || totalsecond < 0)//大于10s 说明心跳不正常 { nodemonitorRep.UpdateById(new List<int>() { x.id }, new Dictionary<string, string>() { { "monitorstatus", ((int)NodeStatus.NoRun).ToString() } });//, { "refreshcommandqueuestatus", ((int)RefreshCommandQueueStatus.NoRefresh).ToString() } if (node.nodestatus != (int) NodeStatus.NoRun) { string title = "节点(编号):" + node.nodename + "(" + x.nodeid.ToString() + "),监控组件:" + x.classname + ",心跳异常,已自动更新为未监控状态,请及时处理该节点下该监控组件!"; StringBuilder strContent = new StringBuilder(); strContent.AppendLine("节点(编号):" + node.nodename + "(" + node.id.ToString() + ")<br/>"); strContent.AppendLine("节点监控组件名称(编号):" + x.name + "(" + x.id.ToString() + ")<br/>"); strContent.AppendLine("节点监控组件描述:" + x.discription + "<br/>"); strContent.AppendLine("节点监控类名,命名空间:" + x.classname + "," + x.classnamespace.ToString() + "<br/>"); strContent.AppendLine("节点监控组件最后一次心跳时间:" + x.lastmonitortime + "<br/>"); AlarmHelper.AlarmAsync(node.isenablealarm, (AlarmType) node.alarmtype, alaramperson, title, strContent.ToString()); } } #endregion } } catch (Exception ex) { strLog.AppendLine("监控节点监控组件异常:" + JsonConvert.SerializeObject(ex)); } }); if (strLog.Length > 0) { log.Error(strLog.ToString()); } } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraTrigger : MonoBehaviour { [SerializeField] private int _cameraID; [SerializeField]private Transform _cameraPos; private void OnTriggerEnter(Collider other) { if (other.tag =="Player") { switch (_cameraID) { case 0: { Debug.Log("Trigger Activated"); Camera.main.transform.position = _cameraPos.transform.position; Camera.main.transform.rotation = _cameraPos.transform.rotation; //Camera.main.transform.rotation = _cameraID; } break; case 1: { Camera.main.transform.position = _cameraPos.transform.position; Camera.main.transform.rotation = _cameraPos.transform.rotation; break; } case 2: { Camera.main.transform.position = _cameraPos.transform.position; Camera.main.transform.rotation = _cameraPos.transform.rotation; break; } case 3: { Camera.main.transform.position = _cameraPos.transform.position; Camera.main.transform.rotation = _cameraPos.transform.rotation; break; } case 4: { Camera.main.transform.position = _cameraPos.transform.position; Camera.main.transform.rotation = _cameraPos.transform.rotation; break; } case 5: { Camera.main.transform.position = _cameraPos.transform.position; Camera.main.transform.rotation = _cameraPos.transform.rotation; break; } } } } }
using MVP.Base.BasePresenter; using MVP.Sample.Web.IViews; namespace MVP.Sample.Web.Presenters { public class DependencyUC1Presenter : BasePresenter<IDependencyUC1, object> { public DependencyUC1Presenter(IDependencyUC1 view) : base(view) { } #region Overrides of BasePresenter<IDependencyUC1,object> protected override object Repository { get { return null; } } protected override void ViewAction() { } protected override void UpdateAction() { } protected override void DeleteAction() { } protected override void InsertAction() { } protected override void InitializeAction() { } protected override void SearchAction() { } public override void Validate() { } #endregion } }
using UnityEngine; using System.Collections; public class ObjectRemover : MonoBehaviour { void Update () { if (!Camera.main.GetComponent<StateKeeper>().inPlay) { Destroy(gameObject); } } }
using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; namespace ConsoleApplication { class Program { static void Main(string[] args) { Img(); try { string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "20.png"); Bitmap image = new Bitmap(path);//识别图像 tessnet2.Tesseract ocr = new tessnet2.Tesseract();//声明一个OCR类 //ocr.SetVariable("tessedit_char_whitelist", "0123456789+-="); //设置识别变量,当前只能识别数字。 //ocr.SetVariable("tessedit_char_whitelist", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"); //ocr.SetVariable("language_model_penalty_non_freq_dict_word", "0"); //ocr.SetVariable("language_model_penalty_non_dict_word ", "0"); //ocr.SetVariable("tessedit_char_blacklist", "xyz"); //ocr.SetVariable("classify_bln_numeric_mode", "1"); string language = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Language"); ocr.Init(language, "eng", false); //应用当前语言包。注,Tessnet2是支持多国语的。语言包下载链接:http://code.google.com/p/tesseract-ocr/downloads/list List<tessnet2.Word> result = ocr.DoOCR(image, Rectangle.Empty);//执行识别操作 foreach (tessnet2.Word word in result) { Console.WriteLine("{0} : {1}", word.Confidence, word.Text); } } catch (Exception ex) { throw; } } public static void Img() { try { //string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "20.png"); //Bitmap image = new Bitmap(path); HttpHelper httpHelper = new HttpHelper(); var d = httpHelper.HttpGet("http://www.variflight.com/flight/fnum/FM9158.html?AE71649A58c77&fdate=20161206", string.Empty, Encoding.UTF8, false, null, 6000 * 10); var imgs = GetHtmlImageUrlList(d).Where(item => item.Contains("/flight/detail")).ToArray(); string url1 = string.Format("http://www.variflight.com{0}", imgs[0]); string url2 = string.Format("http://www.variflight.com{0}", imgs[1]); string url3 = string.Format("http://www.variflight.com{0}", imgs[2]); GetValue(httpHelper, url1); GetValue(httpHelper, url2); GetValue(httpHelper, url3); } catch (Exception ex) { throw; } } private static void GetValue(HttpHelper httpHelper, string url) { var bytes = httpHelper.HttpByteGet(url, string.Empty, false, false, 60*1000); var image = Bitmap(bytes); tessnet2.Tesseract ocr = new tessnet2.Tesseract(); string language = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Language"); ocr.Init(language, "eng", false); List<tessnet2.Word> result = ocr.DoOCR(image, Rectangle.Empty); foreach (tessnet2.Word word in result) { Console.WriteLine("{0} : {1}", word.Confidence, word.Text); } } /// <summary> /// 取得HTML中所有图片的 URL。 /// </summary> /// <param name="sHtmlText">HTML代码</param> /// <returns>图片的URL列表</returns> public static string[] GetHtmlImageUrlList(string sHtmlText) { // 定义正则表达式用来匹配 img 标签 Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase); // 搜索匹配的字符串 MatchCollection matches = regImg.Matches(sHtmlText); int i = 0; string[] sUrlList = new string[matches.Count]; // 取得匹配项列表 foreach (Match match in matches) sUrlList[i++] = match.Groups["imgUrl"].Value; return sUrlList; } public static Bitmap Bitmap(byte[] bytes) { Stream memoryStream = new MemoryStream(bytes); byte[] buf = new byte[memoryStream.Length]; memoryStream.Read(buf, 0, (int)memoryStream.Length); var map = new Bitmap(Image.FromStream(memoryStream)); return map; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AlgorithmProblems.Arrays { /// <summary> /// Get the maximum distance between 2 elements in the array such that the larger element comes after the smaller element. /// For eg [3,5,6,7,81,1,2,101] should give a maximum distance of 100 (101 - 1) /// </summary> class MaxDistanceInArray { /// <summary> /// We will keep track of the min value seen till now and the maxDifference /// and keep updating the maxDifference when it is less than the currentDifference. /// Also when arr[i]<minValue then we should update the minValue and make currentDifference /// </summary> /// <param name="arr"></param> /// <returns></returns> public static int GetMaxDistanceInArray(int[] arr) { int min = int.MaxValue; int maxDifference = 0; int currentDifference = 0; for(int i=0; i<arr.Length; i++) { if (arr[i] < min) { //update min min = arr[i]; currentDifference = 0; } if(arr[i] - min > currentDifference ) { currentDifference = arr[i] - min; if(maxDifference<currentDifference) { // we have a new max difference maxDifference = currentDifference; } } } return maxDifference; } public static void TestMaxDistanceInArray() { int[] arr = new int[] { 3, 5, 6, 7, 81, 1, 2, 101 }; Console.WriteLine("The max difference is {0}. Expected:100", GetMaxDistanceInArray(arr)); arr = new int[] { 1 }; Console.WriteLine("The max difference is {0}. Expected:0", GetMaxDistanceInArray(arr)); arr = new int[] { 1, 1 }; Console.WriteLine("The max difference is {0}. Expected:0", GetMaxDistanceInArray(arr)); } } }
using System; namespace ClassLibrary2 { public class Class1 { public void Print(String input) { } } public static class utility { public static void Print(string input) { Console.WriteLine(input); } } }
using System; using AGCompressedAir.Windows.Enums; using AGCompressedAir.Windows.Models.Base; namespace AGCompressedAir.Windows.Models { public class Part : BindableModelBase<Guid> { private string _number; private PartType _type; private Guid _typeId; public string Number { get { return _number; } set { SetProperty(ref _number, value); } } public Guid TypeId { get { return _typeId; } set { SetProperty(ref _typeId, value); } } public PartType Type { get { return _type; } set { SetProperty(ref _type, value); } } } }
using System; using System.IO; public class GStream0 : Stream { protected Stream stream_0; protected string string_0; public override bool CanRead { get { return true; } } public override bool CanSeek { get { return true; } } public override bool CanWrite { get { return true; } } public override long Length { get { return this.stream_0.Length; } } public override long Position { get { return this.stream_0.Position; } set { this.stream_0.Position = value; } } public override void Close() { this.stream_0.Close(); File.Delete(this.string_0); } public GStream0() { this.string_0 = Path.GetTempFileName(); this.stream_0 = new FileStream(this.string_0, FileMode.Create, FileAccess.ReadWrite); } public override void Flush() { this.stream_0.Flush(); } public override int Read(byte[] buffer, int offset, int count) { return this.stream_0.Read(buffer, offset, count); } public override long Seek(long offset, SeekOrigin origin) { return this.stream_0.Seek(offset, origin); } public override void SetLength(long value) { this.stream_0.SetLength(value); } public override void Write(byte[] buffer, int offset, int count) { this.stream_0.Write(buffer, offset, count); } }
using AdminWebsite.Services.Models; using System; using System.Collections.Concurrent; using System.Threading.Tasks; namespace AdminWebsite.Security { public interface IClaimsCacheProvider { Task<UserRole> GetOrAddAsync(string key, Func<string, Task<UserRole>> valueFactory); } public class MemoryClaimsCacheProvider : IClaimsCacheProvider { private readonly ConcurrentDictionary<string, Task<UserRole>> _cache; public MemoryClaimsCacheProvider() { _cache = new ConcurrentDictionary<string, Task<UserRole>>(); } public async Task<UserRole> GetOrAddAsync(string key, Func<string, Task<UserRole>> valueFactory) { return await _cache.GetOrAdd(key, valueFactory); } } }
using FeedbackAndSurveyService.SurveyService.Model; namespace FeedbackAndSurveyService.SurveyService.Repository { public interface IHospitalSurveyReportGeneratorRepository { SurveyReportGenerator Get(); } }
using System; using System.Text.RegularExpressions; using UnityEngine; public class Empty : MonoBehaviour { void Awake () { string name = Application.version; string res = Regex.Replace(name.ToLower(), @"[^a-z0-9_]+", String.Empty); int version = int.Parse(res); int ver = PlayerPrefs.GetInt("version", 0); if (ver != version) { PlayerPrefs.DeleteAll(); PlayerPrefs.SetInt("version", version); Utiles.SetBool("boy", true); } Loading.LoadScene(Loading.Scenes.MENU); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EBS.Query.DTO { /// <summary> /// ztree 节点格式 /// </summary> public class CategoryTreeNode { public string id { get; set; } public string pId { get; set; } public string name { get; set; } public string text { get; set; } } }
using Cs_IssPrefeitura.Aplicacao.Interfaces; using Cs_IssPrefeitura.Dominio.Entities; using Cs_IssPrefeitura.Relatorios.Forms; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Cs_IssPrefeitura { /// <summary> /// Interaction logic for ApuracaoIss.xaml /// </summary> public partial class ApuracaoIss : Window { List<string> tipoConsulta = new List<string>(); List<string> mesesDoAno = new List<string>(); List<string> Anos = new List<string>(); private readonly IAppServicoApuracaoIss _appServicoApuracaoIss = BootStrap.Container.GetInstance<IAppServicoApuracaoIss>(); private readonly IAppServicoAtoIss _appServicoAtoIss = BootStrap.Container.GetInstance < IAppServicoAtoIss>(); private readonly IAppServicoConfiguracoes _appServicoConfiguracoes = BootStrap.Container.GetInstance<IAppServicoConfiguracoes>(); DateTime primeiroDia = new DateTime(); DateTime ultimoDia = new DateTime(); Cs_IssPrefeitura.Dominio.Entities.ApuracaoIss apuracaoSelecionada; Usuario _usuario; public ApuracaoIss(Usuario usuario) { _usuario = usuario; InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { CarregarListasConsulta(); cmbTipoConsulta.ItemsSource = tipoConsulta; cmbTipoConsulta.SelectedIndex = 0; cmbMesFechamento.ItemsSource = mesesDoAno; cmbAnoFechamento.ItemsSource = Anos; ConsultarApuracao(); } private void CarregarListasConsulta() { for (int i = 0; i < 2; i++) { if (i == 0) tipoConsulta.Add("POR ANO"); if(i == 1) tipoConsulta.Add("POR MÊS"); } for (int i = 1; i < 13; i++) { mesesDoAno.Add(string.Format("{0:00} - {1}", i, getMesPorExtenso(i))); } for (int i = DateTime.Now.Year; i >= 2011; i--) { Anos.Add(string.Format("{0}", i)); } } private void cmbTipoConsulta_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (cmbTipoConsulta.SelectedIndex == 0) { cmbDadoConsulta.ItemsSource = Anos; lblInformacao.Content = "Ano"; } else { cmbDadoConsulta.ItemsSource = mesesDoAno; lblInformacao.Content = "Mês"; } cmbDadoConsulta.SelectedIndex = 0; } private void cmbAtribuicao_PreviewKeyDown(object sender, KeyEventArgs e) { } private void btnConsultar_Click(object sender, RoutedEventArgs e) { ConsultarApuracao(); } private void ConsultarApuracao() { try { if (cmbTipoConsulta.Text == "POR ANO") { dataGridMesesfechados.ItemsSource = _appServicoApuracaoIss.ObterListaApuracaoPorAno(Convert.ToInt16(cmbDadoConsulta.Text)); } if (cmbTipoConsulta.Text == "POR MÊS") { string dadoConsulta = cmbDadoConsulta.Text.Substring(0, 2); dataGridMesesfechados.ItemsSource = _appServicoApuracaoIss.ObterListaApuracaoPorMes(Convert.ToInt16(dadoConsulta)); } if (dataGridMesesfechados.Items.Count > 0) { dataGridMesesfechados.SelectedIndex = 0; btnImprimirFechamento.IsEnabled = true; } else { btnImprimirFechamento.IsEnabled = false; } } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void dataGridMesesfechados_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e) { } private string getMesPorExtenso(int mes) { // Obtém o nome do mês por extenso string mesExtenso = System.Globalization.DateTimeFormatInfo.CurrentInfo.GetMonthName(mes).ToLower(); // retorna o nome do mês com a primeira letra em maiúscula return char.ToUpper(mesExtenso[0]) + mesExtenso.Substring(1); } private void cmbMesFechamento_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (cmbMesFechamento.SelectedIndex > -1) { cmbAnoFechamento.IsEnabled = true; ObterPrimeiroUltimoDiaMes(); } } private void cmbAnoFechamento_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (cmbAnoFechamento.SelectedIndex > -1) { btnFecharMes.IsEnabled = true; dpConsultaInicio.IsEnabled = true; dpConsultaFim.IsEnabled = true; ObterPrimeiroUltimoDiaMes(); } } private void ObterPrimeiroUltimoDiaMes() { if(cmbMesFechamento.SelectedIndex > -1 && cmbAnoFechamento.SelectedIndex >-1) { var data = Convert.ToDateTime(string.Format("{00}/{01}/{0002}", 15, cmbMesFechamento.SelectedIndex +1, cmbAnoFechamento.SelectedItem)); //pega a data que está no controle primeiroDia = new DateTime(data.Year, data.Month, 1); ultimoDia = new DateTime(data.Year, data.Month, DateTime.DaysInMonth(data.Year, data.Month)); dpConsultaInicio.SelectedDate = primeiroDia; dpConsultaFim.SelectedDate = ultimoDia; } } private void btnFecharMes_Click(object sender, RoutedEventArgs e) { if (_usuario.FechamentoMes == false) { MessageBox.Show("Usuário logado não tem permissão para Fechar Mês.", "Atenção", MessageBoxButton.OK, MessageBoxImage.Stop); return; } if(cmbMesFechamento.SelectedIndex > -1 && cmbAnoFechamento.SelectedIndex > -1) { if (dpConsultaInicio.SelectedDate != null && dpConsultaFim.SelectedDate != null) { var verificarApuracaoExistente = _appServicoApuracaoIss.ObterListaApuracaoPorMesAno(cmbMesFechamento.SelectedIndex + 1, Convert.ToInt16(cmbAnoFechamento.SelectedItem)); if (verificarApuracaoExistente.Count > 0) { MessageBox.Show("A Apuração referente ao mês e ano que foi selecionada já está fechada.", "Atenção", MessageBoxButton.OK, MessageBoxImage.Exclamation); return; } List<AtoIss> _listaAtos = _appServicoAtoIss.ListarAtosPorPeriodo(dpConsultaInicio.SelectedDate.Value, dpConsultaFim.SelectedDate.Value); if (_listaAtos.Count == 0) { MessageBox.Show("Não existe atos a serem vinculados neste período.", "Atenção", MessageBoxButton.OK, MessageBoxImage.Exclamation); return; } if (MessageBox.Show("Confirma o Fechamento do Mês de " + cmbMesFechamento.Text.Substring(5,cmbMesFechamento.Text.Length - 5).ToUpper() + " do Ano " + cmbAnoFechamento.Text + "?", "Atenção", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes) { var aguarde = new AguardeApuracaoIss(cmbMesFechamento.SelectedIndex + 1, Convert.ToInt16(cmbAnoFechamento.SelectedItem), dpConsultaInicio.SelectedDate.Value, dpConsultaFim.SelectedDate.Value); aguarde.Owner = this; aguarde.ShowDialog(); ConsultarApuracao(); } } else { MessageBox.Show("É necessário informar Data Inicial e Data Final.", "Atenção", MessageBoxButton.OK, MessageBoxImage.Warning); } } else { MessageBox.Show("É necessário informar Mês e Ano de Fechamento.", "Atenção", MessageBoxButton.OK, MessageBoxImage.Warning); } } private void cmbDadoConsulta_SelectionChanged(object sender, SelectionChangedEventArgs e) { btnConsultar.IsEnabled = true; } private void btnCancelarApuracao_Click(object sender, RoutedEventArgs e) { if (_usuario.FechamentoMes == false) { MessageBox.Show("Usuário logado não tem permissão para Cancelar Atpuração.", "Atenção", MessageBoxButton.OK, MessageBoxImage.Stop); return; } if (dataGridMesesfechados.SelectedItem != null) { apuracaoSelecionada = _appServicoApuracaoIss.GetById(((Cs_IssPrefeitura.Dominio.Entities.ApuracaoIss)dataGridMesesfechados.SelectedItem).ApuracaoIssId); if (apuracaoSelecionada.Cancelado == "SIM") { MessageBox.Show("O Fechamento selecionado foi cancelado por outro usuário.", "Atenção", MessageBoxButton.OK, MessageBoxImage.Stop); ConsultarApuracao(); return; } if (MessageBox.Show("Confirmar Cancelamento da Apuração?", "Atenção", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes) { var dataInicio = Convert.ToDateTime(apuracaoSelecionada.Periodo.Substring(0, 10)); var dataFim = Convert.ToDateTime(apuracaoSelecionada.Periodo.Substring(13, 10)); var atosIss = _appServicoAtoIss.ListarAtosPorPeriodo(dataInicio, dataFim); var aguarde = new AguardeApuracaoIss(apuracaoSelecionada, atosIss.Where(p => p.IdApuracaoIss == apuracaoSelecionada.ApuracaoIssId).ToList()); aguarde.Owner = this; aguarde.ShowDialog(); ConsultarApuracao(); } } } private void dpConsultaInicio_SelectedDateChanged(object sender, SelectionChangedEventArgs e) { if (dpConsultaInicio.SelectedDate < primeiroDia) { dpConsultaInicio.SelectedDate = primeiroDia; } if (dpConsultaInicio.SelectedDate > ultimoDia) { dpConsultaInicio.SelectedDate = ultimoDia; } if (dpConsultaInicio.SelectedDate > dpConsultaFim.SelectedDate) { dpConsultaFim.SelectedDate = dpConsultaInicio.SelectedDate; } } private void dpConsultaFim_SelectedDateChanged(object sender, SelectionChangedEventArgs e) { if (dpConsultaFim.SelectedDate > ultimoDia) { dpConsultaFim.SelectedDate = ultimoDia; } if (dpConsultaFim.SelectedDate < primeiroDia) { dpConsultaFim.SelectedDate = primeiroDia; } if (dpConsultaFim.SelectedDate < dpConsultaInicio.SelectedDate) { dpConsultaFim.SelectedDate = dpConsultaInicio.SelectedDate; } } private void dataGridMesesfechados_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (dataGridMesesfechados.SelectedItem != null) { btnCancelarApuracao.IsEnabled = true; apuracaoSelecionada = (Cs_IssPrefeitura.Dominio.Entities.ApuracaoIss)dataGridMesesfechados.SelectedItem; if (apuracaoSelecionada.Cancelado == "SIM") { MessageBox.Show("O Fechamento selecionado já foi cancelado por outro usuário.", "Atenção", MessageBoxButton.OK, MessageBoxImage.Stop); ConsultarApuracao(); } } else btnCancelarApuracao.IsEnabled = false; } private void btnImprimirFechamento_Click(object sender, RoutedEventArgs e) { if (dataGridMesesfechados.SelectedIndex > -1) { var visualizar = new FrmVisualizadorFechamentoMes(_appServicoConfiguracoes.GetById(1), (Cs_IssPrefeitura.Dominio.Entities.ApuracaoIss)dataGridMesesfechados.SelectedItem); visualizar.ShowDialog(); visualizar.Close(); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : MonoBehaviour { private string name1; private float money; private int age; public static bool requestSpeech = false; public static bool acceptSpeech = false; private Bag myBag; public GameObject pallet; void Start() { myBag = new Bag(); } void Update() { } void buyAnItem(GameObject it) { iTween.MoveTo(it, pallet.transform.position, 2f); } public void buyAnProduct() { } public string Name { get { return name1; } set { name1 = value; } } public float Money { get { return money; } set { money = value; } } public int Age { get { return age; } set { age = value; } } }
using Laoziwubo.Model.Attribute; using System; namespace Laoziwubo.Model.Content { [DataTable("Punch")] public class PunchM { [Identity(true)] [Field] public int Id { get; set; } [Field] public DateTime Date { get; set; } [Field] public int Item1 { get; set; } [Field] public int Item2 { get; set; } [Field] public int Item3 { get; set; } [Field] public string Mood { get; set; } [Field] public DateTime AddTime { get; set; } } }
using System; namespace UIMAYE.classes { public class LocalTask { public int id { get; set; } public string ad { get; set; } public int? projeId { get; set; } public int? durum { get; set; } public int? kaldigiSure { get; set; } public bool? oncelik { get; set; } } }
using System; using Atc.Tests.XUnitTestData; using Xunit; namespace Atc.Tests.Extensions { public class StringHasIsExtensionsTests { [Theory] [InlineData(false, "John Doe")] [InlineData(true, "<b>John Doe</b>")] [InlineData(true, "John Doe<hr />")] [InlineData(true, "John Doe<div class='asd'>Cow<div>")] public void HasHtmlTags(bool expected, string input) => Assert.Equal(expected, input.HasHtmlTags()); [Theory] [InlineData(true, "John Doe", "John Doe")] [InlineData(false, "John Doe", "John DOE")] public void IsEqual(bool expected, string inputA, string inputB) => Assert.Equal(expected, inputA.IsEqual(inputB)); [Theory] [InlineData(false, "John Doe", "John DOE", StringComparison.Ordinal)] [InlineData(true, "John Doe", "John DOE", StringComparison.OrdinalIgnoreCase)] [InlineData(false, "Strasse", "Straße", StringComparison.OrdinalIgnoreCase)] public void IsEqual_StringComparison(bool expected, string inputA, string inputB, StringComparison comparison) => Assert.Equal(expected, inputA.IsEqual(inputB, comparison)); [Theory] [InlineData(false, "", null, StringComparison.Ordinal, false)] [InlineData(true, "", null, StringComparison.Ordinal, true)] public void IsEqual_StringComparison_TreatNullAsEmpty(bool expected, string inputA, string inputB, StringComparison comparison, bool treatNullAsEmpty) => Assert.Equal(expected, inputA.IsEqual(inputB, comparison, treatNullAsEmpty)); [Theory] [InlineData(false, "übersetzer", "ubersetzer", StringComparison.Ordinal, false, false)] [InlineData(true, "übersetzer", "ubersetzer", StringComparison.Ordinal, false, true)] public void IsEqual_StringComparison_TreatNullAsEmpty_UseNormalizeAccents(bool expected, string inputA, string inputB, StringComparison comparison, bool treatNullAsEmpty, bool useNormalizeAccents) => Assert.Equal(expected, inputA.IsEqual(inputB, comparison, treatNullAsEmpty, useNormalizeAccents)); [Theory] [InlineData(true, "true")] [InlineData(true, "1")] [InlineData(true, "yes")] [InlineData(false, "false")] [InlineData(false, "0")] [InlineData(false, "no")] public void IsTrue(bool expected, string input) => Assert.Equal(expected, input.IsTrue()); [Theory] [InlineData(false, "true")] [InlineData(false, "1")] [InlineData(false, "yes")] [InlineData(true, "false")] [InlineData(true, "0")] [InlineData(true, "no")] public void IsFalse(bool expected, string input) => Assert.Equal(expected, input.IsFalse()); [Theory] [InlineData(true, "abc")] [InlineData(false, "123")] [InlineData(false, "abc123")] [InlineData(false, "abc123!#")] public void IsAlphaOnly(bool expected, string input) => Assert.Equal(expected, input.IsAlphaOnly()); [Theory] [InlineData(true, "abc")] [InlineData(true, "123")] [InlineData(true, "abc123")] [InlineData(false, "abc123!#")] public void IsAlphaNumericOnly(bool expected, string input) => Assert.Equal(expected, input.IsAlphaNumericOnly()); [Theory] [InlineData(true, "03-24-2000")] [InlineData(false, "24-03-2000")] public void IsDate(bool expected, string input) => Assert.Equal(expected, input.IsDate()); [Theory] [InlineData(false, "03-24-2000")] [InlineData(true, "24-03-2000")] public void IsDate_DanishCultureCulture(bool expected, string input) { var danishCultureInfo = GlobalizationConstants.DanishCultureInfo; Assert.Equal(expected, input.IsDate(danishCultureInfo)); } [Theory] [InlineData(false, "abc")] [InlineData(true, "123")] [InlineData(false, "abc123")] [InlineData(false, "abc123!#")] public void IsDigitOnly(bool expected, string input) => Assert.Equal(expected, input.IsDigitOnly()); [Theory] [InlineData(false, "abc")] [InlineData(true, "{}")] public void IsFormatJson(bool expected, string input) => Assert.Equal(expected, input.IsFormatJson()); [Theory] [InlineData(false, "abc")] [InlineData(true, "<root>abc</root>")] public void IsFormatXml(bool expected, string input) => Assert.Equal(expected, input.IsFormatXml()); [Theory] [InlineData(false, "abc")] [InlineData(true, "77C01D96-EED4-491D-9A2A-D3A4067A55EC")] [InlineData(true, "{77C01D96-EED4-491D-9A2A-D3A4067A55EC}")] public void IsGuid(bool expected, string input) => Assert.Equal(expected, input.IsGuid()); [Theory] [InlineData(false, "abc")] [InlineData(true, "77C01D96-EED4-491D-9A2A-D3A4067A55EC")] [InlineData(true, "{77C01D96-EED4-491D-9A2A-D3A4067A55EC}")] public void IsGuid_Out(bool expected, string input) => Assert.Equal(expected, input.IsGuid(out _)); [Theory] [InlineData(false, "Hest gris")] [InlineData(true, "Hest")] [InlineData(false, "123")] [InlineData(false, "123 hest")] [InlineData(false, "hest 123")] [InlineData(true, "Hest123")] [InlineData(false, "123Hest")] [InlineData(true, "Hest_123")] [InlineData(false, "123_Hest")] public void IsKey(bool expected, string input) => Assert.Equal(expected, input.IsKey()); [Theory] [InlineData(false, "")] [InlineData(false, "1")] [InlineData(true, "12")] [InlineData(false, "123")] [InlineData(true, "1234")] [InlineData(false, "12345")] public void IsLengthEven(bool expected, string input) => Assert.Equal(expected, input.IsLengthEven()); [Theory] [InlineData(false, "abc")] [InlineData(true, "123")] [InlineData(false, "abc123")] [InlineData(false, "abc123!#")] public void IsNumericOnly(bool expected, string input) => Assert.Equal(expected, input.IsNumericOnly()); [Theory] [InlineData(true, "Hest gris")] [InlineData(false, "Hest")] [InlineData(false, "123")] [InlineData(true, "123 hest")] [InlineData(true, "hest 123")] public void IsSentence(bool expected, string input) => Assert.Equal(expected, input.IsSentence()); [Theory] [InlineData(true, "Hest {0}, {1}")] [InlineData(false, "Hest {0, {1}")] [InlineData(false, "Hest {a}, {1}")] [InlineData(true, "Hest {0}, {0}")] [InlineData(false, "Hest {{0}, {0}")] [InlineData(false, "Hest {0{0}}, {0}")] [InlineData(false, "Hest {{0}0}, {0}")] public void IsStringFormatParametersBalanced(bool expected, string input) => Assert.Equal(expected, input.IsStringFormatParametersBalanced()); [Theory] [InlineData(true, "Hest {0}, {1}", false)] [InlineData(false, "Hest {0, {1}", false)] [InlineData(true, "Hest {a}, {1}", false)] [InlineData(true, "Hest {0}, {0}", false)] [InlineData(false, "Hest {{0}, {0}", false)] [InlineData(false, "Hest {0{0}}, {0}", false)] [InlineData(false, "Hest {{0}0}, {0}", false)] public void IsStringFormatParametersBalanced_IsNumeric(bool expected, string input, bool isNumeric) => Assert.Equal(expected, input.IsStringFormatParametersBalanced(isNumeric)); [Theory] [InlineData(false, "Hest gris")] [InlineData(true, "Hest")] [InlineData(false, "123")] [InlineData(false, "123 hest")] [InlineData(false, "hest 123")] [InlineData(false, "Hest123")] [InlineData(false, "123Hest")] [InlineData(false, "Hest_123")] [InlineData(false, "123_Hest")] public void IsWord(bool expected, string input) => Assert.Equal(expected, input.IsWord()); [Theory] [InlineData(false, "")] [InlineData(false, "1")] [InlineData(true, "hest")] [InlineData(false, "Hest")] public void IsFirstCharacterLowerCase(bool expected, string input) => Assert.Equal(expected, input.IsFirstCharacterLowerCase()); [Theory] [InlineData(false, "")] [InlineData(false, "1")] [InlineData(false, "hest")] [InlineData(true, "Hest")] public void IsFirstCharacterUpperCase(bool expected, string input) => Assert.Equal(expected, input.IsFirstCharacterUpperCase()); [Theory] [MemberData(nameof(TestMemberDataForExtensionsString.IsCasingStyleValidData), MemberType = typeof(TestMemberDataForExtensionsString))] public void IsCasingStyleValid(bool expected, string input, CasingStyle casingStyle) => Assert.Equal(expected, input.IsCasingStyleValid(casingStyle)); [Theory] [InlineData(false, "Hest")] [InlineData(false, "2675972")] [InlineData(true, "26759722")] public void IsCompanyCvrNumber(bool expected, string input) => Assert.Equal(expected, input.IsCompanyCvrNumber()); [Theory] [InlineData(false, "Hest")] [InlineData(false, "101342617")] [InlineData(true, "1013426178")] public void IsCompanyPNumber(bool expected, string input) => Assert.Equal(expected, input.IsCompanyPNumber()); [Theory] [InlineData(false, "Hest")] [InlineData(false, "240300-7260")] [InlineData(true, "240300-7261")] public void IsPersonCprNumber(bool expected, string input) => Assert.Equal(expected, input.IsPersonCprNumber()); [Theory] [InlineData(false, "Hest")] [InlineData(false, "Hest@gris")] [InlineData(true, "Hest@gris.dk")] public void IsEmailAddress(bool expected, string input) => Assert.Equal(expected, input.IsEmailAddress()); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HPYL.BLL { #region << 版 本 注 释 >> /*---------------------------------------------------------------- * 项目名称 :HPYL.BLL * 项目描述 : * 类 名 称 :MysqlTest * 类 描 述 : * 命名空间 :HPYL.BLL * CLR 版本 :4.0.30319.42000 * 作 者 :丁新亮 * 创建时间 :2018-07-08 10:11:56 * 更新时间 :2018-07-08 10:11:56 * 版 本 号 :v1.0.0.0 ******************************************************************* * Copyright @ DXL 2018. All rights reserved. ******************************************************************* //----------------------------------------------------------------*/ #endregion public class MysqlTest { private readonly HPYL.DAL.MysqlTest dal = new DAL.MysqlTest(); public bool Save(HPYL.Model.MysqlTest info) { return dal.Add(info); } } }
using AlgorithmProblems.Graphs.GraphHelper; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AlgorithmProblems.Graphs.GraphColoring { /// <summary> /// Check whether a given graph is Bipartiate. /// A bipartiate graph is the one whose vertices can be divided into 2 disjoint sets, such that /// each edge is starts from one set and ends up in the other set. /// </summary> class CheckBipartiteGraph { /// <summary> /// A graph is bi partite if the graph can be colored by 2 colors. /// This is similar to the approach in the ColorVertices.cs file. /// /// We will assign a color to source and do BFS on the graph. /// the next level will be colored via the second color and so on. /// While coloring a neighbour if we encounter a node which is colored with the same color as the vertex, /// then we cannot color the whole graph using 2 colors and hence the graph is not BiPartite. /// /// /// Instead of color we can just add the graph vertex to the dictionary as the key and the set number as the value. /// /// The running time is O(V+E) /// </summary> /// <returns></returns> public static bool IsBiPartiteGraph(GraphVertex source) { Queue<GraphVertex> queue = new Queue<GraphVertex>(); queue.Enqueue(source); // We can also use this dictionary to get which vertices are visited Dictionary<GraphVertex, int> vertexSetMap = new Dictionary<GraphVertex, int>(); vertexSetMap[source] = 0; while(queue.Count>0) { GraphVertex vertex = queue.Dequeue(); foreach(GraphVertex neighbour in vertex.NeighbourVertices) { if(!vertexSetMap.ContainsKey(neighbour)) { queue.Enqueue(neighbour); vertexSetMap[neighbour] = vertexSetMap[vertex] + 1 % 2; } else { // We have already visted this vertex, make sure that the color is correct if(vertexSetMap[neighbour] == vertexSetMap[vertex]) { // 2 coloring is not possible return false; } } } } return true; } public static void TestCheckBipartiteGraph() { DirectedGraph dg = GraphProbHelper.CreateDirectedGraph(); Console.WriteLine("Can the graph nodes be colored: {0}", IsBiPartiteGraph(dg.AllVertices[2])); dg.RemoveEdge(0, 1); Console.WriteLine("Can the graph nodes be colored: {0}", IsBiPartiteGraph(dg.AllVertices[2])); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace GodaddyWrapper.Requests { public class CloudSSHKeyDelete { public string sshKeyId { get; set; } } }
using System; using System.Configuration; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using BusinessObjects; namespace APIApp.Controllers { public class QuestionsController : ApiController { public IEnumerable<Question> Get() { List<Question> questions = new List<Question>(); List<Answer> answers = new List<Answer>(); List<Category> cateogorys = new List<Category>(); using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["sqldatabase"].ConnectionString)) { // Get Questions string storedProcedure = "spGetQuestions"; SqlCommand command = new SqlCommand(storedProcedure, connection); connection.Open(); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { Question question = new Question(); question.QuestionId = (int)reader["QuestionId"]; question.QuestionText = reader["QuestionText"].ToString(); question.QuestionDifficulty = (int)reader["QuestionDifficulty"]; question.Category.CategoryId = (int)reader["CategoryId"]; questions.Add(question); } reader.Close(); } // Get Question Answers storedProcedure = "spGetAnswers"; command = new SqlCommand(storedProcedure, connection); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { Answer answer = new Answer(); answer.AnswerId = (int)reader["AnswerId"]; answer.AnswerText = reader["AnswerText"].ToString(); answer.QuestionId = (int)reader["QuestionID"]; answer.CorrectAnswer = (bool)reader["CorrectAnswer"]; answers.Add(answer); } reader.Close(); } // Get Categorys storedProcedure = "spGetCategorys"; command = new SqlCommand(storedProcedure, connection); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { Category category = new Category(); category.CategoryId = (int)reader["CategoryId"]; category.CategoryName = reader["CategoryName"].ToString(); cateogorys.Add(category); } reader.Close(); } } // Populate question object with answers and category foreach (Question question in questions) { question.Category = (from c in cateogorys where c.CategoryId == question.Category.CategoryId select c).FirstOrDefault(); List<Answer> questionAnswers = (from a in answers where a.QuestionId == question.QuestionId select a).ToList(); foreach (Answer answer in questionAnswers) { question.Answers.Add(answer); } } return (IEnumerable<Question>)questions; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using _04.RepeatingCounter; using _05.BiggerThanNeighbours; namespace _06.BiggerThanNeighbousIndex { public class FindBigger { //i'm not using method from my previous task, because in task 05 this same method is bool static int[] numArray; static sbyte index; static void Main() { numArray = new int[] { 2, 4, 6, 8, 2, 4, 3, 2, 4, 6, 7, 9, 7, 5, 4, 2, 2 }; CheckCounter.ShowArray(numArray); FindFirstBiggerThanNeighbours(); Console.WriteLine("The first number bigger than it's neighbours is with index: {0}.", index); } public static sbyte FindFirstBiggerThanNeighbours() { for (index = 0; index < numArray[index]; index++) { if (index != 0 && index < numArray.Length) { if (numArray[index] > numArray[index - 1] && numArray[index] > numArray[index + 1]) { return index; } } } return -1; } } }
using gView.Framework.Data; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Text; namespace gView.DataSources.Shape { internal class DBFFileHader { public DBFFileHader(BinaryReader br) { version = br.ReadByte(); YY = br.ReadByte(); MM = br.ReadByte(); DD = br.ReadByte(); recordCount = (uint)br.ReadInt32(); headerLength = br.ReadInt16(); LegthOfEachRecord = br.ReadInt16(); Reserved1 = br.ReadInt16(); IncompleteTransac = br.ReadByte(); EncryptionFlag = br.ReadByte(); FreeRecordThread = (uint)br.ReadInt32(); Reserved2 = br.ReadInt32(); Reserved3 = br.ReadInt32(); MDX = br.ReadByte(); LanguageDriver = br.ReadByte(); Reserved4 = br.ReadInt16(); } public static bool Write(BinaryWriter bw, FieldCollection fields) { if (bw == null || fields == null) { return false; } int c = 0, rl = 1; // deleted Flag foreach (IField field in fields.ToEnumerable()) { switch (field.type) { case FieldType.biginteger: c++; rl += 18; break; case FieldType.boolean: c++; rl += 1; break; case FieldType.character: c++; rl += 1; break; case FieldType.Date: c++; rl += 8; break; case FieldType.Double: c++; rl += 31; break; case FieldType.Float: c++; rl += 11; break; case FieldType.ID: c++; rl += 9; break; case FieldType.integer: c++; rl += 9; break; case FieldType.Shape: break; case FieldType.smallinteger: c++; rl += 6; break; case FieldType.String: c++; rl += (field.size > 255) ? 255 : field.size; break; default: c++; rl += (field.size <= 0) ? 255 : field.size; break; } } short hLength = (short)(32 * c + 33); bw.Write((byte)3); // Version bw.Write((byte)106); // YY bw.Write((byte)6); // MM bw.Write((byte)12); // DD bw.Write((int)0); // recordCount bw.Write(hLength); // headerLength bw.Write((short)rl); // Length of each record bw.Write((short)0); // Reserved1 bw.Write((byte)0); // IncompleteTransac bw.Write((byte)0); // EncryptionFlag bw.Write((int)0); // FreeRecordThread bw.Write((int)0); // Reserved2 bw.Write((int)0); // Reserved3 bw.Write((byte)0); // MDX bw.Write((byte)CodePage.DOS_Multilingual); // LanguageDriver Codepage 850 bw.Write((short)0); // Reserved4 foreach (IField field in fields.ToEnumerable()) { FieldDescriptor.Write(bw, field); } bw.Write((byte)13); // Terminator 0x0D return true; } public int FieldsCount { get { return (headerLength - 1) / 32 - 1; } } public byte version; public byte YY, MM, DD; public uint recordCount; public short headerLength; public short LegthOfEachRecord; public short Reserved1; public byte IncompleteTransac; public byte EncryptionFlag; public uint FreeRecordThread; public int Reserved2; public int Reserved3; public byte MDX; public byte LanguageDriver; public short Reserved4; } internal class FieldDescriptor { public FieldDescriptor(BinaryReader br) { br.Read(fieldName, 0, 11); FieldType = br.ReadChar(); FieldDataAddress = (uint)br.ReadInt32(); FieldLength = br.ReadByte(); DecimalCount = br.ReadByte(); Reserved1 = br.ReadInt16(); WorkAreaID = br.ReadByte(); Reserved2 = br.ReadInt16(); FlagForSET_FIELDS = br.ReadByte(); Reserved3 = br.ReadByte(); Reserved4 = br.ReadByte(); Reserved5 = br.ReadByte(); Reserved6 = br.ReadByte(); Reserved7 = br.ReadByte(); Reserved8 = br.ReadByte(); Reserved9 = br.ReadByte(); IndexFieldFlag = br.ReadByte(); } public static bool Write(BinaryWriter bw, IField field) { if (bw == null || field == null) { return false; } byte decimalCount = 0, fieldLength = 0; char fieldType = 'C'; switch (field.type) { case gView.Framework.Data.FieldType.biginteger: fieldLength = 18; fieldType = 'N'; break; case gView.Framework.Data.FieldType.boolean: fieldLength = 1; fieldType = 'L'; break; case gView.Framework.Data.FieldType.character: fieldLength = 1; fieldType = 'C'; break; case gView.Framework.Data.FieldType.Date: fieldLength = 8; fieldType = 'D'; break; case gView.Framework.Data.FieldType.Double: fieldLength = 31; decimalCount = 31; fieldType = 'F'; break; case gView.Framework.Data.FieldType.Float: fieldLength = 11; fieldType = 'F'; break; case gView.Framework.Data.FieldType.ID: fieldLength = 9; fieldType = 'N'; break; case gView.Framework.Data.FieldType.integer: fieldLength = 9; fieldType = 'N'; break; case gView.Framework.Data.FieldType.Shape: return false; case gView.Framework.Data.FieldType.smallinteger: fieldLength = 6; fieldType = 'N'; break; case gView.Framework.Data.FieldType.String: fieldLength = (byte)(field.size > 255 ? 255 : field.size); fieldType = 'C'; break; default: fieldLength = (byte)(field.size > 0 ? field.size : 255); fieldType = 'C'; break; } // fieldName for (int i = 0; i < 10; i++) { if (i < field.name.Length) { bw.Write((byte)field.name[i]); } else { bw.Write((byte)0); } } bw.Write((byte)0); bw.Write((byte)fieldType); // FieldType bw.Write((int)0); // FieldDataAddress bw.Write((byte)fieldLength); // FieldLength bw.Write((byte)decimalCount); // DecimalCount bw.Write((short)0); // Reserved1 bw.Write((byte)0); // WorkAreaID bw.Write((short)0); // Reserved2 bw.Write((byte)0); // FlagForSET_FIELDS bw.Write((byte)0); // Reserved3 bw.Write((byte)0); // Reserved4 bw.Write((byte)0); // Reserved5 bw.Write((byte)0); // Reserved6 bw.Write((byte)0); // Reserved7 bw.Write((byte)0); // Reserved8 bw.Write((byte)0); // Reserved9 bw.Write((byte)0); // IndexFieldFlag return true; } public string FieldName { get { char[] trims = { '\0' }; System.Text.ASCIIEncoding encoder = new System.Text.ASCIIEncoding(); return encoder.GetString(fieldName).TrimEnd(trims); } } private byte[] fieldName = new byte[11]; public char FieldType; public uint FieldDataAddress; public byte FieldLength; public byte DecimalCount; public short Reserved1; public byte WorkAreaID; public short Reserved2; public byte FlagForSET_FIELDS; public byte Reserved3; public byte Reserved4; public byte Reserved5; public byte Reserved6; public byte Reserved7; public byte Reserved8; public byte Reserved9; public byte IndexFieldFlag; } internal enum CodePage { DOS_USA = 0x01, DOS_Multilingual = 0x02, Windows_ANSI = 0x03, EE_MS_DOS = 0x64, Nordic_MS_DOS = 0x65, Russian_MS_DOS = 0x66, Windows_EE = 0xc8, UTF_7 = 0x57 } internal class DBFFile { private string _filename; private DBFFileHader _header; private List<FieldDescriptor> _fields; private Encoding _encoder = null; private char[] _trims = { '\0', ' ' }; private static IFormatProvider _nhi = System.Globalization.CultureInfo.InvariantCulture.NumberFormat; private string _idField = "FID"; public DBFFile(string filename) { try { FileInfo fi = new FileInfo(filename); if (!fi.Exists) { return; } _filename = filename; StreamReader sr = new StreamReader(filename); BinaryReader br = new BinaryReader(sr.BaseStream); _header = new DBFFileHader(br); _fields = new List<FieldDescriptor>(); for (int i = 0; i < _header.FieldsCount; i++) { FieldDescriptor field = new FieldDescriptor(br); _fields.Add(field); } sr.Close(); int c = 1; string idFieldName = _idField; while (HasField(idFieldName)) { idFieldName = _idField + "_" + c++; } _idField = idFieldName; _encoder = null; try { switch ((CodePage)_header.LanguageDriver) { case CodePage.DOS_USA: _encoder = EncodingFromCodePage(437); break; case CodePage.DOS_Multilingual: _encoder = EncodingFromCodePage(850); break; case CodePage.Windows_ANSI: _encoder = EncodingFromCodePage(1252); break; case CodePage.EE_MS_DOS: _encoder = EncodingFromCodePage(852); break; case CodePage.Nordic_MS_DOS: _encoder = EncodingFromCodePage(865); break; case CodePage.Russian_MS_DOS: _encoder = EncodingFromCodePage(866); break; case CodePage.Windows_EE: _encoder = EncodingFromCodePage(1250); break; case CodePage.UTF_7: _encoder = new UTF7Encoding(); break; } } catch { } if (_encoder == null) { FileInfo encFi = new FileInfo(fi.Directory.FullName + @"/dbf_default_encoding.txt"); if (encFi.Exists) { using (StreamReader encSr = new StreamReader(encFi.FullName)) { switch (encSr.ReadLine().ToLower()) { case "utf8": case "utf-8": _encoder = new UTF8Encoding(); break; case "unicode": _encoder = new UnicodeEncoding(); break; case "ascii": _encoder = new ASCIIEncoding(); break; } } } if (_encoder == null) { _encoder = new UTF7Encoding(); } } //Record(0); //Record(1); } catch { } } private Encoding EncodingFromCodePage(int codePage) { foreach (EncodingInfo ei in Encoding.GetEncodings()) { if (ei.CodePage == codePage) { return ei.GetEncoding(); } } return null; } private bool HasField(string name) { foreach (FieldDescriptor fd in _fields) { if (fd.FieldName == name) { return true; } } return false; } public string Filename { get { return _filename; } } internal DataTable DataTable() { return DataTable(null); } internal DataTable DataTable(string[] fieldnames) { DataTable tab = new DataTable(); if (fieldnames != null) { foreach (string fieldname in fieldnames) { if (fieldname == _idField) { tab.Columns.Add(_idField, typeof(uint)); } foreach (FieldDescriptor field in _fields) { if (field.FieldName == fieldname) { if (tab.Columns[fieldname] == null) { tab.Columns.Add(fieldname, DataType(field)); } } } } } else { tab.Columns.Add(_idField, typeof(uint)); foreach (FieldDescriptor field in _fields) { if (tab.Columns[field.FieldName] == null) { tab.Columns.Add(field.FieldName, DataType(field)); } } } return tab; } private Type DataType(FieldDescriptor fd) { switch (fd.FieldType) { case 'C': return typeof(string); case 'F': case 'N': if (fd.DecimalCount == 0) { if (fd.FieldLength <= 6) { return typeof(short); } if (fd.FieldLength <= 9) { return typeof(int); } return typeof(long); } else // if( fd.DecimalCount==9 && fd.FieldLength==31 ) { if (fd.DecimalCount <= 9) { return typeof(float); } return typeof(double); } case 'L': return typeof(bool); case 'D': return typeof(DateTime); case 'I': return typeof(int); case 'O': return typeof(double); case '+': return typeof(int); // Autoincrement default: return typeof(string); } } private FieldType FieldType(FieldDescriptor fd) { switch (fd.FieldType) { case 'C': return gView.Framework.Data.FieldType.String; case 'F': case 'N': if (fd.DecimalCount == 0) { if (fd.FieldLength <= 6) { return gView.Framework.Data.FieldType.smallinteger; } if (fd.FieldLength <= 9) { return gView.Framework.Data.FieldType.integer; } return gView.Framework.Data.FieldType.biginteger; } else // if( fd.DecimalCount==9 && fd.FieldLength==31 ) { if (fd.DecimalCount <= 9) { return gView.Framework.Data.FieldType.Float; } return gView.Framework.Data.FieldType.Double; } case 'L': return gView.Framework.Data.FieldType.boolean; case 'D': return gView.Framework.Data.FieldType.Date; case 'I': return gView.Framework.Data.FieldType.integer; case 'O': return gView.Framework.Data.FieldType.Double; case '+': return gView.Framework.Data.FieldType.integer; // Autoincrement default: return gView.Framework.Data.FieldType.String; } } public DataTable Record(uint index) { return Record(index, "*"); } public DataTable Record(uint index, string fieldnames) { StreamReader sr = new StreamReader(_filename); BinaryReader br = new BinaryReader(sr.BaseStream); string[] names = null; fieldnames = fieldnames.Replace(" ", ""); if (fieldnames != "*") { names = fieldnames.Split(','); } DataTable tab = DataTable(names); Record(index, tab, br); sr.Close(); return tab; } internal void Record(uint index, DataTable tab, BinaryReader br) { if (index > _header.recordCount || index < 1) { return; } br.BaseStream.Position = _header.headerLength + _header.LegthOfEachRecord * (index - 1); char deleted = br.ReadChar(); if (deleted != ' ') { return; } DataRow row = tab.NewRow(); foreach (FieldDescriptor field in _fields) { if (tab.Columns[field.FieldName] == null) { br.BaseStream.Position += field.FieldLength; continue; } switch ((char)field.FieldType) { case 'C': row[field.FieldName] = _encoder.GetString(br.ReadBytes(field.FieldLength)).TrimEnd(_trims); break; case 'F': case 'N': string str2 = _encoder.GetString(br.ReadBytes(field.FieldLength)).TrimEnd(_trims); if (str2 != "") { try { if (field.DecimalCount == 0) { row[field.FieldName] = Convert.ToInt64(str2); } else { row[field.FieldName] = double.Parse(str2, _nhi); } } catch { } } break; case '+': case 'I': row[field.FieldName] = br.ReadInt32(); break; case 'O': row[field.FieldName] = br.ReadDouble(); break; case 'L': char c = br.ReadChar(); if (c == 'Y' || c == 'y' || c == 'T' || c == 't') { row[field.FieldName] = true; } else if (c == 'N' || c == 'n' || c == 'F' || c == 'f') { row[field.FieldName] = false; } else { row[field.FieldName] = null; } break; case 'D': string date = _encoder.GetString(br.ReadBytes(field.FieldLength)).TrimEnd(_trims); if (date.Length == 8) { int y = int.Parse(date.Substring(0, 4)); int m = int.Parse(date.Substring(4, 2)); int d = int.Parse(date.Substring(6, 2)); DateTime td = new DateTime(y, m, d); row[field.FieldName] = td; } break; } } if (tab.Columns[_idField] != null) { row[_idField] = index; } tab.Rows.Add(row); } internal void Records(DataTable tab, BinaryReader br) { uint rowCount = _header.recordCount; for (uint i = 0; i < rowCount; i++) { br.BaseStream.Position = _header.headerLength + _header.LegthOfEachRecord * (i); char deleted = br.ReadChar(); if (deleted != ' ') { continue; } DataRow row = tab.NewRow(); foreach (FieldDescriptor field in _fields) { if (tab.Columns[field.FieldName] == null) { br.BaseStream.Position += field.FieldLength; continue; } switch ((char)field.FieldType) { case 'C': row[field.FieldName] = _encoder.GetString(br.ReadBytes(field.FieldLength)).TrimEnd(_trims); break; case 'F': case 'N': string str2 = _encoder.GetString(br.ReadBytes(field.FieldLength)).TrimEnd(_trims); if (str2 != "") { try { if (field.DecimalCount == 0) { row[field.FieldName] = long.Parse(str2); } else { row[field.FieldName] = double.Parse(str2, _nhi); } } catch { } } break; case '+': case 'I': row[field.FieldName] = br.ReadInt32(); break; case 'O': row[field.FieldName] = br.ReadDouble(); break; case 'L': char c = br.ReadChar(); if (c == 'Y' || c == 'y' || c == 'T' || c == 't') { row[field.FieldName] = true; } else if (c == 'N' || c == 'n' || c == 'F' || c == 'f') { row[field.FieldName] = false; } else { row[field.FieldName] = null; } break; case 'D': string date = _encoder.GetString(br.ReadBytes(field.FieldLength)).TrimEnd(_trims); if (date.Length == 8) { int y = int.Parse(date.Substring(0, 4)); int m = int.Parse(date.Substring(4, 2)); int d = int.Parse(date.Substring(6, 2)); DateTime td = new DateTime(y, m, d); row[field.FieldName] = td; } break; } } if (tab.Columns[_idField] != null) { row[_idField] = i + 1; } tab.Rows.Add(row); } } #region Writer public static bool Create(string filename, FieldCollection fields) { try { FileInfo fi = new FileInfo(filename); if (fi.Exists) { fi.Delete(); } StreamWriter sw = new StreamWriter(filename); BinaryWriter bw = new BinaryWriter(sw.BaseStream); bool ret = DBFFileHader.Write(bw, fields); bw.Flush(); sw.Flush(); sw.Close(); return ret; } catch { return false; } } internal bool WriteRecord(uint index, IFeature feature) { if (feature == null) { return false; } FileStream fs = null; BinaryWriter bw = null; BinaryReader br = null; try { fs = new FileStream(_filename, FileMode.Open); bw = new BinaryWriter(fs); long pos0 = bw.BaseStream.Position = _header.headerLength + _header.LegthOfEachRecord * (index - 1); long posX = 1; bw.Write((byte)' '); // deleted Flag string str; foreach (FieldDescriptor fd in _fields) { object obj = feature[fd.FieldName]; if (obj == null || obj == DBNull.Value) { WriteNull(fd, bw); } else { try { switch (fd.FieldType) { case 'C': str = obj.ToString().PadRight(fd.FieldLength, ' '); WriteString(fd, bw, str); break; case 'N': case 'F': if (fd.DecimalCount == 0) { str = Convert.ToInt32(obj).ToString(); str = str.PadLeft(fd.FieldLength, ' '); WriteString(fd, bw, str); } else { str = Convert.ToDouble(obj).ToString(_nhi); str = str.PadLeft(fd.FieldLength, ' '); WriteString(fd, bw, str); } break; case '+': case 'I': bw.Write(Convert.ToInt32(obj)); break; case 'O': bw.Write(Convert.ToDouble(obj)); break; case 'L': bool v = Convert.ToBoolean(obj); str = (v) ? "T" : "F"; WriteString(fd, bw, str); break; case 'D': DateTime td = Convert.ToDateTime(obj); str = td.Year.ToString().PadLeft(4, '0') + td.Month.ToString().PadLeft(2, '0') + td.Day.ToString().PadLeft(2, '0'); WriteString(fd, bw, str); break; default: WriteNull(fd, bw); break; } } catch { WriteNull(fd, bw); } } posX += fd.FieldLength; bw.BaseStream.Position = pos0 + posX; } br = new BinaryReader(fs); br.BaseStream.Position = 4; uint recCount = (uint)br.ReadInt32(); DateTime now = DateTime.Now; bw.BaseStream.Position = 1; bw.Write((byte)(now.Year - 1900)); bw.Write((byte)now.Month); bw.Write((byte)now.Day); bw.Write((int)recCount + 1); fs.Flush(); return true; } catch (Exception ex) { string err = ex.Message; return false; } finally { if (fs != null) { fs.Close(); } } } private void WriteNull(FieldDescriptor fd, BinaryWriter bw) { for (int i = 0; i < fd.FieldLength; i++) { bw.Write((byte)' '); } } private void WriteString(FieldDescriptor fd, BinaryWriter bw, string str) { byte[] bytes = _encoder.GetBytes(str); for (int i = 0; i < fd.FieldLength; i++) { if (i < bytes.Length) { bw.Write((byte)bytes[i]); } else { bw.Write((byte)0); } } } #endregion public IFieldCollection Fields { get { FieldCollection fields = new FieldCollection(); // ID Field field = new Field(); field.name = _idField; field.type = gView.Framework.Data.FieldType.ID; fields.Add(field); foreach (FieldDescriptor fd in _fields) { field = new Field(); field.name = fd.FieldName; field.size = fd.FieldLength; field.precision = fd.DecimalCount; field.type = FieldType(fd); fields.Add(field); } return fields; } } } internal class DBFDataReader { private DBFFile _file; private StreamReader _sr = null; private BinaryReader _br = null; private DataTable _tab; public DBFDataReader(DBFFile file, string fieldnames) { if (file == null) { return; } _file = file; _sr = new StreamReader(_file.Filename); _br = new BinaryReader(_sr.BaseStream); string[] names = null; fieldnames = fieldnames.Replace(" ", ""); if (fieldnames != "*") { names = fieldnames.Split(','); } _tab = _file.DataTable(names); } public DataTable AllRecords { get { if (_file == null) { return null; } _file.Records(_tab, _br); return _tab; } } public void AddRecord(uint index) { _file.Record(index, _tab, _br); } public void Clear() { _tab.Rows.Clear(); } public DataTable Table { get { return _tab; } } public void Dispose() { if (_tab != null) { _tab.Rows.Clear(); _tab.Dispose(); _tab = null; } if (_sr != null) { _sr.Close(); _sr = null; } } } internal class DBFDataWriter { public DBFDataWriter() { } } }
using System; using HomeAutomation.Referential.Enums; namespace HomeAutomation.Referential.Models { public class Room : Thing { public Room() { } public Room(Guid id, string label, RoomTypeEnum type) : base(id, label) { Type = type; } public RoomTypeEnum Type { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using Tomelt.ContentManagement; using Tomelt.DisplayManagement.Implementation; using Tomelt.Templates.Models; namespace Tomelt.Templates.Services { public class DefaultTemplateService : ITemplateService { public const string TemplatesSignal = "Tomelt.Templates"; private readonly IEnumerable<ITemplateProcessor> _processors; public DefaultTemplateService(IEnumerable<ITemplateProcessor> processors) { _processors = processors; } public string Execute<TModel>(string template, string name, string processorName, TModel model = default(TModel)) { return Execute(template, name, processorName, null, model); } public string Execute<TModel>(string template, string name, string processorName, DisplayContext context, TModel model = default(TModel)) { var processor = _processors.FirstOrDefault(x => String.Equals(x.Type, processorName, StringComparison.OrdinalIgnoreCase)) ?? _processors.First(); return processor.Process(template, name, context, model); } } }
namespace CheckIt.Syntax { using System.Collections; public interface ICheckClasses : IClasses { IPatternContains<IClassMatcher, ICheckClassesContains> FromAssembly(string pattern); IPatternContains<IClassMatcher, ICheckClassesContains> FromProject(string pattern); IPatternContains<IClassMatcher, ICheckClassesContains> FromFile(string pattern); ICheckClasses Not(); } }
using System; using System.Linq; using DelftTools.Hydro; using DelftTools.Hydro.CrossSections; using DelftTools.Hydro.Helpers; using GeoAPI.Geometries; using GisSharpBlog.NetTopologySuite.Geometries; using NetTopologySuite.Extensions.Networks; using NUnit.Framework; namespace DelftTools.Tests.Hydo.Helpers { [TestFixture] public class CrossSectionConverterTest { [Test] public void ConvertXYZCrossSectionToYz() { var crossSection = new CrossSectionDefinitionXYZ(); crossSection.Geometry = new LineString(new ICoordinate[] {new Coordinate(-3, 0, 0), new Coordinate(0, 4, -5), new Coordinate(3, 0, 0)}); crossSection.XYZDataTable[1].DeltaZStorage = 1; /*crossSection.SetWithHfswData(new[] { new HeightFlowStorageWidth(0, 10, 10), new HeightFlowStorageWidth(10, 20, 16) });*/ var yzCrossSection = CrossSectionConverter.ConvertToYz(crossSection); var yQ = new[] {0, 5, 10}; var z= new[] {0,-5, 0}; var deltaZStorage = new[] {0, 1, 0}; Assert.AreEqual(yQ,yzCrossSection.YZDataTable.Select(r=>r.Yq).ToArray()); Assert.AreEqual(z, yzCrossSection.YZDataTable.Select(r => r.Z).ToArray()); Assert.AreEqual(deltaZStorage, yzCrossSection.YZDataTable.Select(r => r.DeltaZStorage).ToArray()); } } }
using ESRI.ArcGIS.Geodatabase; using LoowooTech.Stock.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LoowooTech.Stock.ArcGISTool { public class TopoTool:ArcGISBaseTool { public string Name { get { return string.Format("图层【{0}】重叠相交核查;",LayerName); } } public string LayerName { get; set; } private string _featureClassName { get { return string.Format("{0}_intersect", LayerName); } } public string Key { get; set; } public List<VillageMessage> Messages { get; set; } = new List<VillageMessage>(); public bool Check(IWorkspace workspace) { IFeatureClass featureClass = workspace.GetFeatureClass(_featureClassName); if (featureClass == null) { Messages.Add(new VillageMessage { Description = string.Format("获取要素类【{0}】失败", _featureClassName) }); return false; } var fidName1 = string.Format("FID_{0}", LayerName); var fidName2 = string.Format("FID_{0}_1", LayerName); var key2 = string.Format("{0}_1", Key); var index1 = featureClass.Fields.FindField(Key); var index2 = featureClass.Fields.FindField(key2); if (index1 < 0 || index2 < 0) { Messages.Add(new VillageMessage { Description = string.Format("在要素类【{0}】中未获取字段【{1}/{2}】的序号", _featureClassName, Key, key2) }); return false; } IQueryFilter queryFilter = new QueryFilterClass(); queryFilter.WhereClause = string.Format("[{0}] <> [{1}]", fidName1, fidName2); IFeatureCursor featureCursor = featureClass.Search(queryFilter, false); IFeature feature = featureCursor.NextFeature(); while (feature != null) { var keyValue1 = feature.get_Value(index1).ToString(); var keyValue2 = feature.get_Value(index2).ToString(); if (string.IsNullOrEmpty(keyValue1) == false && string.IsNullOrEmpty(keyValue2) == false) { Messages.Add(new VillageMessage { Value = keyValue1, Description = string.Format("【{0}】:{1} 与【{0}】:{2}存在重叠相交;", Key, keyValue1, keyValue2), WhereClause = string.Format("[{0}] = '{1}'", Key, keyValue1) }); } feature = featureCursor.NextFeature(); } System.Runtime.InteropServices.Marshal.ReleaseComObject(featureCursor); return true; } } }
using gView.Framework.system; using System; using System.Windows.Forms; namespace gView.Interoperability.GeoServices.Dataset { public partial class FormNewConnection : Form { public FormNewConnection() { InitializeComponent(); cmbServerType.SelectedIndex = 0; cbUseHttps.Checked = true; } public string ConnectionString { get { var server = txtServer.Text; if (!server.ToLower().StartsWith("http://") || !server.ToLower().StartsWith("https://")) { server = (cbUseHttps.Checked == true ? "https://" : "http://") + server; } server = server.UrlRemoveEndingSlashes(); if (!server.ToLower().EndsWith("/services")) { switch (cmbServerType.SelectedIndex) { case 0: server += "/arcgis/rest/services"; break; case 1: server += "/geoservices/rest/services"; break; } } return "server=" + server + ";user=" + txtUser.Text + ";pwd=" + txtPwd.Text; } } private void btnOK_Click(object sender, EventArgs e) { } #region Helper #endregion } }
using Model.EF; using Model.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Model.DAO { public class UserUserGroupDepartmentDAO { DocumentManagementDbContext db = null; public UserUserGroupDepartmentDAO() { db = new DocumentManagementDbContext(); } public UserUserGroupDepartment GetByID(long id) { var model = from u in db.Users join ug in db.UserGroups on u.GroupID equals ug.ID join d in db.Departments on u.DepartmentID equals d.ID orderby u.CreatedDate descending select new UserUserGroupDepartment() { ID = u.ID, UserName = u.UserName, Password = u.Password, GroupID = u.GroupID, Name = u.Name, CreatedDate = u.CreatedDate, ModifiedDate = u.ModifiedDate, CreatedBy = u.CreatedBy, ModifiedBy = u.ModifiedBy, Status = u.Status, Address = u.Address, Phone = u.Phone, Email = u.Email, GroupName = ug.Name, DepartmentName = d.Name, Avatar = u.Avatar }; return model.SingleOrDefault(x => x.ID == id); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class SignIn : MonoBehaviour { public InputField usernameField; public InputField passwordField; public InputField categoryField; public Button submitButton; public GameObject IncorrectPanel; public void CallLogin() { StartCoroutine(LogIn()); } IEnumerator LogIn() { WWWForm form = new WWWForm(); form.AddField("username", usernameField.text); form.AddField("password", passwordField.text); form.AddField("category", categoryField.text); WWW www = new WWW("https://organizacijaradaknjiznice.000webhostapp.com/SignIn.php", form); yield return www; if (www.text == "0") { DBManager.username = usernameField.text; DBManager.category = categoryField.text; if (DBManager.category == "korisnik") { UnityEngine.SceneManagement.SceneManager.LoadScene("UserProfileScene"); } else { UnityEngine.SceneManagement.SceneManager.LoadScene("AdminProfileScene"); } } else { Debug.Log(www.text); IncorrectPanel.gameObject.SetActive(true); } } public void VerifyInput() { submitButton.interactable = (usernameField.text.Length >= 4 && passwordField.text.Length >= 7); } }
using System; namespace MonoDevelop.NUnit.Commands { public enum TestCommands { RunAllTests, RunTest, RunTestWith, ShowTestCode, SelectTestInTree, ShowTestDetails, GoToFailure } }
#if UNITY_2019_1_OR_NEWER using UnityEditor; using UnityAtoms.Editor; namespace UnityAtoms.MonoHooks.Editor { /// <summary> /// Variable property drawer of type `ColliderGameObject`. Inherits from `AtomDrawer&lt;ColliderGameObjectVariable&gt;`. Only availble in `UNITY_2019_1_OR_NEWER`. /// </summary> [CustomPropertyDrawer(typeof(ColliderGameObjectVariable))] public class ColliderGameObjectVariableDrawer : VariableDrawer<ColliderGameObjectVariable> { } } #endif
using System; namespace SudokuSolver.Exceptions { public class InvalidValueException : Exception { } }
using System; using System.IO; using System.Linq; using Ajf.NugetWatcher.Settings; using JCI.ITC.Nuget.TopShelf; using Newtonsoft.Json; using Serilog; namespace Ajf.NugetWatcher { public class WorkerDirWatcher : BaseWorker, IDisposable { private readonly INugetWatcherSettings _nugetWatcherSettings; private readonly IMailSenderService _mailSenderService; private FileSystemWatcher _fileSystemWatcher; public WorkerDirWatcher(IMailSenderService mailSenderService, INugetWatcherSettings nugetWatcherSettings) { _mailSenderService = mailSenderService; _nugetWatcherSettings = nugetWatcherSettings; } public void Dispose() { Stop(); } public override void Start() { try { Log.Logger.Information("Starting WorkerDirWatcher"); var nugetWatcherSettings = new NugetWatcherSettings(); _fileSystemWatcher = new FileSystemWatcher(nugetWatcherSettings.PathToNuget); _fileSystemWatcher.Changed += OnChanged; _fileSystemWatcher.Created += OnChanged; _fileSystemWatcher.Deleted += OnChanged; _fileSystemWatcher.Renamed += OnRenamed; _fileSystemWatcher.EnableRaisingEvents = true; Log.Logger.Information("WorkerDirWatcher started"); } catch (Exception ex) { Log.Error(ex, "During Start", new object[0]); throw; } } private void OnRenamed(object sender, RenamedEventArgs e) { try { var httpStatusCode = _mailSenderService .SendMail("[NugetWatcher] Nuget Rename " + JsonConvert.SerializeObject(e), "", "<b>hello</b>", "andersjuulsfirma@gmail.com;Anders", new[] { "andersjuulsfirma@gmail.com;Anders" }) ; } catch (Exception exception) { Log.Logger.Error(exception, "During on renamed"); throw; } } private void OnChanged(object sender, FileSystemEventArgs e) { try { Log.Logger.Information("Change detected: " + JsonConvert.SerializeObject(e)); var path = e.FullPath; var enumerateDirectories = Directory.EnumerateDirectories(path); var datedDirs = enumerateDirectories.Select(x => new DatedDir { Path = x, Ts = Directory.GetLastWriteTime(x) }) .OrderByDescending(xx => xx.Ts); var latest = datedDirs.FirstOrDefault(); if (latest == null) return; var httpStatusCode = _mailSenderService .SendMail($"[NugetWatcher] {latest.Path} {latest.Ts}", "", $"<b>This was send from {_nugetWatcherSettings.SuiteName}.{_nugetWatcherSettings.ComponentName}, {_nugetWatcherSettings.Environment}, {_nugetWatcherSettings.ReleaseNumber} at {DateTime.Now:yyyy-MM-dd HH.mm.ss}</b>", "andersjuulsfirma@gmail.com;Anders",_nugetWatcherSettings.NotificationReceivers ) ; } catch (Exception exception) { Log.Logger.Error(exception,"During on changed"); } } public override void Stop() { Log.Logger.Information("Stopping worker"); if (_fileSystemWatcher != null) { _fileSystemWatcher.Dispose(); _fileSystemWatcher = null; } Log.Logger.Information("WorkerDirWatcher stopped"); } } internal class DatedDir { public string Path { get; set; } public DateTime Ts { get; set; } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; namespace MobilePhoneRetailer.DataLayer { public class ProductMapper { public static string GetProductID(Product p) { string connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString; SqlConnection con = new SqlConnection(connectionString); //String sql = "INSERT INTO [Products] VALUES(@Price, @Type,NULL)"; try { int pID = 0; SqlDataReader reader; SqlCommand cmd = new SqlCommand("SELECT ProductID FROM [Products] WHERE ProductID = (SELECT MAX(ProductID) FROM [Products])", con); try { con.Open(); reader = cmd.ExecuteReader(); while (reader.Read()) { pID = Convert.ToInt32(reader["ProductID"]); pID++; } reader.Close(); p.ProductID = pID; con.Close(); } catch (SqlException sqlEx) { return (sqlEx.Message); } return "complete"; } catch (SqlException sqlEx) { return (sqlEx.Message); } } public static string AddProduct(Product p) { string connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString; SqlConnection connection = new SqlConnection(connectionString); String sql = "INSERT INTO [Products] VALUES(@ProductID ,@Price, @Type, @SupplierID)"; //if there is an error with the data it will catch the exception and display an error try { if (p.ProductID > 0) { connection.Open(); SqlCommand command = new SqlCommand(sql, connection); command.Parameters.Add("@ProductID", SqlDbType.Int); command.Parameters["@ProductID"].Value = p.ProductID; command.Parameters.Add("@Price", SqlDbType.Float); command.Parameters["@Price"].Value = p.Price; command.Parameters.Add("@Type", SqlDbType.NVarChar); command.Parameters["@Type"].Value = p.Type; command.Parameters.Add("@SupplierID", SqlDbType.Int); command.Parameters["@SupplierID"].Value = p.SupplierID; command.ExecuteNonQuery(); connection.Close(); return "complete"; } else return "ProductID <= 0 for some reason - ProductMapper"; } catch (SqlException sqlEx) { return (sqlEx.Message); } } public static string editProduct(Product p) { string connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString; SqlConnection connection = new SqlConnection(connectionString); String sql = "UPDATE [Products] SET Price = @Price, Type = @Type," + "SupplierID = @SupplierID WHERE ProductID = @ProductID"; //if there is an error with the data it will catch the exception and display an error try { if (p.ProductID > 0) { connection.Open(); SqlCommand command = new SqlCommand(sql, connection); command.Parameters.Add("@Price", SqlDbType.Float); command.Parameters["@Price"].Value = p.Price; command.Parameters.Add("@Type", SqlDbType.NVarChar); command.Parameters["@Type"].Value = p.Type; command.Parameters.Add("@SupplierID", SqlDbType.Int); command.Parameters["@SupplierID"].Value = p.SupplierID; command.Parameters.Add("@ProductID", SqlDbType.Int); command.Parameters["@ProductID"].Value = p.ProductID; command.ExecuteNonQuery(); connection.Close(); } } catch (SqlException sqlEx) { return (sqlEx.Message); } return "Edit Order COmpleted"; } public static string DeleteProduct(Product p) { string connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString; SqlConnection connection = new SqlConnection(connectionString); String sql = "DELETE FROM [Products] WHERE [ProductID] = @ProductID"; //if there is an error with the data it will catch the exception and display an error try { if (p.ProductID > 0) { connection.Open(); SqlCommand command = new SqlCommand(sql, connection); command.Parameters.Add("@ProductID", SqlDbType.Int); command.Parameters["@ProductID"].Value = p.ProductID; command.ExecuteNonQuery(); connection.Close(); return "delete product completed"; } else return "ProductID < 1 - delete product"; } catch (SqlException sqlEx) { return (sqlEx.Message); } } public static Product SelectProduct(int pid){ Product retProduct = null; SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\werl\Documents\Visual Studio 2013\Projects\SystemsAnalysis\WebApplication2\WebApplication2\App_Data\Database.mdf;Integrated Security=True"); SqlDataReader reader; SqlCommand cmd = new SqlCommand("SELECT * FROM [Products] WHERE ProductID = " + pid, con); try { con.Open(); reader = cmd.ExecuteReader(); while (reader.Read()) { retProduct = new StandardProduct(Convert.ToInt32(reader["ProductID"]), (reader["Type"]).ToString(), Convert.ToInt32(reader["SupplierID"])); } reader.Close(); con.Close(); return retProduct; } catch (SqlException sqlEx) { Console.Write(sqlEx.Message); return null; } } public static double getProductPrice(int pID) { string connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString; SqlConnection connection = new SqlConnection(connectionString); String sql = "SELECT Price FROM [Products] WHERE ProductID = @ProductID"; double price = 0.0; SqlCommand command = new SqlCommand(sql, connection); SqlDataReader reader; try { connection.Open(); command.Parameters.Add("@ProductID", SqlDbType.Int); command.Parameters["@ProductID"].Value = pID; reader = command.ExecuteReader(); while (reader.Read()) { price = reader.GetDouble(0); } reader.Close(); return price; } catch (SqlException sqlEx) { Console.WriteLine(sqlEx.Message); return 0.0; } finally { connection.Close(); } } public static String getProductType(int pID) { string connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString; SqlConnection connection = new SqlConnection(connectionString); String sql = "SELECT Type FROM [Products] WHERE ProductID = @ProductID"; String type = ""; SqlCommand command = new SqlCommand(sql, connection); SqlDataReader reader; try { connection.Open(); command.Parameters.Add("@ProductID", SqlDbType.Int); command.Parameters["@ProductID"].Value = pID; reader = command.ExecuteReader(); while (reader.Read()) { type = reader.GetString(0); } reader.Close(); return type; } catch (SqlException sqlEx) { Console.WriteLine(sqlEx.Message); return ""; } finally { connection.Close(); } } } }
using MChooser.Constants; using MChooser.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MChooser.ModelMaker { public class MechModelMaker { public static MechModel GenerateMechModel(MechClasses mechClass, string modelName, string variantName, string weightIncrement, Factions faction) { MechModel mechModel = null; switch (mechClass) { case MechClasses.LIGHT: mechModel = new LightMech(modelName, variantName, faction, (LightMechWeightIncrements)System.Enum.Parse(typeof(LightMechWeightIncrements), weightIncrement)); break; case MechClasses.MEDIUM: mechModel = new MediumMech(modelName, variantName, faction, (MediumMechWeightIncrements)System.Enum.Parse(typeof(MediumMechWeightIncrements), weightIncrement)); break; case MechClasses.HEAVY: mechModel = new HeavyMech(modelName, variantName, faction, (HeavyMechWeightIncrements)System.Enum.Parse(typeof(HeavyMechWeightIncrements), weightIncrement)); break; case MechClasses.ASSAULT: mechModel = new AssaultMech(modelName, variantName, faction, (AssaultMechWeightIncrements)System.Enum.Parse(typeof(AssaultMechWeightIncrements), weightIncrement)); break; } return mechModel; } } }
using Common.Models; using NHibernate; using NHibernate.Criterion; using System; using System.Collections.Generic; namespace Common.Services { public class PassService : BaseService { public PassService(Func<ISession> session) : base(session) { } public IList<Pass> Get() { return CurrentSession.CreateCriteria(typeof(Pass)).List<Pass>(); } public Pass Get(int id) { return CurrentSession.Get<Pass>(id); } public Pass Add(Pass pass) { using (var tran = CurrentSession.BeginTransaction()) { try { if (pass.PassID > 0) { throw new Exception(String.Format("A Pass with Bid {0} already exists. To update please use PUT.",pass.PassID)); } CurrentSession.Save(pass); tran.Commit(); return pass; } catch (Exception ex) { tran.Rollback(); throw ex; } } } public Pass Update(Pass pass) { using (var tran = CurrentSession.BeginTransaction()) { try { if (pass.PassID == 0) { throw new Exception("For creating a Pass please use POST"); } CurrentSession.Update(pass); tran.Commit(); return pass; } catch (Exception ex) { tran.Rollback(); throw ex; } } } public bool Delete(int id) { using (var tran = CurrentSession.BeginTransaction()) { try { var pass = Get(id); if (pass != null) { CurrentSession.Delete(pass); tran.Commit(); } return true; } catch (Exception ex) { tran.Rollback(); throw ex; } } } } }
using Newtonsoft.Json; using StackExchange.Redis; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RedisPSR { class DataGenerator { private IDatabase conn; public DataGenerator(IDatabase conn) { this.conn = conn; } public void Genetate() { var helper = new Helper(conn); var policemen = new List<Policeman>{ new Policeman("Jan", "Kowal", 1990), new Policeman("Anna", "Maj", 1890), new Policeman("Artur", "B?k", 1960), new Policeman("Bart?omiej", "Stonoga", 1988) }; foreach (var policeman in policemen) { var json = JsonConvert.SerializeObject(policeman); var key = "policjant:0"; conn.StringSet(helper.KeyAdjustment(key), json); } var departments = new List<Department> { new Department("Kielce", "miejska"), new Department("Warszawa", "wojewodzka"), new Department("Radom", "powiatowa"), new Department("Kielce", "powiatowa")}; foreach (var department in departments) { var json = JsonConvert.SerializeObject(department); var key = "komenda:0"; conn.StringSet(helper.KeyAdjustment(key), json); } var ranks = new List<Rank> { new Rank("Funkcjonariusz", 2000), new Rank("Podkomisarz", 2500), new Rank("Nadkomisarz", 3500) }; foreach (var rank in ranks) { var json = JsonConvert.SerializeObject(rank); var key = "ranga:0"; conn.StringSet(helper.KeyAdjustment(key), json); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace HiaChat_Client { /// <summary> /// Signup.xaml 的交互逻辑 /// </summary> public partial class Signup : Window { Login login; public Signup(Login login) { InitializeComponent(); this.login = login; this.login.Hide(); } private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { base.OnMouseLeftButtonDown(e); // 获取鼠标相对标题栏位置 Point position = e.GetPosition(gridTitle); // 如果鼠标位置在标题栏内,允许拖动 if (e.LeftButton == MouseButtonState.Pressed) { if (position.X >= 0 && position.X < gridTitle.ActualWidth && position.Y >= 0 && position.Y < gridTitle.ActualHeight) { this.DragMove(); } } } private void Btsignup_Click(object sender, RoutedEventArgs e) { Socketkit s = new Socketkit(); string number = s.TcpSignup(tb_number.Text,tb_password.Text); MessageBox.Show(string.Format("注册成功!您的号码为:{0}",number), "注册成功!"); this.Hide(); this.login.Show(); } } }
using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Table; using Newtonsoft.Json; using System; namespace Sfa.Poc.ResultsAndCertification.Configuration.Configuration { public class ResultsAndCertificationConfigurationLoader { public static ResultsAndCertificationConfiguration Load(string environment, string storageConnectionString, string version, string serviceName) { try { var conn = CloudStorageAccount.Parse(storageConnectionString); var tableClient = conn.CreateCloudTableClient(); var table = tableClient.GetTableReference("Configuration"); var operation = TableOperation.Retrieve(environment, $"{serviceName}_{version}"); var result = table.ExecuteAsync(operation).GetAwaiter().GetResult(); var dynResult = result.Result as DynamicTableEntity; var data = dynResult?.Properties["Data"].StringValue; return JsonConvert.DeserializeObject<ResultsAndCertificationConfiguration>(data); } catch (Exception ex) { throw new InvalidOperationException("Configuration could not be loaded. Please check your configuration files or see the inner exception for details", ex); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Readable : Interactable { public Log log; public override void ProcessDefaultInteraction() { base.ProcessDefaultInteraction(); Read(); } public override void ProcessAltInteraction() { base.ProcessAltInteraction(); Examine(); } void Read() { print("Reading " + log.name); RegisterLogEntry(); } void RegisterLogEntry() { print("Registered " + log.name + " in jounal"); } void Examine() { print("Looking at " + log.description); } }
using System; using ODL.DomainModel.Common; namespace ODL.DomainModel.Adress { // TODO: Eventuellt refaktorera Adressvariant som Value Object, tillåt nya varianter dynamiskt via Admin-gui etc. public enum Adressvariant { [Visningstext("Folkbokföringsadress")] Folkbokforingsadress = 1, [Visningstext("Adress arbete")] AdressArbete = 2, [Visningstext("Leveransadress")] Leveransadress = 3, [Visningstext("Faktureringsadress")] Faktureringsadress = 4, [Visningstext("Epost-adress arbete")] EpostAdressArbete = 5, [Visningstext("Epost-adress privat")] EpostAdressPrivat = 6, [Visningstext("Mobil arbete")] MobilArbete = 7, [Visningstext("Mobil privat")] MobilPrivat = 8, [Visningstext("Telefon arbete")] TelefonArbete = 9, [Visningstext("Telefon privat")] TelefonPrivat = 10, [Visningstext("Facebook")] Facebook = 11, [Visningstext("Linkedin")] Linkedin = 12 } public static class AdressvariantExtensions { public static Adresstyp Adresstyp(this Adressvariant adressvariant) { if (adressvariant == Adressvariant.Folkbokforingsadress) return DomainModel.Adress.Adresstyp.Gatuadress; if (adressvariant == Adressvariant.AdressArbete) return DomainModel.Adress.Adresstyp.Gatuadress; if (adressvariant == Adressvariant.Leveransadress) return DomainModel.Adress.Adresstyp.Gatuadress; if (adressvariant == Adressvariant.Faktureringsadress) return DomainModel.Adress.Adresstyp.Gatuadress; if (adressvariant == Adressvariant.EpostAdressArbete) return DomainModel.Adress.Adresstyp.EpostAdress; if (adressvariant == Adressvariant.EpostAdressPrivat) return DomainModel.Adress.Adresstyp.EpostAdress; if (adressvariant == Adressvariant.MobilArbete) return DomainModel.Adress.Adresstyp.Telefon; if (adressvariant == Adressvariant.MobilPrivat) return DomainModel.Adress.Adresstyp.Telefon; if (adressvariant == Adressvariant.TelefonArbete) return DomainModel.Adress.Adresstyp.Telefon; if (adressvariant == Adressvariant.TelefonPrivat) return DomainModel.Adress.Adresstyp.Telefon; if (adressvariant == Adressvariant.Facebook) return DomainModel.Adress.Adresstyp.Url; if (adressvariant == Adressvariant.Linkedin) return DomainModel.Adress.Adresstyp.Url; throw new ArgumentException($"Adressvarianten '{adressvariant.Visningstext()}' saknar Adresstyp!"); } } }
using Lrs.PersonalLearningRecordService.Api.Client; using Microsoft.Extensions.Logging; using Sfa.Poc.ResultsAndCertification.CsvHelper.Api.Client.Interfaces; using Sfa.Poc.ResultsAndCertification.CsvHelper.Models.Configuration; using System; using System.ServiceModel; using System.Threading.Tasks; namespace Sfa.Poc.ResultsAndCertification.CsvHelper.Api.Client.Clients { public class PersonalLearningRecordServiceClient : IPersonalLearningRecordApiClient { private readonly ILogger<LearnerServiceR9Client> _logger; private readonly ILearnerServiceR9Client _learnerServiceR9Client; private readonly ResultsAndCertificationConfiguration _configuration; public PersonalLearningRecordServiceClient(ILogger<LearnerServiceR9Client> logger, ILearnerServiceR9Client learnerServiceR9Client, ResultsAndCertificationConfiguration configuration) { _logger = logger; _learnerServiceR9Client = learnerServiceR9Client; _configuration = configuration; } public async Task<bool> GetLearnerEventsAsync(string uln, string firstName, string lastName, string dateOfBirth) { try { var invokingOrganisation = new InvokingOrganisationR10 { OrganisationRef = _configuration.LearningRecordServiceSettings.Ukprn, Ukprn = _configuration.LearningRecordServiceSettings.Ukprn, Username = _configuration.LearningRecordServiceSettings.Username, Password = _configuration.LearningRecordServiceSettings.Password }; var response = await _learnerServiceR9Client.GetLearnerLearningEventsAsync(invokingOrganisation, "ORG", 1, "ENG", uln, firstName, lastName, dateOfBirth, null, "FULL"); _learnerServiceR9Client.Close(); return true; } catch (Exception ex) { if (_learnerServiceR9Client.State == CommunicationState.Faulted) _learnerServiceR9Client.Abort(); _logger.LogError($"Error while executing GetLearnerEventsAsync. Exception = {ex}"); _learnerServiceR9Client.Close(); return false; } } } } namespace Lrs.PersonalLearningRecordService.Api.Client { public interface ILearnerServiceR9Client : ICommunicationObject, ILearnerServiceR9 { } public partial class LearnerServiceR9Client : ILearnerServiceR9Client { static partial void ConfigureEndpoint(System.ServiceModel.Description.ServiceEndpoint serviceEndpoint, System.ServiceModel.Description.ClientCredentials clientCredentials) { (serviceEndpoint.Binding as BasicHttpBinding).Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate; } } }
using Microsoft.Data.SqlClient; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; using ServicesSite.Domain; using ServicesSite.Domain.Entities; using ServicesSite.Infraestructure; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ServiceSite.Persistence.Queries { public interface IClientesQueries { Task<List<ClienteE>> GetListCLients(); } public class ClientesQueries: IDisposable , IClientesQueries { private PruebaDbContext _context = null; private readonly ConnectionString _settings; public ClientesQueries(IOptions<ConnectionString> settings) { _settings = settings.Value; _context = new PruebaDbContext(_settings.PruebaConnection); } #region Implementación Dispose bool disposed = false; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } // Protected implementation of Dispose pattern. protected virtual void Dispose(bool disposing) { if (disposed) return; if (disposing) { _context?.Dispose(); } // Free any unmanaged objects here. // disposed = true; } #endregion public async Task<List<ClienteE>> GetListCLients() { List<ClienteE> itemList = null; try { itemList = await _context.ClienteEs.FromSqlRaw("dbo.GetListCLients").ToListAsync(); } catch (Exception ex) { throw; } return itemList; } } }
namespace Sales.ViewModels { using System; using System.Linq; using System.Windows.Input; using Common.Models; using GalaSoft.MvvmLight.Command; using Helpers; using Services; using Views; using Xamarin.Forms; public class ProductItemViewModel : Product { #region Attibutes private ApiService apiService; #endregion #region Constructors public ProductItemViewModel() { this.apiService = new ApiService(); } #endregion #region Commmands public ICommand EditProductCommand { get { return new RelayCommand(EditProduct); } } private async void EditProduct() { MainViewModel.GetInstance().EditProduct = new EditProductViewModel(this); await App.Navigator.PushAsync(new EditProductPage()); } public ICommand DeleteProductCommand { get { return new RelayCommand(DeleteProduct); } } private async void DeleteProduct() { var answer = await Application.Current.MainPage.DisplayAlert( Languages.Confirm, Languages.DeleteConfirmation, Languages.Yes, Languages.No); if (!answer) { return; } var connection = await this.apiService.CheckConnection(); if (!connection.IsSuccess) { await Application.Current.MainPage.DisplayAlert(Languages.Error, connection.Message, Languages.Accept); return; } var url = Application.Current.Resources["UrlAPI"].ToString(); var prefix = Application.Current.Resources["UrlPrefix"].ToString(); var controller = Application.Current.Resources["UrlProductsController"].ToString(); var response = await this.apiService.Delete(url, prefix, controller, this.ProductId, Settings.TokenType, Settings.AccessToken); if (!response.IsSuccess) { await Application.Current.MainPage.DisplayAlert(Languages.Error, response.Message, Languages.Accept); return; } var productsViewModel = ProductsViewModel.GetInstance(); var deletedProduct = productsViewModel.MyProducts.Where(p => p.ProductId == this.ProductId).FirstOrDefault(); if (deletedProduct != null) { productsViewModel.MyProducts.Remove(deletedProduct); } productsViewModel.RefreshList(); } #endregion } }
using System; using SnowSoftware.Driver; using SnowSoftware.PageObjectModels; using Xunit; namespace SnowSoftware { public class SnowTest { private SitePage site; private Menu menu; private SnowGlobe snowGlobe; private ReleaseNotes releaseNotes; public void Setup() { WebDriver.CreateDriver(); site = new SitePage(); menu = new Menu(); snowGlobe = new SnowGlobe(); releaseNotes = new ReleaseNotes(); } [Fact(DisplayName = "Check Exist 'Snow License Manager 9.7.1 Release Note'r")] [System.Obsolete] public void CheckReleaseNotes() { Setup(); site.NavigateToTheSite("https://www.snowsoftware.com"); menu.ClickOnSuccessMenu() .ClickSnowGlobeCommunity(); snowGlobe.InputSearchField("Snow License Manager") .ClickReleaseNotes(); String expectedTitle = "Release Notes: Snow License Manager 9.7.1"; String expectedNumber = "000013119"; Assert.Equal(releaseNotes.getTitleText(), expectedTitle); Assert.Equal(releaseNotes.getArticleNumber(), expectedNumber); After(); } public void After() { WebDriver.QuitDriver(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MoveFloorCollider : MonoBehaviour { void OnCollisionStay2D(Collision2D col) { if (col.gameObject.CompareTag("Player")) col.gameObject.transform.SetParent(transform.parent); } void OnCollisionExit2D(Collision2D col) { if (col.gameObject.CompareTag("Player")) col.gameObject.transform.parent = null; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class tasks : MonoBehaviour { public GameManager gameManager; [SerializeField] private GameObject[] taskPanels; [SerializeField] private GameObject[] taskBTNS; //coinGoals [Header("Objectives 2")] private int coinGoal = 400; //player must make this much money to complete Objective 2 [Header("Objectives 1")] private int classRoom = 1; //player must have this many classes built to complete Objective 1 public void classRoomGoals() { if (gameManager.ClassRCount >= classRoom) { if (taskPanels[1] != null) { taskPanels[1].SetActive(false); } Destroy(taskBTNS[1].gameObject); taskPanels[0].SetActive(true); taskBTNS[0].SetActive(true); } else { taskPanels[1].SetActive(true); } } public void coinGoals() { if (gameManager.Money >= coinGoal) { if (taskPanels[0] != null) { taskPanels[0].SetActive(false); } Destroy(taskBTNS[0].gameObject); SceneManager.LoadScene(3); } else { taskPanels[0].SetActive(true); } } // Start is called before the first frame update void Start() { taskPanels[0].SetActive(false); taskBTNS[0].SetActive(false); gameManager = GameManager.instance; } // Update is called once per frame void Update() { } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using UFO.Server; using UFO.Server.Data; namespace UFO.WebService.Controllers { public class PerformanceController : ApiController { private IPerformanceService ps; public PerformanceController() { ps = ServiceFactory.CreatePerformanceService(DatabaseConnection.GetDatabase()); } [HttpGet] public Performance GetPerformanceById(uint id) { return ps.GetPerformanceById(id); } [HttpGet] public Performance[] GetAllPerformances() { return ps.GetAllPerformances().ToArray(); } [HttpGet] public Performance[] GetPerformancesForDay(string date) { string[] parts = date.Split('-'); return ps.GetPerformancesForDay(new DateTime(int.Parse(parts[0]), int.Parse(parts[1]), int.Parse(parts[2]))).ToArray(); } [HttpPost] public void DeletePerformance(Performance performance) { ps.DeletePerformance(performance); } [HttpPost] public void UpdatePerformance(Performance performance) { ps.UpdatePerformance(performance); } [HttpPost] public Performance CreatePerformance(Performance param) { return ps.CreatePerformance(param.Date, new Artist { Id = param.ArtistId }, new Venue { Id = param.VenueId }); } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using JqwidgetsMVCDemo.Models; namespace JqwidgetsMVCDemo.Controllers { public class EmployeeController : Controller { //http://www.jqwidgets.com/jquery-widgets-demo/demos/aspnetmvc/index.htm?(arctic) private EmployeeDBEntities db = new EmployeeDBEntities(); // GET: /Employee/ public ActionResult Index() { return View(db.Employees.ToList()); } // GET: /Employee/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Employee employee = db.Employees.Find(id); if (employee == null) { return HttpNotFound(); } return View(employee); } // GET: /Employee/Create public ActionResult Create() { return View(); } // POST: /Employee/Create // 为了防止“过多发布”攻击,请启用要绑定到的特定属性,有关 // 详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include="EmployeeID,ManagerID,FirstName,LastName,Title,Country,City,Address,HireDate,BirthDate")] Employee employee) { if (ModelState.IsValid) { db.Employees.Add(employee); db.SaveChanges(); return RedirectToAction("Index"); } return View(employee); } // GET: /Employee/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Employee employee = db.Employees.Find(id); if (employee == null) { return HttpNotFound(); } return View(employee); } // POST: /Employee/Edit/5 // 为了防止“过多发布”攻击,请启用要绑定到的特定属性,有关 // 详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include="EmployeeID,ManagerID,FirstName,LastName,Title,Country,City,Address,HireDate,BirthDate")] Employee employee) { if (ModelState.IsValid) { db.Entry(employee).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(employee); } // GET: /Employee/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Employee employee = db.Employees.Find(id); if (employee == null) { return HttpNotFound(); } return View(employee); } // POST: /Employee/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Employee employee = db.Employees.Find(id); db.Employees.Remove(employee); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } public JsonResult GetEmployees() { var dbResult = db.Employees.ToList(); var employees = (from employee in dbResult select new { employee.FirstName, employee.LastName, employee.EmployeeID, employee.BirthDate, employee.HireDate, employee.ManagerID, employee.Title, employee.City, employee.Country, employee.Address }); return Json(employees, JsonRequestBehavior.AllowGet); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class CharacterIK : MonoBehaviour { public Character character { get; protected set; } protected Animator animator; public bool isActiveRightHand = false; public Transform rightHandTarget = null; public float rightHandTargetWeight = 0.0f; public float rightHandCurrentWeight = 0.0f; public float rightHandWeightDamping = 7.5f; [Space] public bool isActiveLeftHand = false; public Transform leftHandTarget = null; public float leftHandTargetWeight = 0.0f; public float leftHandCurrentWeight = 0.0f; public float leftHandWeightDamping = 7.5f; [Space] public Vector3 leftHandTargetPosition = new Vector3 (); public Quaternion leftHandTargetRotation = new Quaternion (); [Space] public Transform lookTarget = null; public Transform rightHandRootPivot; public Transform rightHandPivot; [Space] public bool debugRightIK = false; private void Awake () { character = GetComponent<Character> (); character.cWeapon.onWeaponEquiped += OnWeaponEquipped; character.cWeapon.onWeaponUnequiped += OnWeaponUnequipped; character.cWeapon.onWeaponHolstered += OnWeaponHolstered; character.cWeapon.onWeaponUnholstered += OnWeaponUnholstered; character.OnAimChanged += OnAimChanged; } void Start () { animator = GetComponent<Animator> (); } void OnAnimatorIK () { SetLeftHandPosition (); RightHandIK (); LeftHandIK (); SetLookAtPosition (); } private float recoilCounter = 0.0f; public RecoilData recoilData = null; public AudioSource src; private void Update () { MatchWeaponIK (); HandleDamping (); WeaponAimPosition (); MonitorRecoil (); } private void MonitorRecoil () { if (recoilCounter <= 1.0f) { recoilCounter += Time.deltaTime * recoilData.time; if (recoilCounter > 1.0f) recoilCounter = 1.0f; } float lerp = 10.0f; float isEmptyClipMultiplier = (character.cWeapon.currentRounds > 0) ? 1.0f : 0.5f; rightHandRootPivot.localRotation = Quaternion.Slerp ( rightHandRootPivot.localRotation, Quaternion.Euler ( recoilData.rotationalDirection * recoilData.rotationalCurve.Evaluate ( recoilCounter ) * recoilData.visualMultiplier * isEmptyClipMultiplier ), Time.deltaTime * lerp ); rightHandRootPivot.localPosition = Vector3.Lerp ( rightHandRootPivot.localPosition, recoilData.positionalDirection * recoilData.positionalCurve.Evaluate ( recoilCounter ) * recoilData.visualMultiplier * isEmptyClipMultiplier, Time.deltaTime * lerp ); FindObjectOfType<PlayerCameraController> ().SetXRecoil ( recoilData.cameraXAmount * recoilData.cameraXCurve.Evaluate ( recoilCounter ) * UnityEngine.Random.Range ( recoilData.rangeXModifier.x, recoilData.rangeXModifier.y ) * recoilData.cameraMultiplier * isEmptyClipMultiplier ); FindObjectOfType<PlayerCameraController> ().SetYRecoil ( recoilData.cameraYAmount * recoilData.cameraYCurve.Evaluate ( recoilCounter ) * UnityEngine.Random.Range ( recoilData.rangeYModifier.x, recoilData.rangeYModifier.y ) * recoilData.cameraMultiplier * isEmptyClipMultiplier ); } private void HandleDamping () { if (!isActiveLeftHand) { leftHandTargetWeight = 0.0f; } if (!isActiveRightHand) { rightHandTargetWeight = 0.0f; } leftHandCurrentWeight = Mathf.Lerp ( leftHandCurrentWeight, leftHandTargetWeight, leftHandWeightDamping * Time.deltaTime ); rightHandCurrentWeight = Mathf.Lerp ( rightHandCurrentWeight, rightHandTargetWeight, rightHandWeightDamping * Time.deltaTime ); } private void WeaponAimPosition () { Vector3 dir = (character.cWeapon.AimPosition - rightHandPivot.transform.position).normalized; Quaternion lookRot = Quaternion.LookRotation ( dir, Vector3.Cross ( dir, -Vector3.up ).normalized ); rightHandPivot.rotation = lookRot; } private void OnWeaponHolstered (WeaponData obj) { isActiveLeftHand = false; isActiveRightHand = false; } private void OnWeaponUnholstered (WeaponData obj) { if (character.cWeapon.currentWeaponData.weaponType == WeaponData.WeaponType.Rifle) { isActiveLeftHand = true; leftHandTargetWeight = 1.0f; } } private void OnWeaponEquipped (WeaponData data) { if (character.cWeapon.currentWeaponData.weaponType == WeaponData.WeaponType.Rifle && !character.cWeapon.isHolstered) { isActiveLeftHand = true; leftHandTargetWeight = 1.0f; } } private void OnWeaponUnequipped (WeaponData data) { isActiveLeftHand = false; isActiveRightHand = false; } private void OnAimChanged() { isActiveRightHand = false; if (!character.IsAiming) { if (character.cWeapon.isEquipped && character.cWeapon.currentWeaponData.weaponType == WeaponData.WeaponType.Pistol) { isActiveLeftHand = false; } } } private void SetLeftHandPosition () { leftHandTarget.position = leftHandTargetPosition; leftHandTarget.rotation = leftHandTargetRotation; } private void RightHandIK () { if (animator) { if (rightHandTarget != null) { animator.SetIKPositionWeight ( AvatarIKGoal.RightHand, rightHandCurrentWeight ); animator.SetIKRotationWeight ( AvatarIKGoal.RightHand, rightHandCurrentWeight ); animator.SetIKPosition ( AvatarIKGoal.RightHand, rightHandTarget.position ); animator.SetIKRotation ( AvatarIKGoal.RightHand, rightHandTarget.rotation ); } } } private void LeftHandIK () { if (animator) { if (leftHandTarget != null) { animator.SetIKPositionWeight ( AvatarIKGoal.LeftHand, leftHandCurrentWeight ); animator.SetIKRotationWeight ( AvatarIKGoal.LeftHand, leftHandCurrentWeight ); animator.SetIKPosition ( AvatarIKGoal.LeftHand, leftHandTarget.position ); animator.SetIKRotation ( AvatarIKGoal.LeftHand, leftHandTarget.rotation ); } } } private void SetLookAtPosition () { animator.SetLookAtPosition ( character.cCameraController.cameraTransform.position + character.cCameraController.cameraTransform.forward * 100.0f ); animator.SetLookAtWeight ( 1.0f, character.IsAiming ? 1.0f : 0.0f, 1.0f, 1.0f, 1.0f ); } private void MatchWeaponIK () { if (character.cWeapon.isEquipped && !character.cWeapon.isHolstered) { if (character.cWeapon.currentWeaponData.weaponType == WeaponData.WeaponType.Rifle) { leftHandTargetPosition = character.cWeapon.WeaponHandTarget.position; leftHandTargetRotation = character.cWeapon.WeaponHandTarget.rotation; } if (character.IsAiming) { if (!debugRightIK) { rightHandTarget.localPosition = character.cWeapon.GetCurrentIKData.position; rightHandTarget.localEulerAngles = character.cWeapon.GetCurrentIKData.eulerAngles; } else { character.cWeapon.GetCurrentIKData.position = rightHandTarget.localPosition; character.cWeapon.GetCurrentIKData.eulerAngles = rightHandTarget.localEulerAngles; } if (character.cWeapon.currentWeaponData.weaponType == WeaponData.WeaponType.Pistol) { leftHandTargetPosition = character.cWeapon.WeaponHandTarget.position; leftHandTargetRotation = character.cWeapon.WeaponHandTarget.rotation; } isActiveLeftHand = true; isActiveRightHand = true; leftHandTargetWeight = 1.0f; rightHandTargetWeight = 1.0f; return; } } } public void SetRightHand (Transform target) { rightHandTarget = target; } public void OpeningCarDoor(bool state, Transform target) { if (state) { isActiveLeftHand = true; leftHandTargetPosition = target.position; leftHandTargetRotation = target.rotation; leftHandTargetWeight = 1.0f; } else { isActiveLeftHand = false; leftHandTargetWeight = 0.0f; } } public void AddRecoil (RecoilData data) { recoilData = data; recoilCounter = 0.0f; } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; namespace WebService { /// <summary> /// Descripción breve de WebServiceCalculator /// </summary> [WebService(Namespace = "http://tempuri.org/")] // En caso de tener varios metodos con el mismo nombre se utiliza MessageName, ademas se pone ConformsTo = WsiProfiles.None //[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [WebServiceBinding(ConformsTo = WsiProfiles.None)] [System.ComponentModel.ToolboxItem(false)] // Para permitir que se llame a este servicio web desde un script, usando ASP.NET AJAX, quite la marca de comentario de la línea siguiente. // [System.Web.Script.Services.ScriptService] public class WebServiceCalculator : System.Web.Services.WebService { [WebMethod] public string HelloWorld() { return "Hola a todos"; } [WebMethod (MessageName ="HellowWorld1")] public string HelloWorld(String a) { return a; } /**Description: Pequena descripcion del WebService * Cache duration: Impide la insercion de valores duplicados en un lapso de tiempo */ [WebMethod(EnableSession = true, Description = "This sum 2 Numbers", CacheDuration = 5)] public Int32 Add(int firtNumber, int lastNumber) { List<String> calculations; if (Session["CALCULATIONS"] == null) { calculations = new List<String>(); } else { calculations = (List<String>)Session["CALCULATIONS"]; } String strRecentCalculation = firtNumber.ToString() + " + " + lastNumber.ToString() + " = " + (firtNumber + lastNumber).ToString(); calculations.Add(strRecentCalculation); Session["CALCULATIONS"] = calculations; return firtNumber + lastNumber; } [WebMethod(EnableSession = true, Description ="This Metod Sum Det A session array of metod Add")] public List<String> GetCalculations() { if(Session["CALCULATIONS"] == null) { List<String> calculations = new List<string>(); calculations.Add("You dont have eny calculation"); return calculations; } else { return (List<String>)Session["CALCULATIONS"]; } } } }
using Zesty.Core.Common; using Zesty.Core.Entities.Settings; namespace Zesty.Core { internal class StorageManager { internal static IStorage Storage { get; private set; } static StorageManager() { Storage = InstanceHelper.Create<IStorage>(Settings.Current.StorageImplementationType); } } }
using System.Windows; using System.Windows.Controls; using System.Windows.Input; using UI.Pages; namespace UI { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); CategoriesListTabHeaderLabel.MouseLeftButtonDown += CategoriesListTabHeaderLabel_MouseLeftButtonDown; RecordsListTabHeaderLabel.MouseLeftButtonDown += RecordsListTabHeaderLabel_MouseLeftButtonDown; } private void BudgetDataTabHeaderLabel_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { var budgetDataPage = BudgetDataFrame.Content as BudgetDataPage; budgetDataPage.UpdateViewModelServices(); RemoveEventHandlers(); CategoriesListTabHeaderLabel.MouseLeftButtonDown += CategoriesListTabHeaderLabel_MouseLeftButtonDown; RecordsListTabHeaderLabel.MouseLeftButtonDown += RecordsListTabHeaderLabel_MouseLeftButtonDown; } private void CategoriesListTabHeaderLabel_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { RemoveEventHandlers(); RecordsListTabHeaderLabel.MouseLeftButtonDown += RecordsListTabHeaderLabel_MouseLeftButtonDown; BudgetDataTabHeaderLabel.MouseLeftButtonDown += BudgetDataTabHeaderLabel_MouseLeftButtonDown; } private void RecordsListTabHeaderLabel_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { var recordsListPage = RecordsListFrame.Content as RecordsListPage; recordsListPage.UpdateViewModelServices(); RemoveEventHandlers(); CategoriesListTabHeaderLabel.MouseLeftButtonDown += CategoriesListTabHeaderLabel_MouseLeftButtonDown; BudgetDataTabHeaderLabel.MouseLeftButtonDown += BudgetDataTabHeaderLabel_MouseLeftButtonDown; } private void RemoveEventHandlers() { CategoriesListTabHeaderLabel.MouseLeftButtonDown -= CategoriesListTabHeaderLabel_MouseLeftButtonDown; RecordsListTabHeaderLabel.MouseLeftButtonDown -= RecordsListTabHeaderLabel_MouseLeftButtonDown; BudgetDataTabHeaderLabel.MouseLeftButtonDown -= BudgetDataTabHeaderLabel_MouseLeftButtonDown; } } }
using System; using System.Collections.Generic; using System.Text; namespace Monogame.src.utils { class Position { } }