content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System.Collections.Generic; using System.Threading.Tasks; using Models; namespace Data { public interface IRepository { public Item GetItem(int id); public List<Item> GetItems(Item.ItemType itemType); public void AddCustomer(Customer newCustomer); public Task<bool> SaveChanges(); } }
23.928571
59
0.695522
[ "MIT" ]
Vlashious/blazing_pizza
Data/Repository/IRepository.cs
335
C#
using System; using System.Runtime.InteropServices; using System.Threading; using Microsoft.VisualStudio.Shell; using VSColorOutput.State; using Task = System.Threading.Tasks.Task; namespace VSColorOutput { [PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)] [Guid(VSColorOutputPackage.PackageGuidString)] [ProvideOptionPage(typeof(VsColorOutputOptionsDialog), VsColorOutputOptionsDialog.Category, VsColorOutputOptionsDialog.SubCategory, 1000, 1001, true)] [ProvideProfile(typeof(VsColorOutputOptionsDialog), VsColorOutputOptionsDialog.Category, VsColorOutputOptionsDialog.SubCategory, 1000, 1001, true)] [InstalledProductRegistration("VSColorOutput", "Color output for build and debug windows - https://mike-ward.net/vscoloroutput", "2.7")] public sealed class VSColorOutputPackage : AsyncPackage { public const string PackageGuidString = "CD56B219-38CB-482A-9B2D-7582DF4AAF1E"; protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress) { await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); } } }
49.958333
154
0.790659
[ "MIT" ]
kyle-john/VSColorOutput
VSColorOutput/VsColorOutputPackage.cs
1,201
C#
using InventorySystem.Runtime.Scripts.Core.Models.Interfaces; using UnityEngine; using UnityEngine.UI; namespace InventorySystem.Runtime.Scripts.Inventory.Item { public class ItemView { private readonly Transform _itemTransform; public ItemView(Transform itemTransform) { _itemTransform = itemTransform; } public void PrepareItem(IItem item) { var image = _itemTransform.gameObject.GetComponent<Image>(); image.color = item.Color; } } }
21.318182
63
0.761194
[ "MIT" ]
artem-karaman/Unity-Inventory-System
Unity-Inventory-System/Assets/InventorySystem/Runtime/Scripts/Inventory/Item/ItemView.cs
471
C#
using System.IO; using System.Web; using Umbraco.Core.CodeAnnotations; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Web.Mvc; using umbraco.BasePages; using Umbraco.Core; namespace umbraco { /// <summary> /// The UI 'tasks' for the create dialog and delete processes /// </summary> [UmbracoWillObsolete("http://issues.umbraco.org/issue/U4-1373", "This will one day be removed when we overhaul the create process")] public class PartialViewTasks : interfaces.ITaskReturnUrl { private string _alias; private int _parentId; private int _typeId; private int _userId; protected virtual string EditViewFile { get { return "Settings/Views/EditView.aspx"; } } protected string BasePath { get { return SystemDirectories.MvcViews + "/" + ParentFolderName.EnsureEndsWith('/'); } } protected virtual string ParentFolderName { get { return "Partials"; } } public int UserId { set { _userId = value; } } public int TypeID { set { _typeId = value; } get { return _typeId; } } public string Alias { set { _alias = value; } get { return _alias; } } public int ParentID { set { _parentId = value; } get { return _parentId; } } public bool Save() { var fileName = _alias + ".cshtml"; var fullFilePath = IOHelper.MapPath(BasePath + fileName); //return the link to edit the file if it already exists if (File.Exists(fullFilePath)) { _returnUrl = string.Format(EditViewFile + "?file={0}", HttpUtility.UrlEncode(ParentFolderName.EnsureEndsWith('/') + fileName)); return true; } //create the file using (var sw = File.CreateText(fullFilePath)) { WriteTemplateHeader(sw); } // Create macro? if (ParentID == 1) { var name = fileName .Substring(0, (fileName.LastIndexOf('.') + 1)).Trim('.') .SplitPascalCasing().ToFirstUpperInvariant(); var m = cms.businesslogic.macro.Macro.MakeNew(name); m.ScriptingFile = BasePath + fileName; } _returnUrl = string.Format(EditViewFile + "?file={0}", HttpUtility.UrlEncode(ParentFolderName.EnsureEndsWith('/') + fileName)); return true; } protected virtual void WriteTemplateHeader(StreamWriter sw) { //write out the template header sw.Write("@inherits "); sw.Write(typeof(UmbracoTemplatePage).FullName.TrimEnd("`1")); } public bool Delete() { var path = IOHelper.MapPath(BasePath + _alias.TrimStart('/')); if (File.Exists(path)) File.Delete(path); else if (Directory.Exists(path)) Directory.Delete(path, true); LogHelper.Info<PartialViewTasks>(string.Format("{0} Deleted by user {1}", _alias, UmbracoEnsuredPage.CurrentUser.Id)); return true; } #region ITaskReturnUrl Members private string _returnUrl = ""; public string ReturnUrl { get { return _returnUrl; } } #endregion } }
24.666667
134
0.638102
[ "MIT" ]
DigiBorg0/Umbarco-CMS
src/Umbraco.Web/umbraco.presentation/umbraco/create/PartialViewTasks.cs
3,036
C#
// $Id$ // // Copyright 2008-2009 The AnkhSVN Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Windows.Forms; using Ankh.Scc; using Ankh.UI.WorkingCopyExplorer.Nodes; namespace Ankh.UI.WorkingCopyExplorer { sealed class FileSystemTreeNode : TreeNode { readonly WCTreeNode _wcNode; readonly SvnItem _item; public FileSystemTreeNode(WCTreeNode wcNode, SvnItem item) { if (wcNode == null) throw new ArgumentNullException("wcNode"); _wcNode = wcNode; Text = wcNode.Title; _item = item; wcNode.TreeNode = this; } public FileSystemTreeNode(WCTreeNode wcNode) :this(wcNode, null) { } public FileSystemTreeNode(string text) : base(text) { } public new FileSystemTreeView TreeView { get { return (FileSystemTreeView)base.TreeView; } } public WCTreeNode WCNode { get { return _wcNode; } } public SvnItem SvnItem { get { WCFileSystemNode dirNode = _wcNode as WCFileSystemNode; if (_item == null && dirNode != null) return dirNode.SvnItem; return _item; } } public void Refresh() { StateImageIndex = (int) AnkhGlyph.None; if(SvnItem == null) return; if (SvnItem.IsDirectory) { bool canRead; foreach (SccFileSystemNode node in SccFileSystemNode.GetDirectoryNodes(SvnItem.FullPath, out canRead)) { canRead = true; break; } if (!canRead) return; } StateImageIndex = (int)TreeView.StatusMapper.GetStatusImageForSvnItem(SvnItem); } internal void SelectSubNode(string path) { Expand(); foreach (FileSystemTreeNode tn in Nodes) { if (tn.WCNode.ContainsDescendant(path)) { tn.SelectSubNode(path); return; } } // No subnode to expand; we reached the target, lets select it TreeView.SelectedNode = this; EnsureVisible(); if (SvnItem != null && SvnItem.FullPath == path) { TreeView.Select(); TreeView.Focus(); } } } }
26.731092
118
0.533166
[ "Apache-2.0" ]
AnkhSVN/AnkhSVN
src/Ankh.UI/WorkingCopyExplorer/FileSystemTreeNode.cs
3,181
C#
using System.Collections.Generic; using System.Threading.Tasks; using OrchardCore.ContentLocalization.Models; namespace OrchardCore.ContentLocalization.Services { public interface ILocalizationEntries { Task<(bool, LocalizationEntry)> TryGetLocalizationAsync(string contentItemId); Task<IEnumerable<LocalizationEntry>> GetLocalizationsAsync(string localizationSet); Task UpdateEntriesAsync(); } }
31
91
0.78341
[ "BSD-3-Clause" ]
1051324354/OrchardCore
src/OrchardCore.Modules/OrchardCore.ContentLocalization/Services/ILocalizationEntries.cs
434
C#
using PortClosedEmailer.Core.EmailSending; using System.Threading.Tasks; using Tests.Configuration; using Xunit; namespace Tests.EmailSending { public class SmtpClientSenderFacts { [InlineData("cred1.txt")] [InlineData("cred2.txt")] [Theory(DisplayName = "Sends email")] public Task Sendsemail(string credsFilename) { var cfg = new TestSettings(credsFilename); var sut = new SmtpClientSender1(cfg, null); return sut.SendPortClosedAlert("samplehost:123"); } } }
26.619048
61
0.651163
[ "MIT" ]
peterson1/port-closed-emailer
Tests/EmailSending/SmtpClientSenderFacts.cs
561
C#
using System.Collections; using System.Collections.Generic; using Invader.Bullets; using UnityEngine; namespace Invader.Level { /// <summary> /// 難易度調整に使うデータのインターフェース /// </summary> public interface ILevelData { float PlayerMoveVelocity { get; } float PlayerBulletVelocity { get; } BulletModel PlayerBullet { get; } // etc... } }
17.35
37
0.717579
[ "MIT" ]
atori708/SOLIDInvader
Assets/Invader/Battle/LevelData/ILevelData.cs
389
C#
using System.Collections.Generic; namespace Lesson12 { public class Dungeon : IGame { public List<List<MapTile>> Map { get; set; } public short X { get; set; } public short Y { get; set; } public Dungeon() { var Map = new List<List<MapTile>> { new List<MapTile>() {MapTile.Wall, MapTile.Spawn, MapTile.Wall, MapTile.Wall, MapTile.Wall, MapTile.Wall, }, new List<MapTile>() {MapTile.Wall, MapTile.Empty, MapTile.Empty, MapTile.Empty, MapTile.Wall, MapTile.Wall, }, new List<MapTile>() {MapTile.Wall, MapTile.Wall, MapTile.Wall, MapTile.Empty, MapTile.Wall, MapTile.Wall, }, new List<MapTile>() {MapTile.Exit, MapTile.Empty, MapTile.Wall, MapTile.Empty, MapTile.Wall, MapTile.Wall, }, new List<MapTile>() {MapTile.Wall, MapTile.Empty, MapTile.Empty, MapTile.Empty, MapTile.Wall, MapTile.Wall, }, new List<MapTile>() {MapTile.Wall, MapTile.Wall, MapTile.Wall, MapTile.Wall, MapTile.Wall, MapTile.Wall, } }; X = 1; Y = 0; } public bool CanMoveUp() { return Map[Y][X] == MapTile.Empty; } } }
39.46875
126
0.56057
[ "MIT" ]
Axelancerr/CollegeWork
Programming/Lesson12/Dungeon.cs
1,265
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Reason.Reasons; namespace Reason.Results { /// <summary> /// Success when all results have succeeded. /// </summary> public class AllSuccessResult : AggregatedResult { public AllSuccessResult(IEnumerable<Result> aggregatedResults) : base(aggregatedResults, null) { } public AllSuccessResult(IEnumerable<Result> aggregatedResults, FailedReason reason) : base(aggregatedResults, reason) { } protected override ReasonBase? GetReasonCore() { List<Result> failedResults = NextResults.Where(r => r.IsFailed()).ToList(); if (failedResults.Count <= 0) return new FailedReasonNotFailed(); if (Reason != null) return Reason; return new FailedReasonCollection(failedResults.Select(r => r.GetReason()).Where(r => r is FailedReason).Select(r => (FailedReason)r)); } } }
30.4
148
0.639098
[ "MIT" ]
nldd419/Reason
ReasonProject/Reason/Results/AllSuccessResult.cs
1,066
C#
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Kms.V1.Snippets { using Google.Cloud.Kms.V1; using System.Threading.Tasks; public sealed partial class GeneratedKeyManagementServiceClientStandaloneSnippets { /// <summary>Snippet for GetKeyRingAsync</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task GetKeyRingRequestObjectAsync() { // Create client KeyManagementServiceClient keyManagementServiceClient = await KeyManagementServiceClient.CreateAsync(); // Initialize request argument(s) GetKeyRingRequest request = new GetKeyRingRequest { KeyRingName = KeyRingName.FromProjectLocationKeyRing("[PROJECT]", "[LOCATION]", "[KEY_RING]"), }; // Make the request KeyRing response = await keyManagementServiceClient.GetKeyRingAsync(request); } } }
39.186047
115
0.686647
[ "Apache-2.0" ]
googleapis/googleapis-gen
google/cloud/kms/v1/google-cloud-kms-v1-csharp/Google.Cloud.Kms.V1.StandaloneSnippets/KeyManagementServiceClient.GetKeyRingRequestObjectAsyncSnippet.g.cs
1,685
C#
using OpenQA.Selenium.Appium.Android; using OpenQA.Selenium.Appium.Interfaces; using OpenQA.Selenium.Appium.PageObjects.Attributes; using OpenQA.Selenium.Support.PageObjects; using System.Collections.Generic; namespace Appium.Integration.Tests.PageObjects { public class AndroidPageObjectChecksAttributeMixOnNativeApp2 { ///////////////////////////////////////////////////////////////// [FindsBy(How = How.Id, Using = "FakeHTMLid", Priority = 1)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[0]")] [FindsByAndroidUIAutomator(AndroidUIAutomator = "new UiSelector().resourceId(\"android:id/text1\")")] private IMobileElement<AndroidElement> testMobileElement; [FindsBy(How = How.Id, Using = "FakeHTMLid", Priority = 1)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[0]")] [FindsByAndroidUIAutomator(AndroidUIAutomator = "new UiSelector().resourceId(\"android:id/text1\")")] private IList<AndroidElement> testMobileElements; [FindsBy(How = How.Id, Using = "FakeHTMLid", Priority = 1)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[0]")] [FindsByAndroidUIAutomator(AndroidUIAutomator = "new UiSelector().resourceId(\"android:id/text1\")")] private IMobileElement<AndroidElement> TestMobileElement { set; get; } [FindsBy(How = How.Id, Using = "FakeHTMLid", Priority = 1)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[0]")] [FindsByAndroidUIAutomator(AndroidUIAutomator = "new UiSelector().resourceId(\"android:id/text1\")")] private IList<AndroidElement> TestMobileElements { set; get; } [FindsBy(How = How.Id, Using = "FakeHTMLid", Priority = 1)] [FindsBy(How = How.ClassName, Using = "FakeHTMLClass", Priority = 2)] [FindsBy(How = How.XPath, Using = ".//fakeTag", Priority = 3)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[0]", Priority = 1)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[1]", Priority = 2)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[2]", Priority = 3)] [FindsByAndroidUIAutomator(AndroidUIAutomator = "new UiSelector().resourceId(\"android:id/fakeId\")", Priority = 1)] [FindsByAndroidUIAutomator(ID = "FakeId", Priority = 2)] [FindsByAndroidUIAutomator(ClassName = "android.widget.TextView", Priority = 3)] private IMobileElement<AndroidElement> testMultipleElement; [FindsBy(How = How.Id, Using = "FakeHTMLid", Priority = 1)] [FindsBy(How = How.ClassName, Using = "FakeHTMLClass", Priority = 2)] [FindsBy(How = How.XPath, Using = ".//fakeTag", Priority = 3)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[0]", Priority = 1)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[1]", Priority = 2)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[2]", Priority = 3)] [FindsByAndroidUIAutomator(AndroidUIAutomator = "new UiSelector().resourceId(\"android:id/fakeId\")", Priority = 1)] [FindsByAndroidUIAutomator(ID = "FakeId", Priority = 2)] [FindsByAndroidUIAutomator(ClassName = "android.widget.TextView", Priority = 3)] private IList<AndroidElement> testMultipleElements; ///////////////////////////////////////////////////////////////// [FindsBy(How = How.Id, Using = "FakeHTMLid", Priority = 1)] [FindsBy(How = How.ClassName, Using = "FakeHTMLClass", Priority = 2)] [FindsBy(How = How.XPath, Using = ".//fakeTag", Priority = 3)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[0]", Priority = 1)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[1]", Priority = 2)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[2]", Priority = 3)] [FindsByAndroidUIAutomator(AndroidUIAutomator = "new UiSelector().resourceId(\"android:id/fakeId\")", Priority = 1)] [FindsByAndroidUIAutomator(ID = "FakeId", Priority = 2)] [FindsByAndroidUIAutomator(ClassName = "android.widget.TextView", Priority = 3)] private IMobileElement<AndroidElement> TestMultipleFindByElementProperty { set; get; } [FindsBy(How = How.Id, Using = "FakeHTMLid", Priority = 1)] [FindsBy(How = How.ClassName, Using = "FakeHTMLClass", Priority = 2)] [FindsBy(How = How.XPath, Using = ".//fakeTag", Priority = 3)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[0]", Priority = 1)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[1]", Priority = 2)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[2]", Priority = 3)] [FindsByAndroidUIAutomator(AndroidUIAutomator = "new UiSelector().resourceId(\"android:id/fakeId\")", Priority = 1)] [FindsByAndroidUIAutomator(ID = "FakeId", Priority = 2)] [FindsByAndroidUIAutomator(ClassName = "android.widget.TextView", Priority = 3)] private IList<AndroidElement> MultipleFindByElementsProperty { set; get; } [FindsBySequence] [MobileFindsBySequence(Android = true, IOS = true)] [FindsBy(How = How.Id, Using = "FakeHTMLid", Priority = 1)] [FindsBy(How = How.ClassName, Using = "FakeHTMLClass", Priority = 2)] [FindsBy(How = How.XPath, Using = ".//fakeTag", Priority = 3)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[0]", Priority = 1)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[1]", Priority = 2)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[2]", Priority = 3)] [FindsByAndroidUIAutomator(AndroidUIAutomator = "new UiSelector().resourceId(\"android:id/content\")", Priority = 1)] [FindsByAndroidUIAutomator(AndroidUIAutomator = "new UiSelector().resourceId(\"android:id/list\")", Priority = 2)] [FindsByAndroidUIAutomator(ClassName = "android.widget.TextView", Priority = 3)] private IMobileElement<AndroidElement> foundByChainedSearchElement; [FindsBySequence] [MobileFindsBySequence(Android = true, IOS = true)] [FindsBy(How = How.Id, Using = "FakeHTMLid", Priority = 1)] [FindsBy(How = How.ClassName, Using = "FakeHTMLClass", Priority = 2)] [FindsBy(How = How.XPath, Using = ".//fakeTag", Priority = 3)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[0]", Priority = 1)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[1]", Priority = 2)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[2]", Priority = 3)] [FindsByAndroidUIAutomator(AndroidUIAutomator = "new UiSelector().resourceId(\"android:id/content\")", Priority = 1)] [FindsByAndroidUIAutomator(AndroidUIAutomator = "new UiSelector().resourceId(\"android:id/list\")", Priority = 2)] [FindsByAndroidUIAutomator(ClassName = "android.widget.TextView", Priority = 3)] private IList<AndroidElement> foundByChainedSearchElements; ///////////////////////////////////////////////////////////////// [FindsBySequence] [MobileFindsBySequence(Android = true, IOS = true)] [FindsBy(How = How.Id, Using = "FakeHTMLid", Priority = 1)] [FindsBy(How = How.ClassName, Using = "FakeHTMLClass", Priority = 2)] [FindsBy(How = How.XPath, Using = ".//fakeTag", Priority = 3)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[0]", Priority = 1)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[1]", Priority = 2)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[2]", Priority = 3)] [FindsByAndroidUIAutomator(AndroidUIAutomator = "new UiSelector().resourceId(\"android:id/content\")", Priority = 1)] [FindsByAndroidUIAutomator(AndroidUIAutomator = "new UiSelector().resourceId(\"android:id/list\")", Priority = 2)] [FindsByAndroidUIAutomator(ClassName = "android.widget.TextView", Priority = 3)] private IMobileElement<AndroidElement> TestFoundByChainedSearchElementProperty { set; get; } [FindsBySequence] [MobileFindsBySequence(Android = true, IOS = true)] [FindsBy(How = How.Id, Using = "FakeHTMLid", Priority = 1)] [FindsBy(How = How.ClassName, Using = "FakeHTMLClass", Priority = 2)] [FindsBy(How = How.XPath, Using = ".//fakeTag", Priority = 3)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[0]", Priority = 1)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[1]", Priority = 2)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[2]", Priority = 3)] [FindsByAndroidUIAutomator(AndroidUIAutomator = "new UiSelector().resourceId(\"android:id/content\")", Priority = 1)] [FindsByAndroidUIAutomator(AndroidUIAutomator = "new UiSelector().resourceId(\"android:id/list\")", Priority = 2)] [FindsByAndroidUIAutomator(ClassName = "android.widget.TextView", Priority = 3)] private IList<AndroidElement> TestFoundByChainedSearchElementsProperty { set; get; } [FindsByAll] [MobileFindsByAll(Android = true, IOS = true)] [FindsBy(How = How.Id, Using = "FakeHTMLid", Priority = 1)] [FindsBy(How = How.ClassName, Using = "FakeHTMLClass", Priority = 2)] [FindsBy(How = How.XPath, Using = ".//fakeTag", Priority = 3)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[0]", Priority = 1)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[1]", Priority = 2)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[2]", Priority = 3)] [FindsByAndroidUIAutomator(ID = "android:id/text1", Priority = 1)] //[FindsByAndroidUIAutomator(ClassName = "android.widget.TextView", Priority = 2)] //Equals method of RemoteWebElement is not consistent for mobile apps //The second selector will be commented till the problem is worked out private IMobileElement<AndroidElement> matchedToAllLocatorsElement; [FindsByAll] [MobileFindsByAll(Android = true, IOS = true)] [FindsBy(How = How.Id, Using = "FakeHTMLid", Priority = 1)] [FindsBy(How = How.ClassName, Using = "FakeHTMLClass", Priority = 2)] [FindsBy(How = How.XPath, Using = ".//fakeTag", Priority = 3)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[0]", Priority = 1)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[1]", Priority = 2)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[2]", Priority = 3)] [FindsByAndroidUIAutomator(ID = "android:id/text1", Priority = 1)] //[FindsByAndroidUIAutomator(ClassName = "android.widget.TextView", Priority = 2)] //Equals method of RemoteWebElement is not consistent for mobile apps //The second selector will be commented till the problem is worked out private IList<AndroidElement> matchedToAllLocatorsElements; ///////////////////////////////////////////////////////////////// [FindsByAll] [MobileFindsByAll(Android = true, IOS = true)] [FindsBy(How = How.Id, Using = "FakeHTMLid", Priority = 1)] [FindsBy(How = How.ClassName, Using = "FakeHTMLClass", Priority = 2)] [FindsBy(How = How.XPath, Using = ".//fakeTag", Priority = 3)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[0]", Priority = 1)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[1]", Priority = 2)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[2]", Priority = 3)] [FindsByAndroidUIAutomator(ID = "android:id/text1", Priority = 1)] //[FindsByAndroidUIAutomator(ClassName = "android.widget.TextView", Priority = 2)] //Equals method of RemoteWebElement is not consistent for mobile apps //The second selector will be commented till the problem is worked out private IMobileElement<AndroidElement> TestMatchedToAllLocatorsElementProperty { set; get; } [FindsByAll] [MobileFindsByAll(Android = true, IOS = true)] [FindsBy(How = How.Id, Using = "FakeHTMLid", Priority = 1)] [FindsBy(How = How.ClassName, Using = "FakeHTMLClass", Priority = 2)] [FindsBy(How = How.XPath, Using = ".//fakeTag", Priority = 3)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[0]", Priority = 1)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[1]", Priority = 2)] [FindsByIOSUIAutomation(IosUIAutomation = ".elements()[2]", Priority = 3)] [FindsByAndroidUIAutomator(ID = "android:id/text1", Priority = 1)] //[FindsByAndroidUIAutomator(ClassName = "android.widget.TextView", Priority = 2)] //Equals method of RemoteWebElement is not consistent for mobile apps //The second selector will be commented till the problem is worked out private IList<AndroidElement> TestMatchedToAllLocatorsElementsProperty { set; get; } ////////////////////////////////////////////////////////////////////////// public string GetMobileElementText() { return testMobileElement.Text; } public int GetMobileElementSize() { return testMobileElements.Count; } public string GetMobileElementPropertyText() { return TestMobileElement.Text; } public int GetMobileElementPropertySize() { return TestMobileElements.Count; } ////////////////////////////////////////////////////////////////////////// public string GetMultipleFindByElementText() { return testMultipleElement.Text; } public int GetMultipleFindByElementSize() { return testMultipleElements.Count; } public string GetMultipleFindByElementPropertyText() { return TestMultipleFindByElementProperty.Text; } public int GetMultipleFindByElementPropertySize() { return MultipleFindByElementsProperty.Count; } ////////////////////////////////////////////////////////////////////////// public string GetFoundByChainedSearchElementText() { return foundByChainedSearchElement.Text; } public int GetFoundByChainedSearchElementSize() { return foundByChainedSearchElements.Count; } public string GetFoundByChainedSearchElementPropertyText() { return TestFoundByChainedSearchElementProperty.Text; } public int GetFoundByChainedSearchElementPropertySize() { return TestFoundByChainedSearchElementsProperty.Count; } ////////////////////////////////////////////////////////////////////////// public string GetMatchedToAllLocatorsElementText() { return matchedToAllLocatorsElement.Text; } public int GetMatchedToAllLocatorsElementSize() { return matchedToAllLocatorsElements.Count; } public string GetMatchedToAllLocatorsElementPropertyText() { return TestMatchedToAllLocatorsElementProperty.Text; } public int GetMatchedToAllLocatorsElementPropertySize() { return TestMatchedToAllLocatorsElementsProperty.Count; } } }
47.803681
125
0.628016
[ "Apache-2.0" ]
elv1s42/appium-driver-restore
integration_tests/PageObjects/AndroidPageObjectChecksAttributeMixOnNativeApp2.cs
15,586
C#
using System; using UnityEngine; using FairyGUI.Utils; namespace FairyGUI { /// <summary> /// GLoader class /// </summary> public class GLoader : GObject, IAnimationGear, IColorGear { /// <summary> /// Display an error sign if the loader fails to load the content. /// UIConfig.loaderErrorSign muse be set. /// </summary> public bool showErrorSign; string _url; AlignType _align; VertAlignType _verticalAlign; bool _autoSize; FillType _fill; bool _shrinkOnly; bool _updatingLayout; PackageItem _contentItem; Action<NTexture> _reloadDelegate; MovieClip _content; GObject _errorSign; GComponent _content2; public GLoader() { _url = string.Empty; _align = AlignType.Left; _verticalAlign = VertAlignType.Top; showErrorSign = true; _reloadDelegate = OnExternalReload; } override protected void CreateDisplayObject() { displayObject = new Container("GLoader"); displayObject.gOwner = this; _content = new MovieClip(); ((Container)displayObject).AddChild(_content); ((Container)displayObject).opaque = true; } override public void Dispose() { if (_content.texture != null) { if (_contentItem == null) { _content.texture.onSizeChanged -= _reloadDelegate; try { FreeExternal(_content.texture); } catch (Exception err) { Debug.LogWarning(err); } } } if (_errorSign != null) _errorSign.Dispose(); if (_content2 != null) _content2.Dispose(); _content.Dispose(); base.Dispose(); } /// <summary> /// /// </summary> public string url { get { return _url; } set { if (_url == value) return; ClearContent(); _url = value; LoadContent(); UpdateGear(7); } } override public string icon { get { return _url; } set { this.url = value; } } /// <summary> /// /// </summary> public AlignType align { get { return _align; } set { if (_align != value) { _align = value; UpdateLayout(); } } } /// <summary> /// /// </summary> public VertAlignType verticalAlign { get { return _verticalAlign; } set { if (_verticalAlign != value) { _verticalAlign = value; UpdateLayout(); } } } /// <summary> /// /// </summary> public FillType fill { get { return _fill; } set { if (_fill != value) { _fill = value; UpdateLayout(); } } } /// <summary> /// /// </summary> public bool shrinkOnly { get { return _shrinkOnly; } set { if (_shrinkOnly != value) { _shrinkOnly = value; UpdateLayout(); } } } /// <summary> /// /// </summary> public bool autoSize { get { return _autoSize; } set { if (_autoSize != value) { _autoSize = value; UpdateLayout(); } } } /// <summary> /// /// </summary> public bool playing { get { return _content.playing; } set { _content.playing = value; UpdateGear(5); } } /// <summary> /// /// </summary> public int frame { get { return _content.frame; } set { _content.frame = value; UpdateGear(5); } } /// <summary> /// /// </summary> public float timeScale { get { return _content.timeScale; } set { _content.timeScale = value; } } /// <summary> /// /// </summary> public bool ignoreEngineTimeScale { get { return _content.ignoreEngineTimeScale; } set { _content.ignoreEngineTimeScale = value; } } /// <summary> /// /// </summary> /// <param name="time"></param> public void Advance(float time) { _content.Advance(time); } /// <summary> /// /// </summary> public Material material { get { return _content.material; } set { _content.material = value; } } /// <summary> /// /// </summary> public string shader { get { return _content.shader; } set { _content.shader = value; } } /// <summary> /// /// </summary> public Color color { get { return _content.color; } set { if (_content.color != value) { _content.color = value; UpdateGear(4); } } } /// <summary> /// /// </summary> public FillMethod fillMethod { get { return _content.fillMethod; } set { _content.fillMethod = value; } } /// <summary> /// /// </summary> public int fillOrigin { get { return _content.fillOrigin; } set { _content.fillOrigin = value; } } /// <summary> /// /// </summary> public bool fillClockwise { get { return _content.fillClockwise; } set { _content.fillClockwise = value; } } /// <summary> /// /// </summary> public float fillAmount { get { return _content.fillAmount; } set { _content.fillAmount = value; } } /// <summary> /// /// </summary> public Image image { get { return _content; } } /// <summary> /// /// </summary> public MovieClip movieClip { get { return _content; } } /// <summary> /// /// </summary> public GComponent component { get { return _content2; } } /// <summary> /// /// </summary> public NTexture texture { get { return _content.texture; } set { this.url = null; _content.texture = value; if (value != null) { sourceWidth = value.width; sourceHeight = value.height; } else { sourceWidth = sourceHeight = 0; } UpdateLayout(); } } override public IFilter filter { get { return _content.filter; } set { _content.filter = value; } } override public BlendMode blendMode { get { return _content.blendMode; } set { _content.blendMode = value; } } /// <summary> /// /// </summary> protected void LoadContent() { ClearContent(); if (string.IsNullOrEmpty(_url)) return; if (_url.StartsWith(UIPackage.URL_PREFIX)) LoadFromPackage(_url); else LoadExternal(); } protected void LoadFromPackage(string itemURL) { _contentItem = UIPackage.GetItemByURL(itemURL); if (_contentItem != null) { _contentItem = _contentItem.getBranch(); sourceWidth = _contentItem.width; sourceHeight = _contentItem.height; _contentItem = _contentItem.getHighResolution(); _contentItem.Load(); if (_contentItem.type == PackageItemType.Image) { _content.texture = _contentItem.texture; _content.textureScale = new Vector2(_contentItem.width / (float)sourceWidth, _contentItem.height / (float)sourceHeight); _content.scale9Grid = _contentItem.scale9Grid; _content.scaleByTile = _contentItem.scaleByTile; _content.tileGridIndice = _contentItem.tileGridIndice; UpdateLayout(); } else if (_contentItem.type == PackageItemType.MovieClip) { _content.interval = _contentItem.interval; _content.swing = _contentItem.swing; _content.repeatDelay = _contentItem.repeatDelay; _content.frames = _contentItem.frames; UpdateLayout(); } else if (_contentItem.type == PackageItemType.Component) { GObject obj = UIPackage.CreateObjectFromURL(itemURL); if (obj == null) SetErrorState(); else if (!(obj is GComponent)) { obj.Dispose(); SetErrorState(); } else { _content2 = (GComponent)obj; ((Container)displayObject).AddChild(_content2.displayObject); UpdateLayout(); } } else { if (_autoSize) this.SetSize(_contentItem.width, _contentItem.height); SetErrorState(); Debug.LogWarning("Unsupported type of GLoader: " + _contentItem.type); } } else SetErrorState(); } virtual protected void LoadExternal() { Texture2D tex = (Texture2D)Resources.Load(_url, typeof(Texture2D)); if (tex != null) onExternalLoadSuccess(new NTexture(tex)); else onExternalLoadFailed(); } virtual protected void FreeExternal(NTexture texture) { } protected void onExternalLoadSuccess(NTexture texture) { _content.texture = texture; sourceWidth = texture.width; sourceHeight = texture.height; _content.scale9Grid = null; _content.scaleByTile = false; texture.onSizeChanged += _reloadDelegate; UpdateLayout(); } protected void onExternalLoadFailed() { SetErrorState(); } void OnExternalReload(NTexture texture) { sourceWidth = texture.width; sourceHeight = texture.height; UpdateLayout(); } private void SetErrorState() { if (!showErrorSign || !Application.isPlaying) return; if (_errorSign == null) { if (UIConfig.loaderErrorSign != null) _errorSign = UIPackage.CreateObjectFromURL(UIConfig.loaderErrorSign); else return; } if (_errorSign != null) { _errorSign.SetSize(this.width, this.height); ((Container)displayObject).AddChild(_errorSign.displayObject); } } protected void ClearErrorState() { if (_errorSign != null && _errorSign.displayObject.parent != null) ((Container)displayObject).RemoveChild(_errorSign.displayObject); } protected void UpdateLayout() { if (_content2 == null && _content.texture == null && _content.frames == null) { if (_autoSize) { _updatingLayout = true; SetSize(50, 30); _updatingLayout = false; } return; } float contentWidth = sourceWidth; float contentHeight = sourceHeight; if (_autoSize) { _updatingLayout = true; if (contentWidth == 0) contentWidth = 50; if (contentHeight == 0) contentHeight = 30; SetSize(contentWidth, contentHeight); _updatingLayout = false; if (_width == contentWidth && _height == contentHeight) { if (_content2 != null) { _content2.SetXY(0, 0); _content2.SetScale(1, 1); } else { _content.SetXY(0, 0); _content.SetSize(contentWidth, contentHeight); } InvalidateBatchingState(); return; } //如果不相等,可能是由于大小限制造成的,要后续处理 } float sx = 1, sy = 1; if (_fill != FillType.None) { sx = this.width / sourceWidth; sy = this.height / sourceHeight; if (sx != 1 || sy != 1) { if (_fill == FillType.ScaleMatchHeight) sx = sy; else if (_fill == FillType.ScaleMatchWidth) sy = sx; else if (_fill == FillType.Scale) { if (sx > sy) sx = sy; else sy = sx; } else if (_fill == FillType.ScaleNoBorder) { if (sx > sy) sy = sx; else sx = sy; } if (_shrinkOnly) { if (sx > 1) sx = 1; if (sy > 1) sy = 1; } contentWidth = sourceWidth * sx; contentHeight = sourceHeight * sy; } } if (_content2 != null) _content2.SetScale(sx, sy); else _content.size = new Vector2(contentWidth, contentHeight); float nx; float ny; if (_align == AlignType.Center) nx = (this.width - contentWidth) / 2; else if (_align == AlignType.Right) nx = this.width - contentWidth; else nx = 0; if (_verticalAlign == VertAlignType.Middle) ny = (this.height - contentHeight) / 2; else if (_verticalAlign == VertAlignType.Bottom) ny = this.height - contentHeight; else ny = 0; if (_content2 != null) _content2.SetXY(nx, ny); else _content.SetXY(nx, ny); InvalidateBatchingState(); } private void ClearContent() { ClearErrorState(); if (_content.texture != null) { if (_contentItem == null) { _content.texture.onSizeChanged -= _reloadDelegate; FreeExternal(_content.texture); } _content.texture = null; } _content.frames = null; if (_content2 != null) { _content2.Dispose(); _content2 = null; } _contentItem = null; } override protected void HandleSizeChanged() { base.HandleSizeChanged(); if (!_updatingLayout) UpdateLayout(); } override public void Setup_BeforeAdd(ByteBuffer buffer, int beginPos) { base.Setup_BeforeAdd(buffer, beginPos); buffer.Seek(beginPos, 5); _url = buffer.ReadS(); _align = (AlignType)buffer.ReadByte(); _verticalAlign = (VertAlignType)buffer.ReadByte(); _fill = (FillType)buffer.ReadByte(); _shrinkOnly = buffer.ReadBool(); _autoSize = buffer.ReadBool(); showErrorSign = buffer.ReadBool(); _content.playing = buffer.ReadBool(); _content.frame = buffer.ReadInt(); if (buffer.ReadBool()) _content.color = buffer.ReadColor(); _content.fillMethod = (FillMethod)buffer.ReadByte(); if (_content.fillMethod != FillMethod.None) { _content.fillOrigin = buffer.ReadByte(); _content.fillClockwise = buffer.ReadBool(); _content.fillAmount = buffer.ReadFloat(); } if (!string.IsNullOrEmpty(_url)) LoadContent(); } } }
28.284457
141
0.40337
[ "MIT" ]
1901/FairyGUI-unity
Assets/Scripts/UI/GLoader.cs
19,340
C#
using DomainFramework.Core; using System; using System.Collections.Generic; namespace PersonWithDisciples.PersonBoundedContext { public class Person : Entity<int> { public string Name { get; set; } public char Gender { get; set; } public int CreatedBy { get; set; } public DateTime CreatedDateTime { get; set; } public int? UpdatedBy { get; set; } public DateTime? UpdatedDateTime { get; set; } public int? LeaderId { get; set; } } }
21.208333
54
0.634578
[ "MIT" ]
jgonte/DomainFramework
DomainFramework.Tests/PersonWithDisciples/PersonBoundedContext/Entities/Person.cs
509
C#
namespace ArmyAntServer_TestClient_CSharp { partial class Form_Main { /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清理所有正在使用的资源。 /// </summary> /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows 窗体设计器生成的代码 /// <summary> /// 设计器支持所需的方法 - 不要修改 /// 使用代码编辑器修改此方法的内容。 /// </summary> private void InitializeComponent() { this.receiveTextBox = new System.Windows.Forms.TextBox(); this.sendTextBox = new System.Windows.Forms.TextBox(); this.btnConnectinout = new System.Windows.Forms.Button(); this.btnLoginout = new System.Windows.Forms.Button(); this.btnSend = new System.Windows.Forms.Button(); this.loginNameTextBox = new System.Windows.Forms.TextBox(); this.btnBroadcast = new System.Windows.Forms.Button(); this.targetUserTextBox = new System.Windows.Forms.TextBox(); this.statusStrip = new System.Windows.Forms.StatusStrip(); this.toolStripStatus_Label = new System.Windows.Forms.ToolStripStatusLabel(); this.cbWebsocket = new System.Windows.Forms.CheckBox(); this.statusStrip.SuspendLayout(); this.SuspendLayout(); // // receiveTextBox // this.receiveTextBox.AcceptsReturn = true; this.receiveTextBox.AcceptsTab = true; this.receiveTextBox.Location = new System.Drawing.Point(12, 39); this.receiveTextBox.Multiline = true; this.receiveTextBox.Name = "receiveTextBox"; this.receiveTextBox.ReadOnly = true; this.receiveTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Horizontal; this.receiveTextBox.Size = new System.Drawing.Size(617, 279); this.receiveTextBox.TabIndex = 0; // // sendTextBox // this.sendTextBox.AcceptsReturn = true; this.sendTextBox.AcceptsTab = true; this.sendTextBox.Location = new System.Drawing.Point(12, 351); this.sendTextBox.Multiline = true; this.sendTextBox.Name = "sendTextBox"; this.sendTextBox.Size = new System.Drawing.Size(617, 87); this.sendTextBox.TabIndex = 1; this.sendTextBox.TextChanged += new System.EventHandler(this.sendTextBox_TextChanged); // // btnConnectinout // this.btnConnectinout.Location = new System.Drawing.Point(635, 36); this.btnConnectinout.Name = "btnConnectinout"; this.btnConnectinout.Size = new System.Drawing.Size(153, 34); this.btnConnectinout.TabIndex = 2; this.btnConnectinout.Text = "连接服务器"; this.btnConnectinout.UseVisualStyleBackColor = true; this.btnConnectinout.Click += new System.EventHandler(this.btnConnectinout_Click); // // btnLoginout // this.btnLoginout.Location = new System.Drawing.Point(635, 76); this.btnLoginout.Name = "btnLoginout"; this.btnLoginout.Size = new System.Drawing.Size(153, 34); this.btnLoginout.TabIndex = 3; this.btnLoginout.Text = "登录EchoServer"; this.btnLoginout.UseVisualStyleBackColor = true; this.btnLoginout.Click += new System.EventHandler(this.btnLoginout_Click); // // btnSend // this.btnSend.Location = new System.Drawing.Point(635, 404); this.btnSend.Name = "btnSend"; this.btnSend.Size = new System.Drawing.Size(153, 34); this.btnSend.TabIndex = 4; this.btnSend.Text = "发送给指定用户"; this.btnSend.UseVisualStyleBackColor = true; this.btnSend.Click += new System.EventHandler(this.btnSend_ClickAsync); // // loginNameTextBox // this.loginNameTextBox.Location = new System.Drawing.Point(12, 12); this.loginNameTextBox.Name = "loginNameTextBox"; this.loginNameTextBox.Size = new System.Drawing.Size(617, 21); this.loginNameTextBox.TabIndex = 5; this.loginNameTextBox.TextChanged += new System.EventHandler(this.loginNameTextBox_TextChanged); // // btnBroadcast // this.btnBroadcast.Location = new System.Drawing.Point(635, 364); this.btnBroadcast.Name = "btnBroadcast"; this.btnBroadcast.Size = new System.Drawing.Size(153, 34); this.btnBroadcast.TabIndex = 6; this.btnBroadcast.Text = "发送群体消息"; this.btnBroadcast.UseVisualStyleBackColor = true; this.btnBroadcast.Click += new System.EventHandler(this.btnBroadcast_Click); // // targetUserTextBox // this.targetUserTextBox.Location = new System.Drawing.Point(12, 324); this.targetUserTextBox.Name = "targetUserTextBox"; this.targetUserTextBox.Size = new System.Drawing.Size(617, 21); this.targetUserTextBox.TabIndex = 7; this.targetUserTextBox.TextChanged += new System.EventHandler(this.targetUserTextBox_TextChanged); // // statusStrip // this.statusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripStatus_Label}); this.statusStrip.Location = new System.Drawing.Point(0, 450); this.statusStrip.Name = "statusStrip"; this.statusStrip.Size = new System.Drawing.Size(800, 22); this.statusStrip.TabIndex = 8; this.statusStrip.Text = "statusStrip1"; // // toolStripStatus_Label // this.toolStripStatus_Label.Name = "toolStripStatus_Label"; this.toolStripStatus_Label.Size = new System.Drawing.Size(124, 17); this.toolStripStatus_Label.Text = "就绪 "; // // cbWebsocket // this.cbWebsocket.AutoSize = true; this.cbWebsocket.Location = new System.Drawing.Point(662, 14); this.cbWebsocket.Name = "cbWebsocket"; this.cbWebsocket.Size = new System.Drawing.Size(102, 16); this.cbWebsocket.TabIndex = 9; this.cbWebsocket.Text = "使用websocket"; this.cbWebsocket.UseVisualStyleBackColor = true; // // Form_Main // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center; this.ClientSize = new System.Drawing.Size(800, 472); this.Controls.Add(this.cbWebsocket); this.Controls.Add(this.statusStrip); this.Controls.Add(this.targetUserTextBox); this.Controls.Add(this.btnBroadcast); this.Controls.Add(this.loginNameTextBox); this.Controls.Add(this.btnSend); this.Controls.Add(this.btnLoginout); this.Controls.Add(this.btnConnectinout); this.Controls.Add(this.sendTextBox); this.Controls.Add(this.receiveTextBox); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "Form_Main"; this.Text = "ArmyAntServer测试客户端"; this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.Form_Main_FormClosed); this.Load += new System.EventHandler(this.Form_onLoad); this.statusStrip.ResumeLayout(false); this.statusStrip.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox receiveTextBox; private System.Windows.Forms.TextBox sendTextBox; private System.Windows.Forms.Button btnConnectinout; private System.Windows.Forms.Button btnLoginout; private System.Windows.Forms.Button btnSend; private System.Windows.Forms.TextBox loginNameTextBox; private System.Windows.Forms.Button btnBroadcast; private System.Windows.Forms.TextBox targetUserTextBox; private System.Windows.Forms.StatusStrip statusStrip; private System.Windows.Forms.ToolStripStatusLabel toolStripStatus_Label; private System.Windows.Forms.CheckBox cbWebsocket; } }
46.183673
110
0.604949
[ "BSD-3-Clause" ]
Army-Ant/ArmyAntServer
test/ArmyAntServer_TestClient_CSharp/ArmyAntServer_TestClient_CSharp/Form_Main.Designer.cs
9,266
C#
using System.Web; using System.Web.Optimization; namespace ASP.NET_MVC_Tutorial { public class BundleConfig { // For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at https://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css")); } } }
39.09375
113
0.576339
[ "Apache-2.0" ]
arifahmed411/ASP.NET_MVC_APP
ASP.NET_MVC_Tutorial/ASP.NET_MVC_Tutorial/App_Start/BundleConfig.cs
1,253
C#
using AltinnCore.Common.Configuration; using AltinnCore.Common.Helpers; using AltinnCore.Common.Services.Interfaces; using AltinnCore.ServiceLibrary.ServiceMetadata; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Options; using System.Collections.Generic; using System.IO; using System.Linq; namespace AltinnCore.Common.Services.Implementation { /// <summary> /// Service that handles functionality needed for creating and updating services in AltinnCore /// </summary> public class TestingRepository : ITestingRepository { private readonly IDefaultFileFactory _defaultFileFactory; private readonly ServiceRepositorySettings _settings; private readonly GeneralSettings _generalSettings; private readonly IHttpContextAccessor _httpContextAccessor; /// <summary> /// Initializes a new instance of the <see cref="RepositorySI"/> class /// </summary> /// <param name="repositorySettings">The settings for the service repository</param> /// <param name="generalSettings">The current general settings</param> /// <param name="defaultFileFactory">The default factory</param> public TestingRepository(IOptions<ServiceRepositorySettings> repositorySettings, IOptions<GeneralSettings> generalSettings, IDefaultFileFactory defaultFileFactory, IHttpContextAccessor httpContextAccessor) { _defaultFileFactory = defaultFileFactory; _settings = repositorySettings.Value; _generalSettings = generalSettings.Value; _httpContextAccessor = httpContextAccessor; } /// <summary> /// Create Test metadata for a service /// </summary> /// <param name="org">The Organization code for the service owner</param> /// <param name="service">The service code for the current service</param> /// <param name="test">The test metadata</param> /// <returns>A boolean indicating if saving was ok</returns> public bool UpdateTest(string org, string service, TestMetadata test) { string dirName = _settings.GetTestPath(org, service, AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext)); bool updated = false; if(!Directory.Exists(dirName)) { Directory.CreateDirectory(dirName); } if (string.IsNullOrEmpty(test.FileName)) { // TODO: Use type test.FileName = test.Name + ".cs"; } File.WriteAllText(dirName + test.FileName, test.Content ?? ""); updated = true; return updated; } /// <summary> /// Get the view content for a given razor file on disk /// </summary> /// <param name="org">The Organization code for the service owner</param> /// <param name="service">The service code for the current service</param> /// <param name="name">The name of the test file</param> /// <returns>The content of the test</returns> public string GetTest(string org, string service, string name) { IList<TestMetadata> tests = GetTests(org, service, true, name); string test = null; if (tests.Count == 1) { test = tests.First().Content; } return test; } /// <summary> /// Get the view content for a given razor file on disk /// </summary> /// <param name="org">The Organization code for the service owner</param> /// <param name="service">The service code for the current service</param> /// <param name="includeContent">Controls if the test content should be included. Default is false.</param> /// /// <param name="filterPattern">Pattern to filter the returned tests</param> /// <returns>All the tests</returns> public IList<TestMetadata> GetTests(string org, string service, bool includeContent = false, string filterPattern = "*") { IList<TestMetadata> tests = new List<TestMetadata>(); string dirName = _settings.GetTestPath(org, service, AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext)); if(!Directory.Exists(dirName)) { return tests; } string[] files = Directory.GetFiles(dirName, filterPattern); foreach (string filename in files) { var test = new TestMetadata { Name = Path.GetFileNameWithoutExtension(filename), FileName = filename }; if (includeContent) { test.Content = File.ReadAllText(filename); } tests.Add(test); } return tests; } } }
39.904
142
0.613873
[ "BSD-3-Clause" ]
iotryti/altinn-studio
src/AltinnCore/Common/Services/Implementation/TestingRepository.cs
4,988
C#
namespace MemoryVizualizer.UI { using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Forms; using System.Drawing; using MemoryVizualizer.Formats; public partial class RealtimeBitmap : UserControl { public FastBitmap bitmap = null; public PixFormat curFormat = null; public int W = 256; public int H = 256; public RealtimeBitmap() { InitializeComponent(); bitmap = new FastBitmap(W, H); disp.Image = bitmap.Bitmap; } public void SetSize(int w, int h) { var oldBmp = bitmap; bitmap = new FastBitmap(w, h); disp.Image = bitmap.Bitmap; W = w; H = h; oldBmp.Dispose(); } public void SetBytes(byte[] bytes) { //disp.Visible = false; SetPixels(bytes); //disp.Visible = true; } //protected override di //Does not refresh private void SetPixels(byte[] bts) { int pw = curFormat.BytesWide; int mx = bts.Length; int curOffset = 0; if (!curFormat.CustomParsing) { for (int y = 0; y < H; y++) { for (int x = 0; x < W; x++) { if (curOffset + pw > mx) { //Missing textures yay if ((y / 4) % 2 == 0) { if ((x / 4) % 2 == 0) bitmap.SetPixel(x, y, Color.Magenta); else bitmap.SetPixel(x, y, Color.Black); } else { if ((x / 4) % 2 == 0) bitmap.SetPixel(x, y, Color.Black); else bitmap.SetPixel(x, y, Color.Magenta); } //return; } else { bitmap.SetPixel(x, y, curFormat.Parse(bts, curOffset)); curOffset += pw; } } } } else { if (W % curFormat.Pixels != 0) return; curFormat.CustomParse(bitmap, bts); //for (int y = 0; y < bitmap.Height; y++) //{ // for (int x = 0; x < bitmap.Width;) // { // if (curOffset + pw > mx) // { // if ((y / 4) % 2 == 0) // { // if ((x / 4) % 2 == 0) bitmap.SetPixel(x, y, Color.Magenta); // else bitmap.SetPixel(x, y, Color.Black); // } // else // { // if ((x / 4) % 2 == 0) bitmap.SetPixel(x, y, Color.Black); // else bitmap.SetPixel(x, y, Color.Magenta); // } // x++; // } // else // { // var px = curFormat.ParseMultiple(bts, curOffset); // for (int j = 0; j < curFormat.Pixels; j++) // { // bitmap.SetPixel(x + j, y, px[j]); // } // curOffset += pw * curFormat.Pixels; // x += curFormat.Pixels; // } // } //} } } } }
32.936
93
0.346612
[ "MIT" ]
NullShock78/MemoryVisualizerPlugin
RTCV_Plugin_MemoryVisualizer/MemoryVisualizerPlugin/UI/RealtimeBitmap.cs
4,117
C#
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace InteropTypes.Graphics.Drawing { internal partial class TypeTests { [Test] public void MatrixFromVectors() { var xform = Matrix3x2.CreateRotation(1) * Matrix3x2.CreateTranslation(5, 5); Span<Vector2> points = stackalloc Vector2[3]; points[0] = new Vector2(0, 0); points[1] = new Vector2(10, 0); points[2] = new Vector2(0, 10); for(int i = 0; i < 3; i++) points[i] = Vector2.Transform(points[i], xform); var dx = points[1] - points[0]; var dy = points[2] - points[0]; var ww = dx.Length(); var hh = dy.Length(); dx = Vector2.Normalize(dx); dy = Vector2.Normalize(dy); var m = new Matrix3x2(dx.X, dx.Y, dy.X, dy.Y, points[0].X, points[0].Y); } [Test] public void CameraTransform2DTests() { var cam1 = CameraTransform2D.Create(Matrix3x2.Identity, (500, 500)); // Top-Down var cam2 = CameraTransform2D.Create(Matrix3x2.Identity, (500, -500)); // Bottom-Top Point2 p1 = Vector2.Transform(Vector2.Zero, cam1.CreateFinalMatrix((500, 500))); Assert.AreEqual(Point2.Zero, p1); p1 = Vector2.Transform(Vector2.Zero, cam2.CreateFinalMatrix((1000, 1000))); Assert.AreEqual(new Point2(0, 1000), p1); p1 = Vector2.Transform(Vector2.Zero, cam1.CreateFinalMatrix((1000, 500))); Assert.AreEqual(new Point2(250, 0), p1); } [Test] public void CameraOuterBoundsTests() { // create physical viewport var backend = new DummyBackend2D(2000, 500); // virtual camera var innerCamera = CameraTransform2D.Create(Matrix3x2.CreateTranslation(700,0), (500, -500)); // get virtual viewport Assert.IsTrue(Transforms.Canvas2DTransform.TryCreate(backend, innerCamera, out var virtualCanvas)); // draw onto the virtual canvas virtualCanvas.DrawRectangle((2, 2), (1, 1), System.Drawing.Color.Red); // check bounds in the physical backend var (bMin, bMax) = backend.BoundingBox; Assert.AreEqual(53, bMax.X); Assert.AreEqual(498, bMax.Y); bMax -= bMin; Assert.AreEqual(1, bMax.X); Assert.AreEqual(1, bMax.Y); // check if we can retrieve the outer camera bounds Assert.IsTrue(CameraTransform2D.TryGetOuterCamera(virtualCanvas, out var outerCamera)); var outerRect = outerCamera.GetOuterBoundingRect(); Assert.AreEqual(-50, outerRect.X); Assert.AreEqual(0, outerRect.Y); Assert.AreEqual(2000, outerRect.Width); Assert.AreEqual(500, outerRect.Height); } } }
35.137931
111
0.581616
[ "MIT" ]
vpenades/InteropBitmaps
src/InteropTypes.Graphics.Drawing.Core.Tests/CameraTransform2D.Tests.cs
3,059
C#
using System.Xml; namespace DbShell.Driver.Common.DmlFramework { public class DmlfPlaceholderExpression : DmlfStringValueExpressionBase { public DmlfPlaceholderExpression() { } public DmlfPlaceholderExpression(XmlElement xml) { LoadFromXml(xml); } protected override string GetTypeName() { return "placeholder"; } public override object EvalExpression(IDmlfNamespace ns) { return ns.GetValue(Value); } } }
21.269231
74
0.596745
[ "MIT" ]
dbshell/dbshell
DbShell.Driver.Common/DmlFramework/DmlfPlaceholderExpression.cs
553
C#
using System.Threading; using System.Threading.Tasks; using Orange.AirportToAirportDistanceCalculator.Domain.Models; namespace Orange.AirportToAirportDistanceCalculator.Domain.Interfaces { /// <summary> /// A service that provides information about airports /// </summary> public interface IAirportInformationProviderService { /// <summary> /// Get airport information using IATA. /// </summary> /// <param name="IATACode">The IATA code.</param> /// <param name="cancellationToken">The cancellation token.</param> Task<AirportInformation?> GetInformationAsync(string IATACode, CancellationToken cancellationToken = default); } }
35.15
118
0.708393
[ "MIT" ]
ReyStar/Orange.AirportToAirportDistanceCalculator
src/Orange.AirportToAirportDistanceCalculator.Domain/Interfaces/IAirportInformationProviderService.cs
705
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using Foundation; using UIKit; using ContextKit; using HockeyApp; namespace CNotes { public partial class CNotesTvc : UITableViewController { const string showDetail = "showDetail"; List<CNote> notes => CkContext.Shared.Notes; public CNotesTvc (IntPtr handle) : base (handle) { } bool refreshedContext; public override void ViewWillAppear (bool animated) { base.ViewWillAppear (animated); if (!refreshedContext) { Log ("Refreshing Context"); activityIndicator.Hidden = false; activityIndicator.StartAnimating (); Task.Run (async () => { await CkContext.Shared.RefreshContextAndSortNotes (); BeginInvokeOnMainThread (() => { reloadData (); activityIndicator.StopAnimating (); }); refreshedContext = true; }); } else { reloadData (); } } public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) { if (segue.Identifier == showDetail) { var notesVc = (segue.DestinationViewController as UINavigationController)?.TopViewController as CNotesVc; if (notesVc != null) { var cell = sender as UITableViewCell; if (cell != null) { var index = TableView.IndexPathForCell (cell).Row; var note = notes [index]; CkContext.Shared.SelectedNote = note; notesVc.Title = note.Title; BITHockeyManager.SharedHockeyManager.MetricsManager.TrackEvent (string.Format (HockeyEventIds.OpenedNoteFmt, index)); Log ($"Set Note Selected: {note}"); } } } base.PrepareForSegue (segue, sender); } public override nint NumberOfSections (UITableView tableView) => 1; public override nint RowsInSection (UITableView tableView, nint section) => notes.Count; public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { var cell = tableView.Dequeue<CNotesTvCell> (indexPath); var note = notes [indexPath.Row]; cell.SetData (note); return cell; } public override void CommitEditingStyle (UITableView tableView, UITableViewCellEditingStyle editingStyle, NSIndexPath indexPath) { if (editingStyle == UITableViewCellEditingStyle.Delete) { var note = notes [indexPath.Row]; CkContext.Shared.DeleteNote (note); tableView.DeleteRows (new [] { indexPath }, UITableViewRowAnimation.Automatic); } } partial void editClicked (NSObject sender) { BITHockeyManager.SharedHockeyManager.MetricsManager.TrackEvent (HockeyEventIds.SelectedEditNotes); //CkContext.Shared.PrintEvents (); } partial void composeClicked (NSObject sender) { BITHockeyManager.SharedHockeyManager.MetricsManager.TrackEvent (HockeyEventIds.SelectedNewNote); CkContext.Shared.CreateNewNote (); reloadData (); Log ($"Notes.Count (B) {notes.Count}"); Task.Run (async () => { await CkContext.Shared.AddContextPoint (); Log ($"Notes.Count (C) {notes.Count}"); BeginInvokeOnMainThread (() => reloadData ()); }); PerformSegue (showDetail, sender); } void reloadData () { Log ("ReloadData"); noteCountLabel.Title = $"{notes.Count} Notes"; TableView.ReloadData (); } bool log = true; void Log (string message) { if (log) System.Diagnostics.Debug.WriteLine ($"[CNotesTvc] {message}"); } } }
20.567073
130
0.693744
[ "MIT" ]
colbylwilliams/C-Notes
CNotes/CNotes/ViewControllers/CNotesTvc.cs
3,373
C#
namespace SchedulingAlgorithms { partial class MainForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea(); System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend(); System.Windows.Forms.DataVisualization.Charting.Series series1 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm)); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.chart = new System.Windows.Forms.DataVisualization.Charting.Chart(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.btnRemove = new System.Windows.Forms.Button(); this.btnAdd = new System.Windows.Forms.Button(); this.label3 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.txtLabel = new System.Windows.Forms.TextBox(); this.Label1 = new System.Windows.Forms.Label(); this.nudDuration = new System.Windows.Forms.NumericUpDown(); this.nudArrival = new System.Windows.Forms.NumericUpDown(); this.ProcessListView = new System.Windows.Forms.ListView(); this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader3 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.Options = new System.Windows.Forms.GroupBox(); this.label6 = new System.Windows.Forms.Label(); this.nudFBQ = new System.Windows.Forms.NumericUpDown(); this.label5 = new System.Windows.Forms.Label(); this.nudRRQ = new System.Windows.Forms.NumericUpDown(); this.menuStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.chart)).BeginInit(); this.groupBox1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.nudDuration)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.nudArrival)).BeginInit(); this.Options.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.nudFBQ)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.nudRRQ)).BeginInit(); this.SuspendLayout(); // // menuStrip1 // this.menuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20); this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(762, 28); this.menuStrip1.TabIndex = 0; this.menuStrip1.Text = "menuStrip1"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(46, 24); this.fileToolStripMenuItem.Text = "File"; // // chart // this.chart.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); chartArea1.Name = "ChartArea1"; this.chart.ChartAreas.Add(chartArea1); legend1.Name = "Legend1"; this.chart.Legends.Add(legend1); this.chart.Location = new System.Drawing.Point(12, 48); this.chart.Name = "chart"; series1.ChartArea = "ChartArea1"; series1.Legend = "Legend1"; series1.Name = "Series1"; this.chart.Series.Add(series1); this.chart.Size = new System.Drawing.Size(738, 434); this.chart.TabIndex = 25; this.chart.Text = "chart"; // // groupBox1 // this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.groupBox1.Controls.Add(this.btnRemove); this.groupBox1.Controls.Add(this.btnAdd); this.groupBox1.Controls.Add(this.label3); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.Add(this.txtLabel); this.groupBox1.Controls.Add(this.Label1); this.groupBox1.Controls.Add(this.nudDuration); this.groupBox1.Controls.Add(this.nudArrival); this.groupBox1.Controls.Add(this.ProcessListView); this.groupBox1.Location = new System.Drawing.Point(12, 577); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(738, 264); this.groupBox1.TabIndex = 2; this.groupBox1.TabStop = false; this.groupBox1.Text = "Process Editor"; // // btnRemove // this.btnRemove.FlatStyle = System.Windows.Forms.FlatStyle.System; this.btnRemove.Location = new System.Drawing.Point(638, 46); this.btnRemove.Name = "btnRemove"; this.btnRemove.Size = new System.Drawing.Size(100, 23); this.btnRemove.TabIndex = 22; this.btnRemove.Text = "Remove"; this.btnRemove.UseVisualStyleBackColor = true; this.btnRemove.Click += new System.EventHandler(this.btnRemove_Click); // // btnAdd // this.btnAdd.FlatStyle = System.Windows.Forms.FlatStyle.System; this.btnAdd.Location = new System.Drawing.Point(532, 46); this.btnAdd.Name = "btnAdd"; this.btnAdd.Size = new System.Drawing.Size(100, 23); this.btnAdd.TabIndex = 21; this.btnAdd.Text = "Add"; this.btnAdd.UseVisualStyleBackColor = true; this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click); // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(271, 27); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(101, 17); this.label3.TabIndex = 19; this.label3.Text = "Duration Time:"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(137, 27); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(87, 17); this.label2.TabIndex = 18; this.label2.Text = "Arrival Time:"; // // txtLabel // this.txtLabel.Location = new System.Drawing.Point(6, 47); this.txtLabel.Name = "txtLabel"; this.txtLabel.Size = new System.Drawing.Size(100, 22); this.txtLabel.TabIndex = 1; // // Label1 // this.Label1.AutoSize = true; this.Label1.Location = new System.Drawing.Point(3, 27); this.Label1.Name = "Label1"; this.Label1.Size = new System.Drawing.Size(97, 17); this.Label1.TabIndex = 16; this.Label1.Text = "Process label:"; // // nudDuration // this.nudDuration.Location = new System.Drawing.Point(274, 47); this.nudDuration.Name = "nudDuration"; this.nudDuration.Size = new System.Drawing.Size(100, 22); this.nudDuration.TabIndex = 3; // // nudArrival // this.nudArrival.Location = new System.Drawing.Point(140, 47); this.nudArrival.Name = "nudArrival"; this.nudArrival.Size = new System.Drawing.Size(100, 22); this.nudArrival.TabIndex = 2; // // ProcessListView // this.ProcessListView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.ProcessListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader1, this.columnHeader2, this.columnHeader3}); this.ProcessListView.FullRowSelect = true; this.ProcessListView.GridLines = true; this.ProcessListView.HideSelection = false; this.ProcessListView.Location = new System.Drawing.Point(6, 75); this.ProcessListView.Name = "ProcessListView"; this.ProcessListView.Size = new System.Drawing.Size(726, 183); this.ProcessListView.TabIndex = 15; this.ProcessListView.UseCompatibleStateImageBehavior = false; this.ProcessListView.View = System.Windows.Forms.View.Details; // // columnHeader1 // this.columnHeader1.Text = "Label"; // // columnHeader2 // this.columnHeader2.Text = "Arrival Time"; this.columnHeader2.Width = 100; // // columnHeader3 // this.columnHeader3.Text = "Duration Time"; this.columnHeader3.Width = 100; // // Options // this.Options.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.Options.Controls.Add(this.label6); this.Options.Controls.Add(this.nudFBQ); this.Options.Controls.Add(this.label5); this.Options.Controls.Add(this.nudRRQ); this.Options.Location = new System.Drawing.Point(12, 488); this.Options.Name = "Options"; this.Options.Size = new System.Drawing.Size(738, 83); this.Options.TabIndex = 3; this.Options.TabStop = false; this.Options.Text = "Options"; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(137, 30); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(91, 17); this.label6.TabIndex = 28; this.label6.Text = "FB Quantum:"; // // nudFBQ // this.nudFBQ.Location = new System.Drawing.Point(140, 50); this.nudFBQ.Name = "nudFBQ"; this.nudFBQ.Size = new System.Drawing.Size(100, 22); this.nudFBQ.TabIndex = 27; this.nudFBQ.Value = new decimal(new int[] { 1, 0, 0, 0}); this.nudFBQ.ValueChanged += new System.EventHandler(this.nudFBQ_ValueChanged); // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(3, 30); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(94, 17); this.label5.TabIndex = 26; this.label5.Text = "RR Quantum:"; // // nudRRQ // this.nudRRQ.Location = new System.Drawing.Point(6, 50); this.nudRRQ.Name = "nudRRQ"; this.nudRRQ.Size = new System.Drawing.Size(100, 22); this.nudRRQ.TabIndex = 26; this.nudRRQ.Value = new decimal(new int[] { 1, 0, 0, 0}); this.nudRRQ.ValueChanged += new System.EventHandler(this.nudRRQ_ValueChanged); // // MainForm // this.AcceptButton = this.btnAdd; this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(762, 853); this.Controls.Add(this.Options); this.Controls.Add(this.chart); this.Controls.Add(this.groupBox1); this.Controls.Add(this.menuStrip1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MinimumSize = new System.Drawing.Size(780, 900); this.Name = "MainForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "CPU Scheduling Algorithms [Sajad Afaghiy]"; this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.chart)).EndInit(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.nudDuration)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.nudArrival)).EndInit(); this.Options.ResumeLayout(false); this.Options.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.nudFBQ)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.nudRRQ)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.DataVisualization.Charting.Chart chart; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.ListView ProcessListView; private System.Windows.Forms.Button btnRemove; private System.Windows.Forms.Button btnAdd; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox txtLabel; private System.Windows.Forms.Label Label1; private System.Windows.Forms.NumericUpDown nudDuration; private System.Windows.Forms.NumericUpDown nudArrival; private System.Windows.Forms.ColumnHeader columnHeader1; private System.Windows.Forms.ColumnHeader columnHeader2; private System.Windows.Forms.ColumnHeader columnHeader3; private System.Windows.Forms.GroupBox Options; private System.Windows.Forms.Label label6; private System.Windows.Forms.NumericUpDown nudFBQ; private System.Windows.Forms.Label label5; private System.Windows.Forms.NumericUpDown nudRRQ; } }
47.929619
164
0.59349
[ "MIT" ]
sajadafaghiy/Scheduling-Algorithms
SchedulingAlgorithms/MainForm.Designer.cs
16,346
C#
// The MIT License (MIT) // // Copyright (c) 2015-2021 Rasmus Mikkelsen // Copyright (c) 2015-2021 eBay Software Foundation // https://github.com/eventflow/EventFlow // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System.Linq; using System.Threading; using System.Threading.Tasks; using EventFlow.Core; using EventFlow.PostgreSql.Connections; using EventFlow.PostgreSql.Tests.IntegrationTests.ReadStores.ReadModels; using EventFlow.Queries; using EventFlow.TestHelpers.Aggregates; using EventFlow.TestHelpers.Aggregates.Queries; namespace EventFlow.PostgreSql.Tests.IntegrationTests.ReadStores.QueryHandlers { public class PostgreSqlThingyGetQueryHandler : IQueryHandler<ThingyGetQuery, Thingy> { private readonly IPostgreSqlConnection _postgreSqlConnection; public PostgreSqlThingyGetQueryHandler( IPostgreSqlConnection postgreSqlConnection) { _postgreSqlConnection = postgreSqlConnection; } public async Task<Thingy> ExecuteQueryAsync(ThingyGetQuery query, CancellationToken cancellationToken) { var readModels = await _postgreSqlConnection.QueryAsync<PostgreSqlThingyReadModel>( Label.Named("postgresql-fetch-test-read-model"), cancellationToken, "SELECT * FROM \"ReadModel-ThingyAggregate\" WHERE AggregateId = @AggregateId;", new { AggregateId = query.ThingyId.Value }) .ConfigureAwait(false); return readModels.SingleOrDefault()?.ToThingy(); } } }
45.385965
110
0.741013
[ "MIT" ]
AlexKalnitskiy/EventFlow
Source/EventFlow.PostgreSql.Tests/IntegrationTests/ReadStores/QueryHandlers/PostgresSqlThingyGetQueryHandler.cs
2,587
C#
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" using System; using System.Globalization; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; using TheArtOfDev.HtmlRenderer.Adapters; using TheArtOfDev.HtmlRenderer.Adapters.Entities; using TheArtOfDev.HtmlRenderer.Core.Utils; using TheArtOfDev.HtmlRenderer.WPF.Utilities; namespace TheArtOfDev.HtmlRenderer.WPF.Adapters { /// <summary> /// Adapter for WPF Graphics. /// </summary> internal sealed class GraphicsAdapter : RGraphics { #region Fields and Consts /// <summary> /// The wrapped WPF graphics object /// </summary> private readonly DrawingContext _g; /// <summary> /// if to release the graphics object on dispose /// </summary> private readonly bool _releaseGraphics; #endregion /// <summary> /// Init. /// </summary> /// <param name="g">the WPF graphics object to use</param> /// <param name="initialClip">the initial clip of the graphics</param> /// <param name="releaseGraphics">optional: if to release the graphics object on dispose (default - false)</param> public GraphicsAdapter(DrawingContext g, RRect initialClip, bool releaseGraphics = false) : base(WpfAdapter.Instance, initialClip) { ArgChecker.AssertArgNotNull(g, "g"); _g = g; _releaseGraphics = releaseGraphics; } /// <summary> /// Init. /// </summary> public GraphicsAdapter() : base(WpfAdapter.Instance, RRect.Empty) { _g = null; _releaseGraphics = false; } public override void PopClip() { _g.Pop(); _clipStack.Pop(); } public override void PushClip(RRect rect) { _clipStack.Push(rect); _g.PushClip(new RectangleGeometry(Utils.Convert(rect))); } public override void PushClipExclude(RRect rect) { var geometry = new CombinedGeometry(); geometry.Geometry1 = new RectangleGeometry(Utils.Convert(_clipStack.Peek())); geometry.Geometry2 = new RectangleGeometry(Utils.Convert(rect)); geometry.GeometryCombineMode = GeometryCombineMode.Exclude; _clipStack.Push(_clipStack.Peek()); _g.PushClip(geometry); } public override Object SetAntiAliasSmoothingMode() { return null; } public override void ReturnPreviousSmoothingMode(Object prevMode) { } public override RSize MeasureString(string str, RFont font) { double width = 0; GlyphTypeface glyphTypeface = ((FontAdapter)font).GlyphTypeface; if (glyphTypeface != null) { for (int i = 0; i < str.Length; i++) { if (glyphTypeface.CharacterToGlyphMap.ContainsKey(str[i])) { ushort glyph = glyphTypeface.CharacterToGlyphMap[str[i]]; double advanceWidth = glyphTypeface.AdvanceWidths[glyph]; width += advanceWidth; } else { width = 0; break; } } } if (width <= 0) { var formattedText = new FormattedText(str, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, ((FontAdapter)font).Font, 96d / 72d * font.Size, Brushes.Red); return new RSize(formattedText.WidthIncludingTrailingWhitespace, formattedText.Height); } return new RSize(width * font.Size * 96d / 72d, font.Height); } public override void MeasureString(string str, RFont font, double maxWidth, out int charFit, out double charFitWidth) { charFit = 0; charFitWidth = 0; bool handled = false; GlyphTypeface glyphTypeface = ((FontAdapter)font).GlyphTypeface; if (glyphTypeface != null) { handled = true; double width = 0; for (int i = 0; i < str.Length; i++) { if (glyphTypeface.CharacterToGlyphMap.ContainsKey(str[i])) { ushort glyph = glyphTypeface.CharacterToGlyphMap[str[i]]; double advanceWidth = glyphTypeface.AdvanceWidths[glyph] * font.Size * 96d / 72d; if (!(width + advanceWidth < maxWidth)) { charFit = i; charFitWidth = width; break; } width += advanceWidth; } else { handled = false; break; } } } if (!handled) { var formattedText = new FormattedText(str, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, ((FontAdapter)font).Font, 96d / 72d * font.Size, Brushes.Red); charFit = str.Length; charFitWidth = formattedText.WidthIncludingTrailingWhitespace; } } public override void DrawString(string str, RFont font, RColor color, RPoint point, RSize size, bool rtl) { var colorConv = ((BrushAdapter)_adapter.GetSolidBrush(color)).Brush; bool glyphRendered = false; GlyphTypeface glyphTypeface = ((FontAdapter)font).GlyphTypeface; if (glyphTypeface != null) { double width = 0; ushort[] glyphs = new ushort[str.Length]; double[] widths = new double[str.Length]; int i = 0; for (; i < str.Length; i++) { ushort glyph; if (!glyphTypeface.CharacterToGlyphMap.TryGetValue(str[i], out glyph)) break; glyphs[i] = glyph; width += glyphTypeface.AdvanceWidths[glyph]; widths[i] = 96d / 72d * font.Size * glyphTypeface.AdvanceWidths[glyph]; } if (i >= str.Length) { point.Y += glyphTypeface.Baseline * font.Size * 96d / 72d; point.X += rtl ? 96d / 72d * font.Size * width : 0; glyphRendered = true; var wpfPoint = Utils.ConvertRound(point); var glyphRun = new GlyphRun(glyphTypeface, rtl ? 1 : 0, false, 96d / 72d * font.Size, glyphs, wpfPoint, widths, null, null, null, null, null, null); var guidelines = new GuidelineSet(); guidelines.GuidelinesX.Add(wpfPoint.X); guidelines.GuidelinesY.Add(wpfPoint.Y); _g.PushGuidelineSet(guidelines); _g.DrawGlyphRun(colorConv, glyphRun); _g.Pop(); } } if (!glyphRendered) { var formattedText = new FormattedText(str, CultureInfo.CurrentCulture, rtl ? FlowDirection.RightToLeft : FlowDirection.LeftToRight, ((FontAdapter)font).Font, 96d / 72d * font.Size, colorConv); point.X += rtl ? formattedText.Width : 0; _g.DrawText(formattedText, Utils.ConvertRound(point)); } } public override RBrush GetTextureBrush(RImage image, RRect dstRect, RPoint translateTransformLocation) { var brush = new ImageBrush(((ImageAdapter)image).Image); brush.Stretch = Stretch.None; brush.TileMode = TileMode.Tile; brush.Viewport = Utils.Convert(dstRect); brush.ViewportUnits = BrushMappingMode.Absolute; brush.Transform = new TranslateTransform(translateTransformLocation.X, translateTransformLocation.Y); brush.Freeze(); return new BrushAdapter(brush); } public override RGraphicsPath GetGraphicsPath() { return new GraphicsPathAdapter(); } public override void Dispose() { if (_releaseGraphics) _g.Close(); } #region Delegate graphics methods public override void DrawLine(RPen pen, double x1, double y1, double x2, double y2) { x1 = (int)x1; x2 = (int)x2; y1 = (int)y1; y2 = (int)y2; var adj = pen.Width; if (Math.Abs(x1 - x2) < .1 && Math.Abs(adj % 2 - 1) < .1) { x1 += .5; x2 += .5; } if (Math.Abs(y1 - y2) < .1 && Math.Abs(adj % 2 - 1) < .1) { y1 += .5; y2 += .5; } _g.DrawLine(((PenAdapter)pen).CreatePen(), new Point(x1, y1), new Point(x2, y2)); } public override void DrawRectangle(RPen pen, double x, double y, double width, double height) { var adj = pen.Width; if (Math.Abs(adj % 2 - 1) < .1) { x += .5; y += .5; } _g.DrawRectangle(null, ((PenAdapter)pen).CreatePen(), new Rect(x, y, width, height)); } public override void DrawRectangle(RBrush brush, double x, double y, double width, double height) { _g.DrawRectangle(((BrushAdapter)brush).Brush, null, new Rect(x, y, width, height)); } public override void DrawImage(RImage image, RRect destRect, RRect srcRect) { CroppedBitmap croppedImage = new CroppedBitmap(((ImageAdapter)image).Image, new Int32Rect((int)srcRect.X, (int)srcRect.Y, (int)srcRect.Width, (int)srcRect.Height)); _g.DrawImage(croppedImage, Utils.ConvertRound(destRect)); } public override void DrawImage(RImage image, RRect destRect) { _g.DrawImage(((ImageAdapter)image).Image, Utils.ConvertRound(destRect)); } public override void DrawPath(RPen pen, RGraphicsPath path) { _g.DrawGeometry(null, ((PenAdapter)pen).CreatePen(), ((GraphicsPathAdapter)path).GetClosedGeometry()); } public override void DrawPath(RBrush brush, RGraphicsPath path) { _g.DrawGeometry(((BrushAdapter)brush).Brush, null, ((GraphicsPathAdapter)path).GetClosedGeometry()); } public override void DrawPolygon(RBrush brush, RPoint[] points) { if (points != null && points.Length > 0) { var g = new StreamGeometry(); using (var context = g.Open()) { context.BeginFigure(Utils.Convert(points[0]), true, true); for (int i = 1; i < points.Length; i++) context.LineTo(Utils.Convert(points[i]), true, true); } g.Freeze(); _g.DrawGeometry(((BrushAdapter)brush).Brush, null, g); } } #endregion } }
35.540785
208
0.524651
[ "BSD-3-Clause" ]
symbiogenesis/HTML-Renderer
Source/HtmlRenderer.WPF/Adapters/GraphicsAdapter.cs
11,764
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; namespace HealthChecks_3._1 { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
24.952381
70
0.580153
[ "MIT" ]
PrometheusClientNet/Prometheus.Client.Examples
HealthChecks/HealthChecks_3.1/Program.cs
524
C#
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.NotificationHubs { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// NamespacesOperations operations. /// </summary> internal partial class NamespacesOperations : Microsoft.Rest.IServiceOperations<NotificationHubsManagementClient>, INamespacesOperations { /// <summary> /// Initializes a new instance of the NamespacesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal NamespacesOperations(NotificationHubsManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the NotificationHubsManagementClient /// </summary> public NotificationHubsManagementClient Client { get; private set; } /// <summary> /// Checks the availability of the given service namespace across all Azure /// subscriptions. This is useful because the domain name is created based on /// the service namespace name. /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj870968.aspx" /> /// </summary> /// <param name='parameters'> /// The namespace name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<CheckAvailabilityResult>> CheckAvailabilityWithHttpMessagesAsync(CheckAvailabilityParameters parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (parameters == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "CheckAvailability", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.NotificationHubs/checkNamespaceAvailability").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<CheckAvailabilityResult>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CheckAvailabilityResult>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates/Updates a service namespace. Once created, this namespace's /// resource manifest is immutable. This operation is idempotent. /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='parameters'> /// Parameters supplied to create a Namespace Resource. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<NamespaceResource>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, NamespaceCreateOrUpdateParameters parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (namespaceName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "namespaceName"); } if (parameters == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("namespaceName", namespaceName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201 && (int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<NamespaceResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<NamespaceResource>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<NamespaceResource>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Patches the existing namespace /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='parameters'> /// Parameters supplied to patch a Namespace Resource. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<NamespaceResource>> PatchWithHttpMessagesAsync(string resourceGroupName, string namespaceName, NamespacePatchParameters parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (namespaceName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "namespaceName"); } if (parameters == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "parameters"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("namespaceName", namespaceName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Patch", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<NamespaceResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<NamespaceResource>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes an existing namespace. This operation also removes all associated /// notificationHubs under the namespace. /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856296.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Send request Microsoft.Rest.Azure.AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync( resourceGroupName, namespaceName, customHeaders, cancellationToken); return await this.Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken); } /// <summary> /// Deletes an existing namespace. This operation also removes all associated /// notificationHubs under the namespace. /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856296.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (namespaceName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "namespaceName"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("namespaceName", namespaceName); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204 && (int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Returns the description for the specified namespace. /// <see href="http://msdn.microsoft.com/library/azure/dn140232.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<NamespaceResource>> GetWithHttpMessagesAsync(string resourceGroupName, string namespaceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (namespaceName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "namespaceName"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("namespaceName", namespaceName); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<NamespaceResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<NamespaceResource>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates an authorization rule for a namespace /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='authorizationRuleName'> /// Aauthorization Rule Name. /// </param> /// <param name='parameters'> /// The shared access authorization rule. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<SharedAccessAuthorizationRuleResource>> CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (namespaceName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "namespaceName"); } if (authorizationRuleName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "authorizationRuleName"); } if (parameters == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("namespaceName", namespaceName); tracingParameters.Add("authorizationRuleName", authorizationRuleName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdateAuthorizationRule", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName)); _url = _url.Replace("{authorizationRuleName}", System.Uri.EscapeDataString(authorizationRuleName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<SharedAccessAuthorizationRuleResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<SharedAccessAuthorizationRuleResource>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes a namespace authorization rule /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='authorizationRuleName'> /// Authorization Rule Name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DeleteAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (namespaceName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "namespaceName"); } if (authorizationRuleName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "authorizationRuleName"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("namespaceName", namespaceName); tracingParameters.Add("authorizationRuleName", authorizationRuleName); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "DeleteAuthorizationRule", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName)); _url = _url.Replace("{authorizationRuleName}", System.Uri.EscapeDataString(authorizationRuleName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204 && (int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets an authorization rule for a namespace by name. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// Authorization rule name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<SharedAccessAuthorizationRuleResource>> GetAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (namespaceName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "namespaceName"); } if (authorizationRuleName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "authorizationRuleName"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("namespaceName", namespaceName); tracingParameters.Add("authorizationRuleName", authorizationRuleName); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetAuthorizationRule", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName)); _url = _url.Replace("{authorizationRuleName}", System.Uri.EscapeDataString(authorizationRuleName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<SharedAccessAuthorizationRuleResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<SharedAccessAuthorizationRuleResource>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists the available namespaces within a resourceGroup. /// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. If resourceGroupName value is null the /// method lists all the namespaces within subscription /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NamespaceResource>>> ListWithHttpMessagesAsync(string resourceGroupName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NamespaceResource>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<NamespaceResource>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists all the available namespaces within the subscription irrespective of /// the resourceGroups. /// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" /> /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NamespaceResource>>> ListAllWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListAll", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.NotificationHubs/namespaces").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NamespaceResource>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<NamespaceResource>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets the authorization rules for a namespace. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<SharedAccessAuthorizationRuleResource>>> ListAuthorizationRulesWithHttpMessagesAsync(string resourceGroupName, string namespaceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (namespaceName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "namespaceName"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("namespaceName", namespaceName); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListAuthorizationRules", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/AuthorizationRules").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<SharedAccessAuthorizationRuleResource>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SharedAccessAuthorizationRuleResource>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets the Primary and Secondary ConnectionStrings to the namespace /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj873988.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='authorizationRuleName'> /// The connection string of the namespace for the specified authorizationRule. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<ResourceListKeys>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (namespaceName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "namespaceName"); } if (authorizationRuleName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "authorizationRuleName"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("namespaceName", namespaceName); tracingParameters.Add("authorizationRuleName", authorizationRuleName); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListKeys", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}/listKeys").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName)); _url = _url.Replace("{authorizationRuleName}", System.Uri.EscapeDataString(authorizationRuleName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<ResourceListKeys>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ResourceListKeys>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Regenerates the Primary/Secondary Keys to the Namespace Authorization Rule /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj873988.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='authorizationRuleName'> /// The connection string of the namespace for the specified authorizationRule. /// </param> /// <param name='parameters'> /// Parameters supplied to regenerate the Namespace Authorization Rule Key. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<ResourceListKeys>> RegenerateKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, PolicykeyResource parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (namespaceName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "namespaceName"); } if (authorizationRuleName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "authorizationRuleName"); } if (parameters == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "parameters"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("namespaceName", namespaceName); tracingParameters.Add("authorizationRuleName", authorizationRuleName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "RegenerateKeys", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}/regenerateKeys").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName)); _url = _url.Replace("{authorizationRuleName}", System.Uri.EscapeDataString(authorizationRuleName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<ResourceListKeys>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ResourceListKeys>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists the available namespaces within a resourceGroup. /// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" /> /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NamespaceResource>>> ListNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (nextPageLink == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NamespaceResource>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<NamespaceResource>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists all the available namespaces within the subscription irrespective of /// the resourceGroups. /// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" /> /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NamespaceResource>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (nextPageLink == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListAllNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NamespaceResource>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<NamespaceResource>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets the authorization rules for a namespace. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<SharedAccessAuthorizationRuleResource>>> ListAuthorizationRulesNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (nextPageLink == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListAuthorizationRulesNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<SharedAccessAuthorizationRuleResource>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SharedAccessAuthorizationRuleResource>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
52.042403
538
0.590434
[ "MIT" ]
samtoubia/azure-sdk-for-net
src/ResourceManagement/NotificationHubs/Microsoft.Azure.Management.NotificationHubs/Generated/NamespacesOperations.cs
162,008
C#
/* * Copyright (c) 2016, Will Strohl * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name of Will Strohl, nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; namespace WillStrohl.Modules.CodeCamp.Components { public class Globals { public const string LOCALIZATION_FILE_PATH = "/DesktopModules/CodeCamp/App_LocalResources/SharedResources.resx"; public const string VIEW_PATH = "Views/"; public const string VIEW_EXTENSION = ".ascx"; public const string SETTINGS_VIEW = "View"; public const string SETTINGS_BOOTSTRAP = "Bootstrap"; public const string SETTINGS_USECDN = "UseCdn"; public const string VIEW_SETTINGS = "SettingsView"; public const string VIEW_CODECAMP = "CodeCampView"; public const string RESPONSE_SUCCESS = "Success"; public const string RESPONSE_FAILURE = "Failure"; public const string TASKSTATE_OPEN = "open"; public const string TASKSTATE_CLOSED = "closed"; public const string TASKSTATE_OVERDUE = "overdue"; public const string SPACE = " "; public const string SPEAKER_AVATAR_FOLDER_PATH_FORMAT = "CodeCamps/{0}/SpeakerAvatars/"; public const string SPEAKER_AVATAR_FILENAME_FORMAT = "avatar-{0}-{1}.{2}"; public const string SPEAKER_AVATAR_FILENAME_STAMP_FORMAT = "yyyyMMdd-hhmmss"; public const string SPEAKER_AVATAR_FILEEXTENSION = "png"; public const string SPEAKER_ICON_FILE_PATH = "Portals/{0}/{1}"; public static DateTime NULL_DATE => DateTime.Parse("1/1/1753 12:00:00 AM"); } }
45.590909
120
0.731805
[ "MIT" ]
hismightiness/dnnextensions
Modules/CodeCamp/Components/Globals.cs
3,011
C#
namespace Eir.Common.Common { public enum TimeSpanSerializedUnit { Milliseconds, Seconds, Minutes, Hours, Days } }
15.181818
38
0.54491
[ "CC0-1.0" ]
BjarniPeturFridjonsson/Qlik-SupportTools
Code/Eir.Common/Eir.Common/Common/TimeSpanSerializedUnit.cs
169
C#
using System.Collections; using System.Collections.ObjectModel; using System.Windows.Controls; using System.Windows.Data; namespace SuperShell.Infrastructure.Commands.Menu { public class SortedMenuItemCollection : ObservableCollection<IMenuItem> { public SortedMenuItemCollection() { var collectionView = (ListCollectionView)CollectionViewSource.GetDefaultView(this); collectionView.CustomSort = new MenuItemSorter(); } internal class MenuItemSorter : IComparer { #region Implementation of IComparer /// <summary> /// Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other. /// </summary> /// <returns> /// A signed integer that indicates the relative values of <paramref name="x"/> and <paramref name="y"/>, as shown in the following table. /// Value Meaning Less than zero <paramref name="x"/> is less than <paramref name="y"/>. /// Zero <paramref name="x"/> equals <paramref name="y"/>. /// Greater than zero <paramref name="x"/> is greater than <paramref name="y"/>. /// </returns> /// <param name="x">The first object to compare. </param> /// <param name="y">The second object to compare. </param> /// <exception cref="T:System.ArgumentException"> /// Neither <paramref name="x"/> nor <paramref name="y"/> implements the <see cref="T:System.IComparable"/> interface. /// -or- <paramref name="x"/> and <paramref name="y"/> are of different types and neither one can handle comparisons with the other. /// </exception> /// <filterpriority>2</filterpriority> public int Compare(object x, object y) { var menuItemOne = (IMenuItem) x; var menuItemTwo = (IMenuItem) y; //now need to get metadata var metadataOne = MenuUtils.GetMenuItemMetadata(menuItemOne); var metadataTwo = MenuUtils.GetMenuItemMetadata(menuItemTwo); // level major if (metadataOne.OrderMajor < metadataTwo.OrderMajor) return -1; if (metadataOne.OrderMajor > metadataTwo.OrderMajor) return 1; // level minor if (metadataOne.OrderMinor < metadataTwo.OrderMinor) return -1; if (metadataOne.OrderMinor > metadataTwo.OrderMinor) return 1; // TODO: do more comparisons if more fields added return 0; } #endregion } } }
33.970588
141
0.695238
[ "MIT" ]
kosmakoff/SuperShell
SuperShell.Infrastructure/Commands/Menu/SortedMenuItemCollection.cs
2,312
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; using KtaneStuff.Modeling; using RT.KitchenSink; using RT.Util.Consoles; using RT.Util.ExtensionMethods; namespace KtaneStuff { using static Md; static class Quilting { public static void MakeModels() { foreach (var svgFile in new DirectoryInfo(@"D:\c\KTANE\Quilting\DataFiles").EnumerateFiles("*.svg")) { var doc = XDocument.Parse(File.ReadAllText(svgFile.FullName)); var paths = doc.Root.ElementsI("path").ToArray(); if (paths.Length != 20) System.Diagnostics.Debugger.Break(); for (var pathIx = 0; pathIx < paths.Length; pathIx++) { var path = paths[pathIx]; var data = path.AttributeI("d").Value; ConsoleUtil.WriteLine($"{svgFile.FullName.Color(ConsoleColor.Cyan)} — {path.AttributeI("id").Value.Color(ConsoleColor.Yellow)}", null); //Utils.ReplaceInFile(@"D:\temp\temp.svg", "<!--#-->", "<!--##-->", $@"<path fill='none' stroke='black' stroke-width='2' d='{data}'/>"); //Utils.ReplaceInFile(@"D:\temp\temp.svg", "<!--%-->", "<!--%%-->", $@"<path fill='none' stroke='red' stroke-width='1' d='{DecodeSvgPath.Do(data, .1).Select(pol => $"M{pol.Select(p => $"{p.X} {p.Y}").JoinString(" ")}").JoinString()}z'/>"); File.WriteAllText($@"D:\c\KTANE\Quilting\Assets\Models\Patches\{Path.GetFileNameWithoutExtension(svgFile.Name)}-{pathIx}.obj", GenerateObjFile(center(DecodeSvgPath.DecodePieces(data).Extrude(1, .1, true)))); } } } private static IEnumerable<VertexInfo[]> center(IEnumerable<VertexInfo[]> source) { var input = source.ToArray(); var minX = input.Min(ps => ps.Min(p => p.Location.X)); var maxX = input.Max(ps => ps.Max(p => p.Location.X)); var minZ = input.Min(ps => ps.Min(p => p.Location.Z)); var maxZ = input.Max(ps => ps.Max(p => p.Location.Z)); return input.Select(ps => ps.Select(p => p.Move(x: -(minX + maxX) / 2, z: -(minZ + maxZ) / 2)).ToArray()).ToArray(); } } }
47.040816
259
0.560087
[ "MIT" ]
Timwi/KtaneStuff
Src/Quilting.cs
2,309
C#
using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.Extensibility; namespace Altinn.Platform.Telemetry { /// <summary> /// Set up custom telemetry for Application Insights /// </summary> public class CustomTelemetryInitializer : ITelemetryInitializer { /// <summary> /// Custom TelemetryInitializer that sets some specific values for the component /// </summary> public void Initialize(ITelemetry telemetry) { if (string.IsNullOrEmpty(telemetry.Context.Cloud.RoleName)) { telemetry.Context.Cloud.RoleName = "platform-events"; } } } }
29.913043
88
0.646802
[ "BSD-3-Clause" ]
Altinn/altinn-studio
src/Altinn.Platform/Altinn.Platform.Events/Events/Configuration/CustomTelemetryInitializer.cs
688
C#
using UnityEngine; using UnityEditor; using System.Collections.Generic; namespace Cinemachine.Editor { [CustomEditor(typeof(CinemachineOrbitalTransposer))] internal class CinemachineOrbitalTransposerEditor : BaseEditor<CinemachineOrbitalTransposer> { protected override void GetExcludedPropertiesInInspector(List<string> excluded) { base.GetExcludedPropertiesInInspector(excluded); if (Target.m_HeadingIsSlave) { excluded.Add(FieldPath(x => x.m_FollowOffset)); excluded.Add(FieldPath(x => x.m_BindingMode)); excluded.Add(FieldPath(x => x.m_Heading)); excluded.Add(FieldPath(x => x.m_XAxis)); excluded.Add(FieldPath(x => x.m_RecenterToTargetHeading)); } if (Target.HideOffsetInInspector) excluded.Add(FieldPath(x => x.m_FollowOffset)); switch (Target.m_BindingMode) { default: case CinemachineTransposer.BindingMode.LockToTarget: if (Target.m_AngularDampingMode == CinemachineTransposer.AngularDampingMode.Euler) excluded.Add(FieldPath(x => x.m_AngularDamping)); else { excluded.Add(FieldPath(x => x.m_PitchDamping)); excluded.Add(FieldPath(x => x.m_YawDamping)); excluded.Add(FieldPath(x => x.m_RollDamping)); } break; case CinemachineTransposer.BindingMode.LockToTargetNoRoll: excluded.Add(FieldPath(x => x.m_RollDamping)); excluded.Add(FieldPath(x => x.m_AngularDamping)); excluded.Add(FieldPath(x => x.m_AngularDampingMode)); break; case CinemachineTransposer.BindingMode.LockToTargetWithWorldUp: excluded.Add(FieldPath(x => x.m_PitchDamping)); excluded.Add(FieldPath(x => x.m_RollDamping)); excluded.Add(FieldPath(x => x.m_AngularDamping)); excluded.Add(FieldPath(x => x.m_AngularDampingMode)); break; case CinemachineTransposer.BindingMode.LockToTargetOnAssign: case CinemachineTransposer.BindingMode.WorldSpace: excluded.Add(FieldPath(x => x.m_PitchDamping)); excluded.Add(FieldPath(x => x.m_YawDamping)); excluded.Add(FieldPath(x => x.m_RollDamping)); excluded.Add(FieldPath(x => x.m_AngularDamping)); excluded.Add(FieldPath(x => x.m_AngularDampingMode)); break; case CinemachineTransposer.BindingMode.SimpleFollowWithWorldUp: excluded.Add(FieldPath(x => x.m_XDamping)); excluded.Add(FieldPath(x => x.m_PitchDamping)); excluded.Add(FieldPath(x => x.m_YawDamping)); excluded.Add(FieldPath(x => x.m_RollDamping)); excluded.Add(FieldPath(x => x.m_AngularDamping)); excluded.Add(FieldPath(x => x.m_AngularDampingMode)); excluded.Add(FieldPath(x => x.m_Heading)); excluded.Add(FieldPath(x => x.m_RecenterToTargetHeading)); break; } } private void OnEnable() { Target.UpdateInputAxisProvider(); } public override void OnInspectorGUI() { BeginInspector(); if (Target.FollowTarget == null) EditorGUILayout.HelpBox( "Orbital Transposer requires a Follow target.", MessageType.Warning); Target.m_XAxis.ValueRangeLocked = (Target.m_BindingMode == CinemachineTransposer.BindingMode.SimpleFollowWithWorldUp); DrawRemainingPropertiesInInspector(); } /// Process a position drag from the user. /// Called "magically" by the vcam editor, so don't change the signature. private void OnVcamPositionDragged(Vector3 delta) { Undo.RegisterCompleteObjectUndo(Target, "Camera drag"); // GML do we need this? Quaternion targetOrientation = Target.GetReferenceOrientation(Target.VcamState.ReferenceUp); targetOrientation = targetOrientation * Quaternion.Euler(0, Target.m_Heading.m_Bias, 0); Vector3 localOffset = Quaternion.Inverse(targetOrientation) * delta; localOffset.x = 0; FindProperty(x => x.m_FollowOffset).vector3Value += localOffset; serializedObject.ApplyModifiedProperties(); FindProperty(x => x.m_FollowOffset).vector3Value = Target.EffectiveOffset; serializedObject.ApplyModifiedProperties(); } [DrawGizmo(GizmoType.Active | GizmoType.Selected, typeof(CinemachineOrbitalTransposer))] static void DrawTransposerGizmos(CinemachineOrbitalTransposer target, GizmoType selectionType) { if (target.IsValid && !target.HideOffsetInInspector) { Color originalGizmoColour = Gizmos.color; Gizmos.color = CinemachineCore.Instance.IsLive(target.VirtualCamera) ? CinemachineSettings.CinemachineCoreSettings.ActiveGizmoColour : CinemachineSettings.CinemachineCoreSettings.InactiveGizmoColour; Vector3 up = target.VirtualCamera.State.ReferenceUp; Vector3 pos = target.FollowTargetPosition; Quaternion orient = target.GetReferenceOrientation(up); up = orient * Vector3.up; DrawCircleAtPointWithRadius (pos + up * target.m_FollowOffset.y, orient, target.m_FollowOffset.z); Gizmos.color = originalGizmoColour; } } public static void DrawCircleAtPointWithRadius(Vector3 point, Quaternion orient, float radius) { Matrix4x4 prevMatrix = Gizmos.matrix; Gizmos.matrix = Matrix4x4.TRS(point, orient, radius * Vector3.one); const int kNumPoints = 25; Vector3 currPoint = Vector3.forward; Quaternion rot = Quaternion.AngleAxis(360f / (float)kNumPoints, Vector3.up); for (int i = 0; i < kNumPoints + 1; ++i) { Vector3 nextPoint = rot * currPoint; Gizmos.DrawLine(currPoint, nextPoint); currPoint = nextPoint; } Gizmos.matrix = prevMatrix; } } }
47.58156
104
0.588314
[ "MIT" ]
Dan-Rosen/unity-MadBirds
Library/PackageCache/com.unity.cinemachine@2.6.0/Editor/Editors/CinemachineOrbitalTransposerEditor.cs
6,709
C#
using System; using UnityEngine; namespace FancyScrollView.Example04 { public class Context { public int SelectedIndex = -1; // Cell -> ScrollView public Action<int> OnCellClicked; // ScrollView -> Cell public Action UpdateCellState; // xy = cell position, z = data index, w = scale public Vector4[] CellState = new Vector4[1]; public void SetCellState(int cellIndex, int dataIndex, float x, float y, float scale) { var size = cellIndex + 1; ResizeIfNeeded(ref CellState, size); CellState[cellIndex].x = x; CellState[cellIndex].y = y; CellState[cellIndex].z = dataIndex; CellState[cellIndex].w = scale; } void ResizeIfNeeded<T>(ref T[] array, int size) { if (size <= array.Length) { return; } var tmp = array; array = new T[size]; Array.Copy(tmp, array, tmp.Length); } } }
24.604651
93
0.531191
[ "MIT" ]
coposuke/FancyScrollView
Assets/FancyScrollView/Examples/Sources/04_Metaball/Context.cs
1,060
C#
using System; using JetBrains.Annotations; using TypedRest; namespace MyVendor.MyService.Contacts { /// <summary> /// Represents a REST endpoint for a single <see cref="Contact"/>. /// </summary> [UsedImplicitly] public class ContactElementEndpoint : ElementEndpoint<Contact>, IContactElementEndpoint { public ContactElementEndpoint(IEndpoint referrer, Uri relativeUri) : base(referrer, relativeUri.EnsureTrailingSlash()) {} /// <summary> /// An optional note on the contact. /// </summary> public IElementEndpoint<Note> Note => new ElementEndpoint<Note>(this, relativeUri: "note"); /// <summary> /// A action for poking the contact. /// </summary> public IActionEndpoint Poke => new ActionEndpoint(this, relativeUri: "poke"); } }
31.464286
100
0.624291
[ "MIT" ]
renovate-tests/Templates.WebService
content/src/Client/Contacts/ContactElementEndpoint.cs
881
C#
using System; using System.Linq.Expressions; using System.Reflection; using Our.ModelsBuilder; using Umbraco.Core.Models.PublishedContent; // ReSharper disable once CheckNamespace, reason: extension methods namespace Umbraco.Web { /// <summary> /// Provides extension methods to models. /// </summary> public static class OurModelsBuilderPublishedElementExtensions // ensure name does not conflicts with Core's class { /// <summary> /// Gets the value of a property. /// </summary> /// <typeparam name="TModel">The type of the content model.</typeparam> /// <typeparam name="TValue">The type of the property value.</typeparam> /// <param name="model">The content model.</param> /// <param name="alias">The alias of the property.</param> /// <param name="culture">An optional culture.</param> /// <param name="segment">An optional segment.</param> /// <param name="fallback">A fallback method.</param> /// <returns>A value for the property.</returns> public static TValue Value<TModel, TValue>(this TModel model, string alias, string culture = null, string segment = null, Func<FallbackInfos<TModel, TValue>, TValue> fallback = null) where TModel : IPublishedElement { var property = model.GetProperty(alias); // if we have a property, and it has a value, return that value if (property != null && property.HasValue(culture, segment)) return property.Value<TValue>(culture, segment); // else use the fallback method, if any if (fallback != default) return fallback(new FallbackInfos<TModel, TValue>(model, alias, culture, segment)); // else... if we have a property, at least let the converter return its own // vision of 'no value' (could be an empty enumerable) - otherwise, default return property == null ? default : property.Value<TValue>(culture, segment); } // note: the method below used to be provided by Core, but then when they embedded MB, they ran into // collision, and their "fix" consisted in renaming the method "ValueFor" - so we can provide it here. // see: https://github.com/umbraco/Umbraco-CMS/issues/7469 /// <summary> /// Gets the value of a property. /// </summary> /// <typeparam name="TModel">The type of the model.</typeparam> /// <typeparam name="TValue">The type of the property.</typeparam> /// <param name="model">The model.</param> /// <param name="property">An expression selecting the property.</param> /// <param name="culture">An optional culture.</param> /// <param name="segment">An optional segment.</param> /// <param name="fallback">An optional fallback.</param> /// /// <param name="defaultValue">An optional default value.</param> /// <returns>The value of the property.</returns> public static TValue Value<TModel, TValue>(this TModel model, Expression<Func<TModel, TValue>> property, string culture = null, string segment = null, Fallback fallback = default, TValue defaultValue = default) where TModel : IPublishedElement { var alias = GetAlias(model, property); return model.Value(alias, culture, segment, fallback, defaultValue); } /// <summary> /// Gets the alias of a property. /// </summary> /// <typeparam name="TModel">The type of the model.</typeparam> /// <typeparam name="TValue">The type of the property.</typeparam> /// <param name="model">The model.</param> /// <param name="property">An expression selecting the property.</param> /// <returns>The alias of the property.</returns> private static string GetAlias<TModel, TValue>(TModel model, Expression<Func<TModel, TValue>> property) { if (property.NodeType != ExpressionType.Lambda) throw new ArgumentException("Not a proper lambda expression (lambda).", nameof(property)); var lambda = (LambdaExpression) property; var lambdaBody = lambda.Body; if (lambdaBody.NodeType != ExpressionType.MemberAccess) throw new ArgumentException("Not a proper lambda expression (body).", nameof(property)); var memberExpression = (MemberExpression)lambdaBody; if (memberExpression.Expression.NodeType != ExpressionType.Parameter) throw new ArgumentException("Not a proper lambda expression (member).", nameof(property)); var member = memberExpression.Member; var attribute = member.GetCustomAttribute<ImplementPropertyTypeAttribute>(); if (attribute == null) throw new InvalidOperationException("Property is not marked with ImplementPropertyType attribute."); return attribute.PropertyTypeAlias; } } }
50.39
218
0.637031
[ "MIT" ]
Arlanet/ModelsBuilder.Original
src/Our.ModelsBuilder/UmbracoExtensions/PublishedElementExtensions.cs
5,041
C#
namespace AlunosApi.Services { public interface IAuthenticate { Task<bool> Authenticate(string email, string password); Task<bool> RegisterUser(string email, string password); Task Logout(); } }
21.818182
63
0.641667
[ "MIT" ]
Raphael-Azevedo/WebApiComReact
AlunosApi/Services/IAuthenticate.cs
242
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/wingdi.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System.Runtime.InteropServices; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="PSINJECTDATA" /> struct.</summary> public static unsafe class PSINJECTDATATests { /// <summary>Validates that the <see cref="PSINJECTDATA" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<PSINJECTDATA>(), Is.EqualTo(sizeof(PSINJECTDATA))); } /// <summary>Validates that the <see cref="PSINJECTDATA" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(PSINJECTDATA).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="PSINJECTDATA" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(PSINJECTDATA), Is.EqualTo(8)); } } }
37.277778
145
0.659463
[ "MIT" ]
Ethereal77/terrafx.interop.windows
tests/Interop/Windows/um/wingdi/PSINJECTDATATests.cs
1,344
C#
using System.Collections.ObjectModel; using System.Linq; using Core; using Core.Model; using Core.ViewModel; using Core.Events; using System.Collections.Generic; namespace Agent.ViewModel { class AlertsEngine : GenericSimpleEngine<AlertViewModel, Alert> { readonly IItemStore itemStore; public AlertsEngine(FiltersEvent filtersEvent, IItemStore itemStore) : base(filtersEvent) { this.itemStore = itemStore; } protected override void Subscribe(GameModel model) { model.AlertNotificationArrived += AddEvent; model.AlertNotificationDeparted += RemoveEvent; } protected override IEnumerable<Alert> GetItemsFromModel(GameModel model) => model.GetCurrentAlerts(); protected override AlertViewModel CreateItem(Alert alert, FiltersEvent evt) => new AlertViewModel(alert, evt, itemStore); protected override string LogAddedOne(Alert item) => $"Новая тревога {item.Id.Oid}"; protected override string LogRemovedOne(Alert item) => $"Удаляю тревогу {item.Id.Oid}"; protected override string LogAddedMany(int n) => $"Новые тревоги ({n} шт.)"; protected override string LogRemovedMany(int n) => $"Удаляю тревоги ({n} шт.)"; protected override AlertViewModel TryGetItemByModel(Alert item) => Items.FirstOrDefault(i => i.Id == item.Id); } }
35.74359
129
0.697274
[ "MIT" ]
arrer/WarframeAgent
Agent/Agent/ViewModel/AlertsEngine.cs
1,450
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Sql.FirewallRule.Model; using System.Collections.Generic; using System.Management.Automation; namespace Microsoft.Azure.Commands.Sql.FirewallRule.Cmdlet { /// <summary> /// Defines the Get-AzureRmSqlServerFirewallRule cmdlet /// </summary> [Cmdlet(VerbsCommon.Get, "AzureRmSqlServerFirewallRule", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.None)] public class GetAzureSqlServerFirewallRule : AzureSqlServerFirewallRuleCmdletBase { /// <summary> /// Gets or sets the name of the Azure Sql Database Server Firewall Rule /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, Position = 2, HelpMessage = "The Azure Sql Database Server Firewall Rule name.")] [ValidateNotNullOrEmpty] public string FirewallRuleName { get; set; } /// <summary> /// Gets a Firewall Rule from the service. /// </summary> /// <returns>A single Firewall Rule</returns> protected override IEnumerable<AzureSqlServerFirewallRuleModel> GetEntity() { ICollection<AzureSqlServerFirewallRuleModel> results = null; if (this.MyInvocation.BoundParameters.ContainsKey("FirewallRuleName")) { results = new List<AzureSqlServerFirewallRuleModel>(); results.Add(ModelAdapter.GetFirewallRule(this.ResourceGroupName, this.ServerName, this.FirewallRuleName)); } else { results = ModelAdapter.ListFirewallRules(this.ResourceGroupName, this.ServerName); } return results; } /// <summary> /// No changes, thus nothing to persist. /// </summary> /// <param name="entity">The entity retrieved</param> /// <returns>The unchanged entity</returns> protected override IEnumerable<AzureSqlServerFirewallRuleModel> PersistChanges(IEnumerable<AzureSqlServerFirewallRuleModel> entity) { return entity; } /// <summary> /// No user input to apply to model. /// </summary> /// <param name="model">The model to modify</param> /// <returns>The input model</returns> protected override IEnumerable<AzureSqlServerFirewallRuleModel> ApplyUserInputToModel(IEnumerable<AzureSqlServerFirewallRuleModel> model) { return model; } } }
42.379747
146
0.614695
[ "MIT" ]
LaudateCorpus1/azure-powershell
src/ResourceManager/Sql/Commands.Sql/FirewallRule/Cmdlet/GetAzureSqlServerFirewallRule.cs
3,272
C#
using Qsi.Analyzers; using Qsi.Data; namespace Qsi.SqlServer.Data { public class SqlServerAlterUserAction : IQsiAnalysisResult { public QsiIdentifier TargetUser { get; set; } public QsiIdentifier DefaultSchema { get; set; } public QsiIdentifier NewUserName { get; set; } } }
21
62
0.685714
[ "MIT" ]
ScriptBox99/chequer-qsi
Qsi.SqlServer/Data/SqlServerAlterUserAction.cs
317
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Network.Outputs { [OutputType] public sealed class AadAuthenticationParametersResponse { /// <summary> /// AAD Vpn authentication parameter AAD audience. /// </summary> public readonly string? AadAudience; /// <summary> /// AAD Vpn authentication parameter AAD issuer. /// </summary> public readonly string? AadIssuer; /// <summary> /// AAD Vpn authentication parameter AAD tenant. /// </summary> public readonly string? AadTenant; [OutputConstructor] private AadAuthenticationParametersResponse( string? aadAudience, string? aadIssuer, string? aadTenant) { AadAudience = aadAudience; AadIssuer = aadIssuer; AadTenant = aadTenant; } } }
27.55814
81
0.622785
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/Network/Outputs/AadAuthenticationParametersResponse.cs
1,185
C#
using Newtonsoft.Json.Linq; namespace Xky.Core.Model { public class Response { public bool Result { get; set; } public string Message { get; set; } public JObject Json { get; set; } } }
20.272727
43
0.596413
[ "Apache-2.0" ]
loveyeguo/xky
Xky.Core/Model/Response.cs
225
C#
using System.Collections.Generic; using System.Threading.Tasks; namespace TwitchLib.Internal.TwitchAPI { public static class Undocumented { #region GetClipChat public async static Task<Models.API.Undocumented.ClipChat.GetClipChatResponse> GetClipChat(string slug) { var clip = await v5.GetClip(slug); if (clip == null) return null; string vodId = $"v{clip.VOD.Id}"; string offsetTime = clip.VOD.Url.Split('=')[1]; long offsetSeconds = 2; // for some reason, VODs have 2 seconds behind where clips start if (offsetTime.Contains("h")) { offsetSeconds += int.Parse(offsetTime.Split('h')[0]) * 60 * 60; offsetTime = offsetTime.Replace(offsetTime.Split('h')[0] + "h", ""); } if (offsetTime.Contains("m")) { offsetSeconds += int.Parse(offsetTime.Split('m')[0]) * 60; offsetTime = offsetTime.Replace(offsetTime.Split('m')[0] + "m", ""); } if (offsetTime.Contains("s")) offsetSeconds += int.Parse(offsetTime.Split('s')[0]); var rechatResource = $"https://rechat.twitch.tv/rechat-messages?video_id={vodId}&offset_seconds={offsetSeconds}"; return await Requests.GetGeneric<Models.API.Undocumented.ClipChat.GetClipChatResponse>(rechatResource); } #endregion #region GetTwitchPrimeOffers public async static Task<Models.API.Undocumented.TwitchPrimeOffers.TwitchPrimeOffers> GetTwitchPrimeOffers() { return await Requests.GetGeneric<Models.API.Undocumented.TwitchPrimeOffers.TwitchPrimeOffers>($"https://api.twitch.tv/api/premium/offers?on_site=1"); } #endregion #region GetChannelHosts public async static Task<Models.API.Undocumented.Hosting.ChannelHostsResponse> GetChannelHosts(string channelId) { return await Requests.GetSimpleGeneric<Models.API.Undocumented.Hosting.ChannelHostsResponse>($"https://tmi.twitch.tv/hosts?include_logins=1&target={channelId}"); } #endregion #region GetChatProperties public async static Task<Models.API.Undocumented.ChatProperties.ChatProperties> GetChatProperties(string channelName) { return await Requests.GetGeneric<Models.API.Undocumented.ChatProperties.ChatProperties>($"https://api.twitch.tv/api/channels/{channelName}/chat_properties"); } #endregion #region GetChannelPanels public async static Task<Models.API.Undocumented.ChannelPanels.Panel[]> GetChannelPanels(string channelName) { return await Requests.GetGeneric<Models.API.Undocumented.ChannelPanels.Panel[]>($"https://api.twitch.tv/api/channels/{channelName}/panels"); } #endregion #region GetCSMaps public async static Task<Models.API.Undocumented.CSMaps.CSMapsResponse> GetCSMaps() { return await Requests.GetGeneric<Models.API.Undocumented.CSMaps.CSMapsResponse>("https://api.twitch.tv/api/cs/maps"); } #endregion #region GetCSStreams public async static Task<Models.API.Undocumented.CSStreams.CSStreams> GetCSStreams(int limit = 25, int offset = 0) { string paramsStr = $"?limit={limit}&offset={offset}"; return await Requests.GetGeneric<Models.API.Undocumented.CSStreams.CSStreams>($"https://api.twitch.tv/api/cs{paramsStr}"); } #endregion #region GetRecentMessages public async static Task<Models.API.Undocumented.RecentMessages.RecentMessagesResponse> GetRecentMessages(string channelId) { return await Requests.GetGeneric<Models.API.Undocumented.RecentMessages.RecentMessagesResponse>($"https://tmi.twitch.tv/api/rooms/{channelId}/recent_messages"); } #endregion #region GetChatters public async static Task<List<Models.API.Undocumented.Chatters.ChatterFormatted>> GetChatters(string channelName) { var resp = await Requests.GetGeneric<Models.API.Undocumented.Chatters.ChattersResponse>($"https://tmi.twitch.tv/group/user/{channelName}/chatters"); List<Models.API.Undocumented.Chatters.ChatterFormatted> chatters = new List<Models.API.Undocumented.Chatters.ChatterFormatted>(); foreach (var chatter in resp.Chatters.Staff) chatters.Add(new Models.API.Undocumented.Chatters.ChatterFormatted(chatter, Enums.UserType.Staff)); foreach (var chatter in resp.Chatters.Admins) chatters.Add(new Models.API.Undocumented.Chatters.ChatterFormatted(chatter, Enums.UserType.Admin)); foreach (var chatter in resp.Chatters.GlobalMods) chatters.Add(new Models.API.Undocumented.Chatters.ChatterFormatted(chatter, Enums.UserType.GlobalModerator)); foreach (var chatter in resp.Chatters.Moderators) chatters.Add(new Models.API.Undocumented.Chatters.ChatterFormatted(chatter, Enums.UserType.Moderator)); foreach (var chatter in resp.Chatters.Viewers) chatters.Add(new Models.API.Undocumented.Chatters.ChatterFormatted(chatter, Enums.UserType.Viewer)); return chatters; } #endregion #region GetRecentChannelEvents public async static Task<Models.API.Undocumented.RecentEvents.RecentEvents> GetRecentChannelEvents(string channelId) { return await Requests.GetGeneric<Models.API.Undocumented.RecentEvents.RecentEvents>($"https://api.twitch.tv/bits/channels/{channelId}/events/recent"); } #endregion } }
53.194444
173
0.670496
[ "MIT" ]
NoStudioDude/TwitchLib-1
TwitchLib/Internal/TwitchAPI/Undocumented.cs
5,747
C#
using Bloom.Data.Interfaces; namespace Bloom.Data.Tables { /// <summary> /// Represents the artist_member_role table. /// </summary> /// <seealso cref="Bloom.Data.Interfaces.ISqlTable" /> public class ArtistMemberRoleTable : ISqlTable { /// <summary> /// Gets the create artist_member_role table SQL. /// </summary> public string CreateSql => "CREATE TABLE artist_member_role (" + "artist_member_id BLOB NOT NULL , " + "role_id BLOB NOT NULL , " + "PRIMARY KEY (artist_member_id, role_id) , " + "FOREIGN KEY (artist_member_id) REFERENCES artist_member(id) , " + "FOREIGN KEY (role_id) REFERENCES role(id) )"; } }
40.428571
101
0.52179
[ "Apache-2.0" ]
RobDixonIII/Bloom
Shared/Bloom.Data/Tables/ArtistMemberRoleTable.cs
851
C#
/* * Nz.Framework * Author Paulo Eduardo Nazeazeno * https://github.com/paulonz/Nz.Framework */ namespace Nz.Libs.Encryption.Impl.HashAlgorithm { using System; using System.Security.Cryptography; using System.Text; using Microsoft.Extensions.Logging; using Nz.Common.GeneralSettings; /// <summary> /// Implementação da criptografia /// </summary> public class Encryption : IEncryption { /// <summary> /// Logger /// </summary> private readonly ILogger _logger; /// <summary> /// Configurações de segurança /// </summary> private readonly IEncryptionSettings _security; /// <summary> /// Configurações gerais /// </summary> private readonly IGeneralSettings _general; /// <summary> /// Construtor padrão /// </summary> /// <param name="security">Configurações de segurança</param> /// <param name="general">Configurações gerais</param> /// <param name="logger">Logger</param> public Encryption( IEncryptionSettings security, IGeneralSettings general, ILogger<Encryption> logger) { _security = security; _general = general; _logger = logger; } /// <summary> /// Faz a criptografia de uma string /// </summary> /// <param name="value">Valor para ser criptografado</param> /// <returns>Valor criptografado</returns> public string Encrypt( string value) { try { HashAlgorithm hashAlgorithm = _security.HashAlgorithm; byte[] encodedValue = _general.DefaultEncoding.GetBytes(value); byte[] encryptedPassword = hashAlgorithm.ComputeHash(encodedValue); StringBuilder stringBuilder = new StringBuilder(); foreach (byte character in encryptedPassword) { stringBuilder.Append(character.ToString("X2")); } return stringBuilder.ToString(); } catch (Exception ex) { _logger.LogError(ex, ex.Message); } return null; } } }
28.060241
83
0.55131
[ "Apache-2.0" ]
paulonz/Nz.Framework
Src/Libs/Encryption/Nz.Libs.Encryption.Impl.HashAlgorithm/Encryption.cs
2,344
C#
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Orleans; using Piraeus.Auditing; using Piraeus.Configuration; using Piraeus.Core; using Piraeus.Core.Logging; using Piraeus.Grains; using SkunkLab.Channels; using SkunkLab.Channels.Udp; using SkunkLab.Protocols.Coap; using SkunkLab.Protocols.Coap.Handlers; using SkunkLab.Security.Authentication; using SkunkLab.Security.Identity; namespace Piraeus.Adapters { public class CoapProtocolAdapter : ProtocolAdapter { private readonly PiraeusConfig config; private readonly HttpContext context; private readonly GraphManager graphManager; private readonly ILog logger; private readonly CoapSession session; private IAuditFactory auditFactory; private bool closing; private ICoapRequestDispatch dispatcher; private bool disposed; private bool forcePerReceiveAuthn; private IAuditor userAuditor; public CoapProtocolAdapter(PiraeusConfig config, GraphManager graphManager, IAuthenticator authenticator, IChannel channel, ILog logger, HttpContext context = null) { this.context = context; this.graphManager = graphManager; this.logger = logger; this.config = config; CoapConfigOptions options = config.ObserveOption && config.NoResponseOption ? CoapConfigOptions.Observe | CoapConfigOptions.NoResponse : config.ObserveOption ? CoapConfigOptions.Observe : config.NoResponseOption ? CoapConfigOptions.NoResponse : CoapConfigOptions.None; CoapConfig coapConfig = new CoapConfig(authenticator, config.CoapAuthority, options, config.AutoRetry, config.KeepAliveSeconds, config.AckTimeoutSeconds, config.AckRandomFactor, config.MaxRetransmit, config.NStart, config.DefaultLeisure, config.ProbingRate, config.MaxLatencySeconds) { IdentityClaimType = config.ClientIdentityNameClaimType, Indexes = config.GetClientIndexes() }; InitializeAuditor(config); logger?.LogDebugAsync("CoAP protocol auditor initialized.").GetAwaiter(); Channel = channel; Channel.OnClose += Channel_OnClose; Channel.OnError += Channel_OnError; Channel.OnOpen += Channel_OnOpen; Channel.OnReceive += Channel_OnReceive; Channel.OnStateChange += Channel_OnStateChange; session = new CoapSession(coapConfig, context); logger?.LogDebugAsync("CoAP protocol session open.").GetAwaiter(); if (Channel.State != ChannelState.Open) { Channel.OpenAsync().GetAwaiter(); Channel.ReceiveAsync(); logger?.LogDebugAsync("CoAP protocol channel opened and receiving.").GetAwaiter(); } } #region init public override void Init() { forcePerReceiveAuthn = Channel as UdpChannel != null; Channel.OpenAsync().GetAwaiter(); logger?.LogDebugAsync($"CoAP adapter on channel '{Channel.Id}' is initialized.").GetAwaiter(); } #endregion init private void InitializeAuditor(PiraeusConfig config) { auditFactory = AuditFactory.CreateSingleton(); if (config.AuditConnectionString != null && config.AuditConnectionString.Contains("DefaultEndpointsProtocol")) { auditFactory.Add(new AzureTableAuditor(config.AuditConnectionString, "messageaudit"), AuditType.Message); auditFactory.Add(new AzureTableAuditor(config.AuditConnectionString, "useraudit"), AuditType.User); } else if (config.AuditConnectionString != null) { auditFactory.Add(new FileAuditor(config.AuditConnectionString), AuditType.Message); auditFactory.Add(new FileAuditor(config.AuditConnectionString), AuditType.User); } userAuditor = auditFactory.GetAuditor(AuditType.User); } #region public members public override event System.EventHandler<ProtocolAdapterCloseEventArgs> OnClose; public override event System.EventHandler<ProtocolAdapterErrorEventArgs> OnError; public override event System.EventHandler<ChannelObserverEventArgs> OnObserve; public override IChannel Channel { get; set; } #endregion public members #region events private void Channel_OnClose(object sender, ChannelCloseEventArgs e) { if (!closing) { closing = true; logger?.LogWarningAsync("CoAP adapter closing channel."); UserAuditRecord record = new UserAuditRecord(Channel.Id, session.Identity, DateTime.UtcNow); userAuditor?.UpdateAuditRecordAsync(record).Ignore(); OnClose?.Invoke(this, new ProtocolAdapterCloseEventArgs(Channel.Id)); } } private void Channel_OnError(object sender, ChannelErrorEventArgs e) { logger?.LogErrorAsync(e.Error, "CoAP adapter error on channel."); OnError?.Invoke(this, new ProtocolAdapterErrorEventArgs(Channel.Id, e.Error)); } private void Channel_OnOpen(object sender, ChannelOpenEventArgs e) { session.IsAuthenticated = Channel.IsAuthenticated; logger?.LogDebugAsync( $"CoAP protocol channel opening with session authenticated '{session.IsAuthenticated}'.").GetAwaiter(); try { if (!Channel.IsAuthenticated && e.Message != null) { CoapMessage msg = CoapMessage.DecodeMessage(e.Message); CoapUri coapUri = new CoapUri(msg.ResourceUri.ToString()); session.IsAuthenticated = session.Authenticate(coapUri.TokenType, coapUri.SecurityToken); logger?.LogDebugAsync( $"CoAP protocol channel opening session authenticated '{session.IsAuthenticated}' by authenticator.") .GetAwaiter(); } if (session.IsAuthenticated) { IdentityDecoder decoder = new IdentityDecoder(session.Config.IdentityClaimType, context, session.Config.Indexes); session.Identity = decoder.Id; session.Indexes = decoder.Indexes; logger?.LogDebugAsync($"CoAP protocol channel opening with session identity '{session.Identity}'.") .GetAwaiter(); UserAuditRecord record = new UserAuditRecord(Channel.Id, session.Identity, session.Config.IdentityClaimType, Channel.TypeId, "COAP", "Granted", DateTime.UtcNow); userAuditor?.WriteAuditRecordAsync(record).Ignore(); } } catch (Exception ex) { logger?.LogErrorAsync(ex, $"CoAP adapter opening channel '{Channel.Id}'.").GetAwaiter(); OnError?.Invoke(this, new ProtocolAdapterErrorEventArgs(Channel.Id, ex)); } if (!session.IsAuthenticated && e.Message != null) { logger?.LogWarningAsync("CoAP adpater closing due to unauthenticated user."); Channel.CloseAsync().Ignore(); } else { dispatcher = new CoapRequestDispatcher(session, Channel, config, graphManager, logger); } } private void Channel_OnReceive(object sender, ChannelReceivedEventArgs e) { try { CoapMessage message = CoapMessage.DecodeMessage(e.Message); if (!session.IsAuthenticated || forcePerReceiveAuthn) { session.EnsureAuthentication(message, forcePerReceiveAuthn); UserAuditRecord record = new UserAuditRecord(Channel.Id, session.Identity, session.Config.IdentityClaimType, Channel.TypeId, "COAP", "Granted", DateTime.UtcNow); userAuditor?.WriteAuditRecordAsync(record).Ignore(); } OnObserve?.Invoke(this, new ChannelObserverEventArgs(Channel.Id, message.ResourceUri.ToString(), MediaTypeConverter.ConvertFromMediaType(message.ContentType), message.Payload)); Task task = Task.Factory.StartNew(async () => { CoapMessageHandler handler = CoapMessageHandler.Create(session, message, dispatcher); CoapMessage msg = await handler.ProcessAsync(); if (msg != null) { byte[] payload = msg.Encode(); await Channel.SendAsync(payload); } }); task.LogExceptions(); } catch (Exception ex) { logger?.LogErrorAsync(ex, $"CoAP adapter receiveing on channel '{Channel.Id}'.").GetAwaiter(); OnError?.Invoke(this, new ProtocolAdapterErrorEventArgs(Channel.Id, ex)); Channel.CloseAsync().Ignore(); } } private void Channel_OnStateChange(object sender, ChannelStateEventArgs e) { logger?.LogDebugAsync($"CoAP adapter channel state changed to {e.State}"); } #endregion events #region dispose public override void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { try { if (dispatcher != null) { dispatcher.Dispose(); logger?.LogDebugAsync($"CoAP adapter disposed dispatcher on channel {Channel.Id}") .GetAwaiter(); } } catch (Exception ex) { logger?.LogErrorAsync(ex, $"CoAP adapter error on channel '{Channel.Id}'.").GetAwaiter(); } try { if (Channel != null) { string channelId = Channel.Id; Channel.Dispose(); logger?.LogDebugAsync($"CoAP adapter channel {channelId} disposed."); } } catch (Exception ex) { logger?.LogErrorAsync(ex, $"CoAP adapter disposing error on channel '{Channel.Id}'.") .GetAwaiter(); } try { if (session != null) { session.Dispose(); logger?.LogDebugAsync("CoAP adapter disposed session."); } } catch (Exception ex) { logger?.LogErrorAsync(ex, $"CoAP adapter Disposing session on channel '{Channel.Id}'.") .GetAwaiter(); } } disposed = true; } } #endregion dispose } }
37.981013
129
0.552325
[ "MIT" ]
lulzzz/piraeus-2
src/Piraeus.Adapters/CoapProtocolAdapter.cs
12,004
C#
using System; using System.Threading.Tasks; using WebSharpJs.NodeJS; using WebSharpJs.Script; namespace WebSharpJs.Electron { public class GlobalShortcut : EventEmitter { protected override string ScriptProxy => @"globalShortcut;"; protected override string Requires => @"const {globalShortcut} = require('electron');"; static GlobalShortcut proxy; public static new async Task<GlobalShortcut> Create() { throw new NotSupportedException("Create() is not valid. Use Instance() to obtain a reference to GlobalShortcut."); } public static async Task<GlobalShortcut> Instance() { if (proxy == null) { proxy = new GlobalShortcut(); await proxy.Initialize(); } return proxy; } protected GlobalShortcut() : base() { } protected GlobalShortcut(object scriptObject) : base(scriptObject) { } public GlobalShortcut(ScriptObjectProxy scriptObject) : base(scriptObject) { } public static explicit operator GlobalShortcut(ScriptObjectProxy sop) { return new GlobalShortcut(sop); } public async Task<bool> Register(Accelerator accelerator, ScriptObjectCallback callback) { return await Invoke<bool>("register", accelerator.ToString(), callback); } public async Task<bool> IsRegistered(Accelerator accelerator) { return await Invoke<bool>("isRegistered", accelerator.ToString()); } public async Task UnRegister(Accelerator accelerator) { await Invoke<object>("unregister", accelerator.ToString()); } public async Task UnRegisterAll() { await Invoke<object>("unregisterAll"); } } }
28.560606
127
0.608488
[ "MIT" ]
xamarin/WebSharp
electron-dotnet/src/websharpjs/WebSharp.js/dotnet/WebSharpJs.Electron/GlobalShortcut.cs
1,887
C#
using LQClass.CustomControls.TabControlHelper; using System.Windows.Controls; using WpfExtensions.Xaml; namespace LQClass.ModuleOfDataPrivilege.Views { /// <summary> /// Interaction logic for ViewA.xaml /// </summary> public partial class MainTabItemView : UserControl, ICloseable { public MainTabItemView() { InitializeComponent(); this.Closer = new CloseableHeader(ModuleOfDataPrivilegeModule.KEY_OF_CURRENT_MODULE , I18nManager.Instance.Get(I18nResources.Language.MainTabItemView_Header).ToString() , true); } public CloseableHeader Closer { get; private set; } } }
26.086957
88
0.768333
[ "MIT" ]
dotnet9/lqclass.com
src/LQClass.AdminForWPF/Modules/LQClass.ModuleOfDataPrivilege/Views/MainTabItemView.xaml.cs
602
C#
using Cosmos.Business.Extensions.Holiday.Core; using Cosmos.I18N.Countries; namespace Cosmos.Business.Extensions.Holiday.Definitions.Africa.ElSalvador.Public { /// <summary> /// August Festivals /// </summary> public class AugustFestivals : BaseFixedHolidayFunc { /// <inheritdoc /> public override Country Country { get; } = Country.ElSalvador; /// <inheritdoc /> public override Country BelongsToCountry { get; } = Country.ElSalvador; /// <inheritdoc /> public override string Name { get; } = "Fiestas de agosto"; /// <inheritdoc /> public override HolidayType HolidayType { get; set; } = HolidayType.Public; /// <inheritdoc /> public override (int Month, int Day)? FromDate { get; set; } = (8, 1); /// <inheritdoc /> public override (int Month, int Day)? ToDate { get; set; } = (8, 7); /// <inheritdoc /> public override string I18NIdentityCode { get; } = "i18n_holiday_sv_august"; } }
32.21875
84
0.615907
[ "Apache-2.0" ]
cosmos-open/Holiday
src/Cosmos.Business.Extensions.Holiday/Cosmos/Business/Extensions/Holiday/Definitions/Africa/ElSalvador/Public/AugustFestivals.cs
1,031
C#
namespace Incoding.UnitTest { #region << Using >> using System; using System.Collections.Generic; using System.Linq; using Incoding.Block; using Incoding.CQRS; using Incoding.MSpecContrib; using Machine.Specifications; #endregion [Subject(typeof(DelayToScheduler.Where.ByStatus))] public class When_delay_to_scheduler_by_status { #region Establish value static IQueryable<DelayToScheduler> fakeCollection; static List<DelayToScheduler> filterCollection; #endregion Establish establish = () => { Func<DelayOfStatus, DelayToScheduler> createEntity = (status) => Pleasure.MockAsObject<DelayToScheduler>(mock => mock.SetupGet(r => r.Status).Returns(status)); fakeCollection = Pleasure.ToQueryable(createEntity(DelayOfStatus.New), createEntity(DelayOfStatus.New.Inverse()), createEntity(DelayOfStatus.New.Inverse())); }; Because of = () => { filterCollection = fakeCollection .Where(new DelayToScheduler.Where.ByStatus(DelayOfStatus.New).IsSatisfiedBy()) .ToList(); }; It should_be_filter = () => { filterCollection.Count.ShouldEqual(1); filterCollection[0].Status.ShouldEqual(DelayOfStatus.New); }; } }
37.75
197
0.48234
[ "Apache-2.0" ]
Incoding-Software/Incoding-Framework
src/Incoding.UnitTest/Block/Scheduler Factory/When_delay_to_scheduler_by_status.cs
1,814
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Common.Log; using Lykke.Common.Log; using Lykke.Service.PayCallback.Client.InvoiceConfirmation; using Lykke.Service.PayInvoice.Core.Domain.InvoiceConfirmation; using Lykke.Service.PayInvoice.Core.Domain.PushNotification; using Lykke.Service.PayInvoice.Core.Services; using Lykke.Service.PayInvoice.Core.Settings; using Lykke.Service.PayPushNotifications.Client.Publisher; using Polly; using Polly.Retry; namespace Lykke.Service.PayInvoice.Services { public class PushNotificationService : IPushNotificationService { private readonly NotificationPublisher _pushNotificationPublisher; private readonly RetryPolicy _retryPolicy; private readonly ILog _log; public PushNotificationService( NotificationPublisher pushNotificationPublisher, RetryPolicySettings retryPolicySettings, ILogFactory logFactory) { _pushNotificationPublisher = pushNotificationPublisher; _log = logFactory.CreateLog(this); _retryPolicy = Policy .Handle<Exception>() .WaitAndRetryAsync( retryPolicySettings.DefaultAttempts, attempt => TimeSpan.FromSeconds(Math.Pow(2, attempt)), (ex, timespan) => _log.Error(ex, "Publish confirmations to callback with retry")); } public async Task PublishDisputeCancelled(DisputeCancelledPushNotificationCommand command) { var notificationMessage = new NotificationMessage { MerchantIds = new string[] { command.NotifiedMerchantId }, Message = "Dispute cancelled." }; await _retryPolicy.ExecuteAsync(() => _pushNotificationPublisher.PublishAsync(notificationMessage)); _log.Info("Information sent to push notifications service", new { notificationMessage }); } public async Task PublishDisputeRaised(DisputeRaisedPushNotificationCommand command) { var notificationMessage = new NotificationMessage { MerchantIds = new string[] { command.NotifiedMerchantId }, Message = "Dispute raised." }; await _retryPolicy.ExecuteAsync(() => _pushNotificationPublisher.PublishAsync(notificationMessage)); _log.Info("Information sent to push notifications service", new { notificationMessage }); } public async Task PublishInvoicePayment(InvoicePaidPushNotificationCommand command) { var notificationMessage = new NotificationMessage { MerchantIds = new string[] { command.NotifiedMerchantId }, Message = $"Invoice has been paid by {command.PayerMerchantName}: {command.PaidAmount} USD received." }; await _retryPolicy.ExecuteAsync(() => _pushNotificationPublisher.PublishAsync(notificationMessage)); _log.Info("Information sent to push notifications service", new { notificationMessage }); } } }
40.151899
117
0.676545
[ "MIT" ]
LykkeCity/Lykke.Service.PayInvoice
src/Lykke.Service.PayInvoice.Services/PushNotificationService.cs
3,174
C#
// This file is auto-generated, don't edit it. Thanks. using System; using System.Collections.Generic; using System.IO; using Tea; namespace AlibabaCloud.SDK.Dingtalkats_1_0.Models { public class FinishBeginnerTaskResponseBody : TeaModel { /// <summary> /// 是否成功 /// </summary> [NameInMap("result")] [Validation(Required=false)] public bool? Result { get; set; } } }
19.454545
60
0.635514
[ "Apache-2.0" ]
aliyun/dingtalk-sdk
dingtalk/csharp/core/ats_1_0/Models/FinishBeginnerTaskResponseBody.cs
436
C#
using UnityEngine; namespace AirFishLab.ScrollingList.BoxTransformCtrl { /// <summary> /// The interface for setting the transform of a box /// </summary> public interface IBoxTransformCtrl { /// <summary> /// Set the initial transform for the specified box /// </summary> /// <param name="transform">The transform of the box</param> /// <param name="boxID">The ID of the box</param> /// <param name="numOfBoxes">The number of boxes</param> void SetInitialTransform(Transform transform, int boxID, int numOfBoxes); /// <summary> /// Set the next local transform according to the moving delta /// </summary> /// <param name="boxTransform">The transform of the box</param> /// <param name="delta">The delta moving distance</param> /// <param name="needToUpdateToLastContent"> /// Does the box need to update to the last content? /// </param> /// <param name="needToUpdateToNextContent"> /// Does the box need to update to the next content? /// </param> void SetLocalTransform( Transform boxTransform, float delta, out bool needToUpdateToLastContent, out bool needToUpdateToNextContent); } }
36.555556
81
0.608663
[ "Apache-2.0" ]
Mighstye/-Tragedies-in-Vacuous-Scroll
Assets/Plugins/CircularScrollingList/Scripts/BoxTransformCtrl/IBoxTransformCtrl.cs
1,318
C#
using System.Collections.Generic; using EcsRx.Blueprints; namespace Adventure.GameEngine.Builder { public interface IBluePrintProvider { IEnumerable<IBlueprint> Blueprints { get; } void Validate(); } }
19.333333
51
0.702586
[ "MIT" ]
Tauron1990/TextAdventure
Alt/Adventure.GameEngine/Builder/IBluePrintProvider.cs
234
C#
using System; using System.Collections.Generic; using System.IO; using TQVaultAE.Domain.Contracts.Providers; using TQVaultAE.Domain.Contracts.Services; using TQVaultAE.Domain.Entities; using TQVaultAE.Domain.Results; using TQVaultAE.Logs; namespace TQVaultAE.Services { public class VaultService : IVaultService { private readonly log4net.ILog Log = null; private readonly SessionContext userContext = null; private readonly IGamePathService GamePathResolver; private readonly IPlayerCollectionProvider PlayerCollectionProvider; public const string MAINVAULT = "Main Vault"; public VaultService(ILogger<StashService> log, SessionContext userContext, IPlayerCollectionProvider playerCollectionProvider, IGamePathService gamePathResolver) { this.Log = log.Logger; this.userContext = userContext; this.GamePathResolver = gamePathResolver; this.PlayerCollectionProvider = playerCollectionProvider; } /// <summary> /// Creates a new empty vault file /// </summary> /// <param name="name">Name of the vault.</param> /// <param name="file">file name of the vault.</param> /// <returns>Player instance of the new vault.</returns> public PlayerCollection CreateVault(string name, string file) { PlayerCollection vault = new PlayerCollection(name, file); vault.IsVault = true; vault.CreateEmptySacks(12); // number of bags return vault; } /// <summary> /// Attempts to save all modified vault files /// </summary> /// <param name="vaultOnError"></param> /// <exception cref="IOException">can happen during file save</exception> public void SaveAllModifiedVaults(ref PlayerCollection vaultOnError) { foreach (KeyValuePair<string, Lazy<PlayerCollection>> kvp in this.userContext.Vaults) { string vaultFile = kvp.Key; PlayerCollection vault = kvp.Value.Value; if (vault == null) continue; if (vault.IsModified) { // backup the file vaultOnError = vault; GamePathResolver.BackupFile(vault.PlayerName, vaultFile); PlayerCollectionProvider.Save(vault, vaultFile); } } } /// <summary> /// Loads a vault file /// </summary> /// <param name="vaultName">Name of the vault</param> public LoadVaultResult LoadVault(string vaultName) { var result = new LoadVaultResult(); // Get the filename result.Filename = GamePathResolver.GetVaultFile(vaultName); // Check the cache var resultVault = this.userContext.Vaults.GetOrAddAtomic(result.Filename, k => { PlayerCollection pc; // We need to load the vault. if (!File.Exists(k)) { // the file does not exist so create a new vault. pc = this.CreateVault(vaultName, k); pc.VaultLoaded = true; } else { pc = new PlayerCollection(vaultName, k); pc.IsVault = true; try { PlayerCollectionProvider.LoadFile(pc); pc.VaultLoaded = true; } catch (ArgumentException argumentException) { pc.ArgumentException = argumentException; } } return pc; }); result.Vault = resultVault; result.VaultLoaded = resultVault.VaultLoaded; result.ArgumentException = resultVault.ArgumentException; return result; } /// <summary> /// Updates VaultPath key from the configuration UI /// Needed since all vaults will need to be reloaded if this key changes. /// </summary> /// <param name="vaultPath">Path to the vault files</param> public void UpdateVaultPath(string vaultPath) { Config.Settings.Default.VaultPath = vaultPath; Config.Settings.Default.Save(); } } }
28.404762
163
0.706063
[ "MIT" ]
AlexSnowLeo/TQVaultAE
src/TQVaultAE.Services/VaultService.cs
3,581
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace YouRate.Account { public partial class Register { /// <summary> /// ErrorMessage control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Literal ErrorMessage; /// <summary> /// Email control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox Email; /// <summary> /// Password control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox Password; /// <summary> /// ConfirmPassword control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox ConfirmPassword; } }
33.269231
84
0.512717
[ "MIT" ]
22gui22/YouRating
YouRate/YouRate/Account/Register.aspx.designer.cs
1,732
C#
using MongoDB.Bson.Serialization.Attributes; using System; namespace SaveMyDataServer.Database.Models.Users { /// <summary> /// The model that holds the user information /// </summary> public class UserDatabaseModel { #region Properties /// <summary> /// The unique id of the user /// </summary> [BsonId] public Guid Id { get; set; } public Guid UserId { get; set; } public string FullName { get; set; } public string Name { get; set; } public DateTime CreationDateUTC { get; set; } public Guid Key { get; set; } #endregion #region Constructer /// <summary> /// Default constructer /// </summary> public UserDatabaseModel() { } #endregion } }
23.771429
53
0.551683
[ "MIT" ]
Saria-houloubi/SaveMyData
SaveMyDatabase.Database/Models/UserDatabaseModel.cs
834
C#
using ArkeCLR.Runtime.Streams; using ArkeCLR.Runtime.Tables.Flags; using ArkeCLR.Utilities; #pragma warning disable S1104 namespace ArkeCLR.Runtime.Tables { public struct MethodSemantics : ICustomByteReader<TokenByteReader> { public MethodSemanticsAttributes Semantics; public TableToken Method; public TableToken Association; public void Read(TokenByteReader reader) { reader.ReadEnum(out this.Semantics); reader.Read(TableType.MethodDef, out this.Method); reader.Read(CodedIndexType.HasSemantics, out this.Association); } } }
32.368421
75
0.713821
[ "MIT" ]
Arke64/ArkeCLR
ArkeCLR.Runtime/Tables/MethodSemantics.cs
617
C#
// This source code is dual-licensed under the Apache License, version // 2.0, and the Mozilla Public License, version 2.0. // // The APL v2.0: // //--------------------------------------------------------------------------- // Copyright (c) 2007-2020 VMware, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //--------------------------------------------------------------------------- // // The MPL v2.0: // //--------------------------------------------------------------------------- // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. // // Copyright (c) 2007-2020 VMware, Inc. All rights reserved. //--------------------------------------------------------------------------- using System; using System.Net.Sockets; using RabbitMQ.Client.Impl; namespace RabbitMQ.Client { public class ConnectionFactoryBase { /// <summary> /// Set custom socket options by providing a SocketFactory. /// </summary> public Func<AddressFamily, ITcpClient> SocketFactory = DefaultSocketFactory; /// <summary> /// Creates a new instance of the <see cref="TcpClient"/>. /// </summary> /// <param name="addressFamily">Specifies the addressing scheme.</param> /// <returns>New instance of a <see cref="TcpClient"/>.</returns> public static ITcpClient DefaultSocketFactory(AddressFamily addressFamily) { var socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp) { NoDelay = true, ReceiveBufferSize = 65536, SendBufferSize = 65536 }; return new TcpClientAdapter(socket); } } }
38.225806
87
0.568776
[ "MPL-2.0-no-copyleft-exception", "MPL-2.0", "Apache-2.0" ]
10088/rabbitmq-dotnet-client
projects/RabbitMQ.Client/client/api/ConnectionFactoryBase.cs
2,370
C#
using Core.DTO; using System; using System.Collections.Generic; using System.Text; namespace Core.Service { public interface IDisponibilizarMedicamentoService { void Editar(Medicamentodisponivel medicamentoDisponivel); int Inserir(Medicamentodisponivel medicamentodisponivel); Medicamentodisponivel Obter(int idDisponibilizacaoMedicamento); // IEnumerable<Medicamentodisponivel> ObterPorNome(string nome); IEnumerable<Medicamentodisponivel> ObterTodos(); void Remover(int idDisponibilizacaoMedicamento); // IEnumerable<DisponibilizarMedicamentoDTO> ObterPorNomeOrdenadoDescending(string nome); } }
26.88
96
0.766369
[ "MIT" ]
marcosdosea/IDrug
Codigo/Core/Service/IDisponibilizarMedicamentoService.cs
674
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using ITSWebMgmt.Models; using System.DirectoryServices; namespace ITSWebMgmt.Controllers { public class HomeController : Controller { public IActionResult Index() { return View(); } public IActionResult Privacy() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } public void Redirector(string adpath) { if (adpath != null) { if (!adpath.StartsWith("LDAP://")) { adpath = "LDAP://" + adpath; } DirectoryEntry de = new DirectoryEntry(adpath); var type = de.SchemaEntry.Name; if (type.Equals("user")) { string param = "?" + "username=" + de.Properties["userPrincipalName"].Value.ToString(); Response.Redirect("/User" + param); } else if (type.Equals("computer")) { var ldapSplit = adpath.Replace("LDAP://", "").Split(','); var name = ldapSplit[0].Replace("CN=", ""); var domain = ldapSplit.Where<string>(s => s.StartsWith("DC=")).ToArray<string>()[0].Replace("DC=", ""); string param = "?" + "computername=" + domain + "\\" + name; Response.Redirect("/Computer" + param); } else if (type.Equals("group")) { string param = "?" + "grouppath=" + adpath; Response.Redirect("/Group" + param); } } } } }
31.676923
123
0.492472
[ "BSD-2-Clause" ]
yrke/AAUWebMgmt
ITSWebMgmt/Controllers/HomeController.cs
2,061
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace SDP_prototype.Staff { public partial class StaffReceiveProblems : Form { #region it make Draggable // It use to make it draggable. // public const int WM_NCLBUTTONDOWN = 0xA1; public const int HT_CAPTION = 0x2; [System.Runtime.InteropServices.DllImport("user32.dll")] public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam); [System.Runtime.InteropServices.DllImport("user32.dll")] public static extern bool ReleaseCapture(); private void StaffReceiveProblems_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { ReleaseCapture(); SendMessage(MdiParent.Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0); } } // It use to make it draggable. // #endregion public StaffReceiveProblems() { InitializeComponent(); } private void StaffReceiveProblems_Load(object sender, EventArgs e) { ProblemReportDataBaseControl.Load(); lblReceiveProblem.Text = ""; for (int i = 0; i < ProblemReportDataBaseControl.dataTable.Rows.Count; i++) { lblReceiveProblem.Text += "ProblemReportID: " + ProblemReportDataBaseControl.problemReportIDs[i] + Environment.NewLine; lblReceiveProblem.Text += "Title: " + ProblemReportDataBaseControl.titles[i] + Environment.NewLine; lblReceiveProblem.Text += "Detail: " + ProblemReportDataBaseControl.details[i] + Environment.NewLine + Environment.NewLine; } } } }
33.614035
139
0.638309
[ "MIT" ]
CWKSC/HKIVE-GSD-SDP-Point-Card-System
Program/SDP_prototype/SDP_prototype/Staff/StaffReceiveProblems.cs
1,918
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Labs_72_LINQQ_JOIN { using System; using System.Data.Entity; using System.Data.Entity.Infrastructure; public partial class NorthwindEntities : DbContext { public NorthwindEntities() : base("name=NorthwindEntities") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { throw new UnintentionalCodeFirstException(); } public virtual DbSet<Category> Categories { get; set; } public virtual DbSet<CustomerDemographic> CustomerDemographics { get; set; } public virtual DbSet<Customer> Customers { get; set; } public virtual DbSet<Employee> Employees { get; set; } public virtual DbSet<Order_Detail> Order_Details { get; set; } public virtual DbSet<Order> Orders { get; set; } public virtual DbSet<Product> Products { get; set; } public virtual DbSet<Region> Regions { get; set; } public virtual DbSet<Shipper> Shippers { get; set; } public virtual DbSet<Supplier> Suppliers { get; set; } public virtual DbSet<Territory> Territories { get; set; } public virtual DbSet<Course> Courses { get; set; } public virtual DbSet<Student> Students { get; set; } } }
40
85
0.593605
[ "MIT" ]
Lidinh26/Sparta-C-Sharp-Course
Labs_72_LINQQ_JOIN/Model1.Context.cs
1,722
C#
using UnityEngine; using System.Collections; public class FpsHudCrosshair : FpsHudReticule { float previousSpread = float.MaxValue; public int PixelWidth = 4; public int PixelHeight = 11; public Transform Left; public Transform Right; public Transform Top; public Transform Bottom; void Start() { Top.renderer.sharedMaterial.SetColor("_Color", FpsHud.Instance.CrosshairColor); } void Update() { Spread = Mathf.Clamp01(Spread); if (Spread != previousSpread) { int pixelSpread = Mathf.Clamp(Mathf.RoundToInt(Spread * MaxSpred), MinSpred, MaxSpred); Left.position = FpsHudUtils.ToScreenPosition(new Vector3(-PixelHeight - pixelSpread, (PixelWidth / 2), 1)); Right.position = FpsHudUtils.ToScreenPosition(new Vector3(pixelSpread, (PixelWidth / 2), 1)); Top.position = FpsHudUtils.ToScreenPosition(new Vector3(-(PixelWidth / 2), PixelHeight + pixelSpread, 1)); Bottom.position = FpsHudUtils.ToScreenPosition(new Vector3(-(PixelWidth / 2), -pixelSpread, 1)); previousSpread = Spread; } } }
31.216216
119
0.660606
[ "Unlicense", "MIT" ]
Amitkapadi/unityassets
FpsHud3D/Assets/FpsHud/Scripts/FpsHudCrosshair.cs
1,155
C#
using System; using System.Collections.Generic; namespace SKIT.FlurlHttpClient.Wechat.Api.Models { /// <summary> /// <para>表示 [POST] /cityservice/sendmsgdata 接口的响应。</para> /// </summary> public class CityServiceSendMessageDataResponse : WechatApiResponse { /// <summary> /// 获取或设置结果页 URL。 /// </summary> [Newtonsoft.Json.JsonProperty("result_page_url")] [System.Text.Json.Serialization.JsonPropertyName("result_page_url")] public string? ResultPageUrl { get; set; } } }
28.631579
76
0.652574
[ "MIT" ]
KimMeng2015/DotNetCore.SKIT.FlurlHttpClient.Wechat
src/SKIT.FlurlHttpClient.Wechat.Api/Models/CityService/CityServiceSendMessageDataResponse.cs
580
C#
using System; namespace Midnight { class Midnight { } }
7.8
18
0.525641
[ "MIT" ]
KamRon-67/project_unicorn
Midnight/Midnight.cs
80
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace zeldaGui { public class CustomItem { public byte[] iconsId; public byte level; public bool on; public string name; public bool loop = false; public bool bottle = false; public bool count = false; public byte counter = 0; public CustomItem(byte[] iconsId, string name, bool loop = false, bool bottle = false, bool count = false) { this.iconsId = iconsId; this.level = 0; this.on = false; this.name = name; this.bottle = bottle; this.loop = loop; this.count = count; } } }
24.5
114
0.565051
[ "MIT" ]
Formedras/ZeldaHUD
ZeldaHUD/ZeldaHUD/CustomItem.cs
786
C#
using System; using System.Linq; using System.Reflection; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; using Unity.Jobs; using Unity.Jobs.LowLevel.Unsafe; namespace Chisel.Core { // Based on: https://github.com/jacksondunstan/NativeCollections/tree/master/JacksonDunstanNativeCollections // https://jacksondunstan.com/articles/4857 // by Jackson Dunstan // MIT license: https://github.com/jacksondunstan/NativeCollections/blob/master/LICENSE.md public static class IJobParallelForDeferExtensions { internal struct ParallelForJobStruct<T> where T : struct, IJobParallelFor { public static IntPtr jobReflectionData; public static IntPtr Initialize() { if (jobReflectionData == IntPtr.Zero) { var attribute = (JobProducerTypeAttribute)typeof(IJobParallelFor).GetCustomAttribute(typeof(JobProducerTypeAttribute)); var jobStruct = attribute.ProducerType.MakeGenericType(typeof(T)); var method = jobStruct.GetMethod("Initialize", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public); var res = method.Invoke(null, new object[0]); jobReflectionData = (IntPtr)res; } return jobReflectionData; } } unsafe public static JobHandle Schedule<T, U>(this T jobData, NativeList<U> list, int innerloopBatchCount, JobHandle dependsOn = default) where T : struct, IJobParallelFor where U : struct { var scheduleParams = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), ParallelForJobStruct<T>.Initialize(), dependsOn, ScheduleMode.Parallel); void* atomicSafetyHandlePtr = null; #if ENABLE_UNITY_COLLECTIONS_CHECKS var safety = NativeListUnsafeUtility.GetAtomicSafetyHandle(ref list); atomicSafetyHandlePtr = UnsafeUtility.AddressOf(ref safety); #endif return JobsUtility.ScheduleParallelForDeferArraySize(ref scheduleParams, innerloopBatchCount, NativeListUnsafeUtility.GetInternalListDataPtrUnchecked(ref list), atomicSafetyHandlePtr); } } public static class IJobRunExtensions { public static JobHandle Run<T, U>(this T jobData, NativeList<U> list, int innerloopBatchCount, JobHandle dependsOn = default) where T : struct, IJobParallelFor where U : struct { for (int i = 0; i < list.Length; i++) jobData.Execute(i); return dependsOn; } public static JobHandle Run<T>(this T jobData, JobHandle dependsOn = default) where T : struct, IJob { jobData.Execute(); return dependsOn; } } }
39.986111
196
0.655783
[ "MIT" ]
cr4yz/Chisel.Prototype
Packages/com.chisel.core/Chisel/Core/API.private/Managed/Thirdparty/IJobParallelForDeferExtensions.cs
2,879
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the iotwireless-2020-11-22.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.IoTWireless.Model { /// <summary> /// Information about a service profile. /// </summary> public partial class ServiceProfile { private string _arn; private string _id; private string _name; /// <summary> /// Gets and sets the property Arn. /// <para> /// The Amazon Resource Name of the resource. /// </para> /// </summary> public string Arn { get { return this._arn; } set { this._arn = value; } } // Check to see if Arn property is set internal bool IsSetArn() { return this._arn != null; } /// <summary> /// Gets and sets the property Id. /// <para> /// The ID of the service profile. /// </para> /// </summary> [AWSProperty(Max=256)] public string Id { get { return this._id; } set { this._id = value; } } // Check to see if Id property is set internal bool IsSetId() { return this._id != null; } /// <summary> /// Gets and sets the property Name. /// <para> /// The name of the resource. /// </para> /// </summary> [AWSProperty(Max=256)] public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } } }
25.958763
109
0.561557
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/IoTWireless/Generated/Model/ServiceProfile.cs
2,518
C#
// <copyright file="DateListOutput.cs" company="Traced-Ideas, Czech republic"> // Copyright (c) 1990-2021 All Right Reserved // </copyright> // <author></author> // <email></email> // <date>2021-09-01</date> // <summary>Part of Astro Observatory</summary> namespace AstroSharedEvents.Lists { using AstroSharedEvents.Records; using AstroSharedOrbits.Dwarfs; using AstroSharedOrbits.Systems; using global::AstroSharedClasses.Calendars; using global::AstroSharedClasses.Computation; using global::AstroSharedClasses.Enums; using JetBrains.Annotations; using System; using System.Globalization; /// <summary> /// Date List. /// </summary> public partial class EventList : DateList { #region MayanConstants /// <summary> /// Mayan Correlation Constant. /// </summary> [UsedImplicitly] public const long MayanCorrelationConstant = 508392; //// public const long MayanCorrelationConstant = 584285; //// public const long MayanCorrelationConstant = 622261; //// Bohm #endregion #region Public methods /// <summary> /// VYPIS POZIC PLANET (TABULKY). /// </summary> /// <param name="charact">The charact.</param> /// <returns>Returns value.</returns> [UsedImplicitly] public string PrintCharacteristic(AstCharacteristic charact) { //// this.List.Append("<HTML>\n\r"); this.List.Append("<PRE>\n\r"); double lastJulianDate; int number = 0; var record = this.GetRecord(charact); //// new AbstractRecord(); foreach (double julianDate in this.Date) { //// var info = i < this.Info.Count ? this.Info[i] : string.Empty; record.SetData(number, julianDate, julianDate - this.LastJulianDate); SolarSystem.Singleton.SetJulianDate(julianDate); //// EarthSystem.SetJulianDate(julianDate); record.OutputRecord(); if (record.IsValid) { if (record.IsFinished) { this.List.Append("\n"); // NEW LINE } this.List.Append(record.Text); number++; lastJulianDate = julianDate; } } //// this.List.Append("</PRE>\n\r"); this.List.Append("</HTML>\n\r"); return this.List.ToString(); } /// <summary> /// Gets the record. /// </summary> /// <param name="charact">The charact.</param> /// <returns>Returns value.</returns> public AbstractRecord GetRecord(AstCharacteristic charact) { var qualifiedAssemblyName = "AstroSharedEvents.Records.Record" + charact.ToString(); var recordType = Type.GetType(qualifiedAssemblyName); var record = (AbstractRecord)Activator.CreateInstance(recordType); return record; } #endregion } }
35.55814
96
0.576848
[ "MIT" ]
Vladimir1965/AstroObservatory
AstroSharedEvents/Lists/DateListOutput.cs
3,060
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Globalization; using System.Net; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Bot.Schema; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using SlackAPI; #if SIGNASSEMBLY [assembly: InternalsVisibleTo("Microsoft.Bot.Builder.Adapters.Slack.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] #else [assembly: InternalsVisibleTo("Microsoft.Bot.Builder.Adapters.Slack.Tests")] #endif namespace Microsoft.Bot.Builder.Adapters.Slack { internal static class SlackHelper { /// <summary> /// Formats a BotBuilder activity into an outgoing Slack message. /// </summary> /// <param name="activity">A BotBuilder Activity object.</param> /// <returns>A Slack message object with {text, attachments, channel, thread ts} as well as any fields found in activity.channelData.</returns> public static NewSlackMessage ActivityToSlack(Activity activity) { if (activity == null) { throw new ArgumentNullException(nameof(activity)); } var message = new NewSlackMessage(); if (activity.Timestamp != null) { message.Ts = activity.Timestamp.Value.DateTime.ToString(CultureInfo.InvariantCulture); } message.Text = activity.Text; if (activity.Attachments != null) { var attachments = new List<SlackAPI.Attachment>(); foreach (var att in activity.Attachments) { if (att.Name == "blocks") { message.Blocks = (List<Block>)att.Content; } else { var newAttachment = new SlackAPI.Attachment() { author_name = att.Name, thumb_url = att.ThumbnailUrl, }; attachments.Add(newAttachment); } } if (attachments.Count > 0) { message.Attachments = attachments; } } message.Channel = activity.Conversation.Id; if (!string.IsNullOrWhiteSpace(activity.Conversation.Properties["thread_ts"]?.ToString())) { message.ThreadTs = activity.Conversation.Properties["thread_ts"].ToString(); } // if channelData is specified, overwrite any fields in message object if (activity.ChannelData != null) { message = activity.GetChannelData<NewSlackMessage>(); } // should this message be sent as an ephemeral message if (!string.IsNullOrWhiteSpace(message.Ephemeral)) { message.User = activity.Recipient.Id; } if (message.IconUrl != null || !string.IsNullOrWhiteSpace(message.Icons?.status_emoji) || !string.IsNullOrWhiteSpace(message.Username)) { message.AsUser = false; } return message; } /// <summary> /// Writes the HttpResponse. /// </summary> /// <param name="response">The httpResponse.</param> /// <param name="code">The status code to be written.</param> /// <param name="text">The text to be written.</param> /// <param name="encoding">The encoding for the text.</param> /// <param name="cancellationToken">A cancellation token for the task.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public static async Task WriteAsync(HttpResponse response, HttpStatusCode code, string text, Encoding encoding, CancellationToken cancellationToken = default) { if (response == null) { throw new ArgumentNullException(nameof(response)); } if (text == null) { throw new ArgumentNullException(nameof(text)); } if (encoding == null) { throw new ArgumentNullException(nameof(encoding)); } response.ContentType = "text/plain"; response.StatusCode = (int)code; var data = encoding.GetBytes(text); await response.Body.WriteAsync(data, 0, data.Length, cancellationToken).ConfigureAwait(false); } /// <summary> /// Creates an activity based on the slack event payload. /// </summary> /// <param name="slackPayload">The payload of the slack event.</param> /// <returns>An activity containing the event data.</returns> public static Activity PayloadToActivity(SlackPayload slackPayload) { if (slackPayload == null) { throw new ArgumentNullException(nameof(slackPayload)); } var activity = new Activity() { Timestamp = default, ChannelId = "slack", Conversation = new ConversationAccount() { Id = slackPayload.Channel.id, }, From = new ChannelAccount() { Id = slackPayload.Message?.BotId ?? slackPayload.User.id, }, Recipient = new ChannelAccount() { Id = null, }, ChannelData = slackPayload, Text = null, Type = ActivityTypes.Event, }; if (slackPayload.ThreadTs != null) { activity.Conversation.Properties["thread_ts"] = slackPayload.ThreadTs; } if (slackPayload.Actions != null && (slackPayload.Type == "block_actions" || slackPayload.Type == "interactive_message")) { activity.Type = ActivityTypes.Message; activity.Text = slackPayload.Actions[0].Value; } return activity; } /// <summary> /// Creates an activity based on the slack event data. /// </summary> /// <param name="slackEvent">The data of the slack event.</param> /// <param name="client">The Slack client.</param> /// <param name="cancellationToken">A cancellation token for the task.</param> /// <returns>An activity containing the event data.</returns> public static async Task<Activity> EventToActivityAsync(SlackEvent slackEvent, SlackClientWrapper client, CancellationToken cancellationToken) { if (slackEvent == null) { throw new ArgumentNullException(nameof(slackEvent)); } var activity = new Activity() { Id = slackEvent.EventTs, Timestamp = default, ChannelId = "slack", Conversation = new ConversationAccount() { Id = slackEvent.Channel ?? slackEvent.ChannelId, }, From = new ChannelAccount() { Id = slackEvent.BotId ?? slackEvent.UserId, }, Recipient = new ChannelAccount() { Id = null, }, ChannelData = slackEvent, Text = null, Type = ActivityTypes.Event, }; if (slackEvent.ThreadTs != null) { activity.Conversation.Properties["thread_ts"] = slackEvent.ThreadTs; } if (activity.Conversation.Id == null) { if (slackEvent.Item != null && slackEvent.ItemChannel != null) { activity.Conversation.Id = slackEvent.ItemChannel; } else { activity.Conversation.Id = slackEvent.Team; } } activity.Recipient.Id = await client.GetBotUserByTeamAsync(activity, cancellationToken).ConfigureAwait(false); // If this is conclusively a message originating from a user, we'll mark it as such if (slackEvent.Type == "message" && slackEvent.BotId == null) { if (slackEvent.SubType == null) { activity.Type = ActivityTypes.Message; activity.Text = slackEvent.Text; } } return activity; } /// <summary> /// Creates an activity based on a slack event related to a slash command. /// </summary> /// <param name="slackBody">The data of the slack event.</param> /// <param name="client">The Slack client.</param> /// <param name="cancellationToken">A cancellation token for the task.</param> /// <returns>An activity containing the event data.</returns> public static async Task<Activity> CommandToActivityAsync(SlackRequestBody slackBody, SlackClientWrapper client, CancellationToken cancellationToken) { if (slackBody == null) { throw new ArgumentNullException(nameof(slackBody)); } var activity = new Activity() { Id = slackBody.TriggerId, Timestamp = default, ChannelId = "slack", Conversation = new ConversationAccount() { Id = slackBody.ChannelId, }, From = new ChannelAccount() { Id = slackBody.UserId, }, Recipient = new ChannelAccount() { Id = null, }, ChannelData = slackBody, Text = slackBody.Text, Type = ActivityTypes.Event, }; activity.Recipient.Id = await client.GetBotUserByTeamAsync(activity, cancellationToken).ConfigureAwait(false); activity.Conversation.Properties["team"] = slackBody.TeamId; return activity; } /// <summary> /// Converts a query string to a dictionary with key-value pairs. /// </summary> /// <param name="query">The query string to convert.</param> /// <returns>A dictionary with the query values.</returns> public static Dictionary<string, string> QueryStringToDictionary(string query) { var values = new Dictionary<string, string>(); if (string.IsNullOrWhiteSpace(query)) { return values; } var pairs = query.Replace("+", "%20").Split('&'); foreach (var p in pairs) { var pair = p.Split('='); var key = pair[0]; var value = Uri.UnescapeDataString(pair[1]); values.Add(key, value); } return values; } /// <summary> /// Deserializes the request's body as a <see cref="SlackRequestBody"/> object. /// </summary> /// <param name="requestBody">The query string to convert.</param> /// <returns>A dictionary with the query values.</returns> public static SlackRequestBody DeserializeBody(string requestBody) { if (string.IsNullOrWhiteSpace(requestBody)) { return null; } // Check if it's a command event if (requestBody.Contains("command=%2F")) { var commandBody = QueryStringToDictionary(requestBody); return JsonConvert.DeserializeObject<SlackRequestBody>(JsonConvert.SerializeObject(commandBody)); } if (requestBody.Contains("payload=")) { // Decode and remove "payload=" from the body var decodedBody = Uri.UnescapeDataString(requestBody).Remove(0, 8); var payload = JsonConvert.DeserializeObject<SlackPayload>(decodedBody); return new SlackRequestBody { Payload = payload, Token = payload.Token, }; } return JsonConvert.DeserializeObject<SlackRequestBody>(requestBody, new UnixDateTimeConverter()); } } }
36.487535
408
0.540313
[ "MIT" ]
NickEricson/botbuilder-dotnet
libraries/Adapters/Microsoft.Bot.Builder.Adapters.Slack/SlackHelper.cs
13,174
C#
 namespace Hills.IdentityServer4.Deployment { partial class EditEndPoint { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.lnkSelectFile = new System.Windows.Forms.LinkLabel(); this.cmbCertificate = new System.Windows.Forms.ComboBox(); this.cmbCertificateType = new System.Windows.Forms.ComboBox(); this.cmbIpAddress = new System.Windows.Forms.ComboBox(); this.label7 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.chkHttps = new System.Windows.Forms.CheckBox(); this.txtFileName = new System.Windows.Forms.TextBox(); this.txtPort = new System.Windows.Forms.TextBox(); this.cmdSave = new System.Windows.Forms.Button(); this.txtPassword = new System.Windows.Forms.TextBox(); this.label5 = new System.Windows.Forms.Label(); this.txtName = new System.Windows.Forms.TextBox(); this.label6 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // lnkSelectFile // this.lnkSelectFile.AutoSize = true; this.lnkSelectFile.Location = new System.Drawing.Point(405, 189); this.lnkSelectFile.Name = "lnkSelectFile"; this.lnkSelectFile.Size = new System.Drawing.Size(57, 15); this.lnkSelectFile.TabIndex = 19; this.lnkSelectFile.TabStop = true; this.lnkSelectFile.Text = "Select file"; this.lnkSelectFile.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkSelectFile_LinkClicked); // // cmbCertificate // this.cmbCertificate.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbCertificate.FormattingEnabled = true; this.cmbCertificate.Location = new System.Drawing.Point(125, 157); this.cmbCertificate.Name = "cmbCertificate"; this.cmbCertificate.Size = new System.Drawing.Size(274, 23); this.cmbCertificate.TabIndex = 16; // // cmbCertificateType // this.cmbCertificateType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbCertificateType.FormattingEnabled = true; this.cmbCertificateType.Location = new System.Drawing.Point(125, 128); this.cmbCertificateType.Name = "cmbCertificateType"; this.cmbCertificateType.Size = new System.Drawing.Size(131, 23); this.cmbCertificateType.TabIndex = 17; this.cmbCertificateType.SelectedIndexChanged += new System.EventHandler(this.cmbCertificateType_SelectedIndexChanged); // // cmbIpAddress // this.cmbIpAddress.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbIpAddress.FormattingEnabled = true; this.cmbIpAddress.Location = new System.Drawing.Point(125, 41); this.cmbIpAddress.Name = "cmbIpAddress"; this.cmbIpAddress.Size = new System.Drawing.Size(274, 23); this.cmbIpAddress.TabIndex = 18; // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(61, 102); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(58, 15); this.label7.TabIndex = 10; this.label7.Text = "Use Https"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(90, 73); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(29, 15); this.label2.TabIndex = 11; this.label2.Text = "Port"; // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(58, 160); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(61, 15); this.label8.TabIndex = 12; this.label8.Text = "Certificate"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(94, 189); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(25, 15); this.label4.TabIndex = 13; this.label4.Text = "File"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(32, 131); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(87, 15); this.label3.TabIndex = 14; this.label3.Text = "Certificate type"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(57, 44); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(62, 15); this.label1.TabIndex = 15; this.label1.Text = "Ip Address"; // // chkHttps // this.chkHttps.Location = new System.Drawing.Point(125, 99); this.chkHttps.Name = "chkHttps"; this.chkHttps.Size = new System.Drawing.Size(104, 23); this.chkHttps.TabIndex = 9; this.chkHttps.UseVisualStyleBackColor = true; this.chkHttps.CheckedChanged += new System.EventHandler(this.chkHttps_CheckedChanged); // // txtFile // this.txtFileName.Location = new System.Drawing.Point(125, 186); this.txtFileName.Name = "txtFile"; this.txtFileName.Size = new System.Drawing.Size(274, 23); this.txtFileName.TabIndex = 7; // // txtPort // this.txtPort.Location = new System.Drawing.Point(125, 70); this.txtPort.Name = "txtPort"; this.txtPort.Size = new System.Drawing.Size(131, 23); this.txtPort.TabIndex = 8; // // cmdSave // this.cmdSave.Location = new System.Drawing.Point(324, 281); this.cmdSave.Name = "cmdSave"; this.cmdSave.Size = new System.Drawing.Size(75, 23); this.cmdSave.TabIndex = 20; this.cmdSave.Text = "Save"; this.cmdSave.UseVisualStyleBackColor = true; this.cmdSave.Click += new System.EventHandler(this.cmdSave_Click); // // txtPassword // this.txtPassword.Location = new System.Drawing.Point(125, 215); this.txtPassword.Name = "txtPassword"; this.txtPassword.Size = new System.Drawing.Size(274, 23); this.txtPassword.TabIndex = 7; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(62, 218); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(57, 15); this.label5.TabIndex = 13; this.label5.Text = "Password"; // // txtName // this.txtName.Location = new System.Drawing.Point(125, 12); this.txtName.Name = "txtName"; this.txtName.Size = new System.Drawing.Size(274, 23); this.txtName.TabIndex = 8; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(80, 15); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(39, 15); this.label6.TabIndex = 11; this.label6.Text = "Name"; // // EditEndPoint // this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None; this.ClientSize = new System.Drawing.Size(510, 337); this.Controls.Add(this.cmdSave); this.Controls.Add(this.lnkSelectFile); this.Controls.Add(this.cmbCertificate); this.Controls.Add(this.cmbCertificateType); this.Controls.Add(this.cmbIpAddress); this.Controls.Add(this.label7); this.Controls.Add(this.label6); this.Controls.Add(this.label2); this.Controls.Add(this.label8); this.Controls.Add(this.label5); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label1); this.Controls.Add(this.chkHttps); this.Controls.Add(this.txtPassword); this.Controls.Add(this.txtFileName); this.Controls.Add(this.txtName); this.Controls.Add(this.txtPort); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; this.Name = "EditEndPoint"; this.Text = "EditEndPoint"; this.Load += new System.EventHandler(this.EditEndPoint_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.LinkLabel lnkSelectFile; private System.Windows.Forms.ComboBox cmbCertificate; private System.Windows.Forms.ComboBox cmbCertificateType; private System.Windows.Forms.ComboBox cmbIpAddress; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label1; private System.Windows.Forms.CheckBox chkHttps; private System.Windows.Forms.TextBox txtFileName; private System.Windows.Forms.TextBox txtPort; private System.Windows.Forms.Button cmdSave; private System.Windows.Forms.TextBox txtPassword; private System.Windows.Forms.Label label5; private System.Windows.Forms.TextBox txtName; private System.Windows.Forms.Label label6; } }
43.973282
136
0.574082
[ "MIT" ]
elaganahills/IdentityServer4.Admin
deployment/EditEndPoint.Designer.cs
11,523
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Gov.Jag.PillPressRegistry.Interfaces.Models { using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// Microsoft.Dynamics.CRM.template /// </summary> public partial class MicrosoftDynamicsCRMtemplate { /// <summary> /// Initializes a new instance of the MicrosoftDynamicsCRMtemplate /// class. /// </summary> public MicrosoftDynamicsCRMtemplate() { CustomInit(); } /// <summary> /// Initializes a new instance of the MicrosoftDynamicsCRMtemplate /// class. /// </summary> /// <param name="presentationxml">XML data for the body of the email /// template.</param> /// <param name="_owningteamValue">Unique identifier of the team who /// owns the template.</param> /// <param name="subjectpresentationxml">XML data for the subject of /// the email template.</param> /// <param name="generationtypecode">For internal use only.</param> /// <param name="_createdbyValue">Unique identifier of the user who /// created the email template.</param> /// <param name="mimetype">MIME type of the email template.</param> /// <param name="modifiedon">Date and time when the email template was /// last modified.</param> /// <param name="_owninguserValue">Unique identifier of the user who /// owns the template.</param> /// <param name="_owneridValue">Unique identifier of the user or team /// who owns the template for the email activity.</param> /// <param name="importsequencenumber">Unique identifier of the data /// import or data migration that created this record.</param> /// <param name="_owningbusinessunitValue">Unique identifier of the /// business unit that owns the template.</param> /// <param name="description">Description of the email /// template.</param> /// <param name="templateidunique">For internal use only.</param> /// <param name="body">Body text of the email template.</param> /// <param name="solutionid">Unique identifier of the associated /// solution.</param> /// <param name="_modifiedbyValue">Unique identifier of the user who /// last modified the template.</param> /// <param name="templatetypecode">Type of email template.</param> /// <param name="_modifiedonbehalfbyValue">Unique identifier of the /// delegate user who last modified the template.</param> /// <param name="iscustomizable">Information that specifies whether /// this component can be customized.</param> /// <param name="ispersonal">Information about whether the template is /// personal or is available to all users.</param> /// <param name="opencount">For internal use only. Shows the number of /// times emails that use this template have been opened.</param> /// <param name="componentstate">For internal use only.</param> /// <param name="templateid">Unique identifier of the template.</param> /// <param name="ismanaged">Indicates whether the solution component is /// part of a managed solution.</param> /// <param name="openrate">Shows the open rate of this template. This /// is based on number of opens on followed emails that use this /// template.</param> /// <param name="title">Title of the template.</param> /// <param name="replyrate">Shows the reply rate for this template. /// This is based on number of replies received on followed emails that /// use this template.</param> /// <param name="createdon">Date and time when the email template was /// created.</param> /// <param name="overwritetime">For internal use only.</param> /// <param name="subject">Subject associated with the email /// template.</param> /// <param name="isrecommended">Indicates if a template is recommended /// by Dynamics 365.</param> /// <param name="introducedversion">Version in which the form is /// introduced.</param> /// <param name="replycount">For internal use only. Shows the number of /// times emails that use this template have received replies.</param> /// <param name="usedcount">Shows the number of sent emails that use /// this template.</param> /// <param name="languagecode">Language of the email template.</param> /// <param name="versionnumber">Version number of the template.</param> /// <param name="_createdonbehalfbyValue">Unique identifier of the /// delegate user who created the template.</param> public MicrosoftDynamicsCRMtemplate(string presentationxml = default(string), string _owningteamValue = default(string), string subjectpresentationxml = default(string), int? generationtypecode = default(int?), string _createdbyValue = default(string), string mimetype = default(string), System.DateTimeOffset? modifiedon = default(System.DateTimeOffset?), string _owninguserValue = default(string), string _owneridValue = default(string), int? importsequencenumber = default(int?), string _owningbusinessunitValue = default(string), string description = default(string), string templateidunique = default(string), string body = default(string), string solutionid = default(string), string _modifiedbyValue = default(string), string templatetypecode = default(string), string _modifiedonbehalfbyValue = default(string), string iscustomizable = default(string), bool? ispersonal = default(bool?), int? opencount = default(int?), int? componentstate = default(int?), string templateid = default(string), bool? ismanaged = default(bool?), int? openrate = default(int?), string title = default(string), int? replyrate = default(int?), System.DateTimeOffset? createdon = default(System.DateTimeOffset?), System.DateTimeOffset? overwritetime = default(System.DateTimeOffset?), string subject = default(string), bool? isrecommended = default(bool?), string introducedversion = default(string), int? replycount = default(int?), int? usedcount = default(int?), int? languagecode = default(int?), string versionnumber = default(string), string _createdonbehalfbyValue = default(string), MicrosoftDynamicsCRMsystemuser createdby = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMbusinessunit owningbusinessunit = default(MicrosoftDynamicsCRMbusinessunit), MicrosoftDynamicsCRMsystemuser modifiedby = default(MicrosoftDynamicsCRMsystemuser), IList<MicrosoftDynamicsCRMasyncoperation> templateAsyncOperations = default(IList<MicrosoftDynamicsCRMasyncoperation>), IList<MicrosoftDynamicsCRMbulkdeletefailure> templateBulkDeleteFailures = default(IList<MicrosoftDynamicsCRMbulkdeletefailure>), MicrosoftDynamicsCRMsystemuser createdonbehalfby = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMteam owningteam = default(MicrosoftDynamicsCRMteam), IList<MicrosoftDynamicsCRMactivitymimeattachment> templateActivityMimeAttachments = default(IList<MicrosoftDynamicsCRMactivitymimeattachment>), MicrosoftDynamicsCRMprincipal ownerid = default(MicrosoftDynamicsCRMprincipal), IList<MicrosoftDynamicsCRMsyncerror> templateSyncErrors = default(IList<MicrosoftDynamicsCRMsyncerror>), MicrosoftDynamicsCRMsystemuser owninguser = default(MicrosoftDynamicsCRMsystemuser), IList<MicrosoftDynamicsCRMorganization> templateOrganization = default(IList<MicrosoftDynamicsCRMorganization>), MicrosoftDynamicsCRMsystemuser modifiedonbehalfby = default(MicrosoftDynamicsCRMsystemuser), IList<MicrosoftDynamicsCRMemail> emailEmailTemplate = default(IList<MicrosoftDynamicsCRMemail>)) { Presentationxml = presentationxml; this._owningteamValue = _owningteamValue; Subjectpresentationxml = subjectpresentationxml; Generationtypecode = generationtypecode; this._createdbyValue = _createdbyValue; Mimetype = mimetype; Modifiedon = modifiedon; this._owninguserValue = _owninguserValue; this._owneridValue = _owneridValue; Importsequencenumber = importsequencenumber; this._owningbusinessunitValue = _owningbusinessunitValue; Description = description; Templateidunique = templateidunique; Body = body; Solutionid = solutionid; this._modifiedbyValue = _modifiedbyValue; Templatetypecode = templatetypecode; this._modifiedonbehalfbyValue = _modifiedonbehalfbyValue; Iscustomizable = iscustomizable; Ispersonal = ispersonal; Opencount = opencount; Componentstate = componentstate; Templateid = templateid; Ismanaged = ismanaged; Openrate = openrate; Title = title; Replyrate = replyrate; Createdon = createdon; Overwritetime = overwritetime; Subject = subject; Isrecommended = isrecommended; Introducedversion = introducedversion; Replycount = replycount; Usedcount = usedcount; Languagecode = languagecode; Versionnumber = versionnumber; this._createdonbehalfbyValue = _createdonbehalfbyValue; Createdby = createdby; Owningbusinessunit = owningbusinessunit; Modifiedby = modifiedby; TemplateAsyncOperations = templateAsyncOperations; TemplateBulkDeleteFailures = templateBulkDeleteFailures; Createdonbehalfby = createdonbehalfby; Owningteam = owningteam; TemplateActivityMimeAttachments = templateActivityMimeAttachments; Ownerid = ownerid; TemplateSyncErrors = templateSyncErrors; Owninguser = owninguser; TemplateOrganization = templateOrganization; Modifiedonbehalfby = modifiedonbehalfby; EmailEmailTemplate = emailEmailTemplate; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets XML data for the body of the email template. /// </summary> [JsonProperty(PropertyName = "presentationxml")] public string Presentationxml { get; set; } /// <summary> /// Gets or sets unique identifier of the team who owns the template. /// </summary> [JsonProperty(PropertyName = "_owningteam_value")] public string _owningteamValue { get; set; } /// <summary> /// Gets or sets XML data for the subject of the email template. /// </summary> [JsonProperty(PropertyName = "subjectpresentationxml")] public string Subjectpresentationxml { get; set; } /// <summary> /// Gets or sets for internal use only. /// </summary> [JsonProperty(PropertyName = "generationtypecode")] public int? Generationtypecode { get; set; } /// <summary> /// Gets or sets unique identifier of the user who created the email /// template. /// </summary> [JsonProperty(PropertyName = "_createdby_value")] public string _createdbyValue { get; set; } /// <summary> /// Gets or sets MIME type of the email template. /// </summary> [JsonProperty(PropertyName = "mimetype")] public string Mimetype { get; set; } /// <summary> /// Gets or sets date and time when the email template was last /// modified. /// </summary> [JsonProperty(PropertyName = "modifiedon")] public System.DateTimeOffset? Modifiedon { get; set; } /// <summary> /// Gets or sets unique identifier of the user who owns the template. /// </summary> [JsonProperty(PropertyName = "_owninguser_value")] public string _owninguserValue { get; set; } /// <summary> /// Gets or sets unique identifier of the user or team who owns the /// template for the email activity. /// </summary> [JsonProperty(PropertyName = "_ownerid_value")] public string _owneridValue { get; set; } /// <summary> /// Gets or sets unique identifier of the data import or data migration /// that created this record. /// </summary> [JsonProperty(PropertyName = "importsequencenumber")] public int? Importsequencenumber { get; set; } /// <summary> /// Gets or sets unique identifier of the business unit that owns the /// template. /// </summary> [JsonProperty(PropertyName = "_owningbusinessunit_value")] public string _owningbusinessunitValue { get; set; } /// <summary> /// Gets or sets description of the email template. /// </summary> [JsonProperty(PropertyName = "description")] public string Description { get; set; } /// <summary> /// Gets or sets for internal use only. /// </summary> [JsonProperty(PropertyName = "templateidunique")] public string Templateidunique { get; set; } /// <summary> /// Gets or sets body text of the email template. /// </summary> [JsonProperty(PropertyName = "body")] public string Body { get; set; } /// <summary> /// Gets or sets unique identifier of the associated solution. /// </summary> [JsonProperty(PropertyName = "solutionid")] public string Solutionid { get; set; } /// <summary> /// Gets or sets unique identifier of the user who last modified the /// template. /// </summary> [JsonProperty(PropertyName = "_modifiedby_value")] public string _modifiedbyValue { get; set; } /// <summary> /// Gets or sets type of email template. /// </summary> [JsonProperty(PropertyName = "templatetypecode")] public string Templatetypecode { get; set; } /// <summary> /// Gets or sets unique identifier of the delegate user who last /// modified the template. /// </summary> [JsonProperty(PropertyName = "_modifiedonbehalfby_value")] public string _modifiedonbehalfbyValue { get; set; } /// <summary> /// Gets or sets information that specifies whether this component can /// be customized. /// </summary> [JsonProperty(PropertyName = "iscustomizable")] public string Iscustomizable { get; set; } /// <summary> /// Gets or sets information about whether the template is personal or /// is available to all users. /// </summary> [JsonProperty(PropertyName = "ispersonal")] public bool? Ispersonal { get; set; } /// <summary> /// Gets or sets for internal use only. Shows the number of times /// emails that use this template have been opened. /// </summary> [JsonProperty(PropertyName = "opencount")] public int? Opencount { get; set; } /// <summary> /// Gets or sets for internal use only. /// </summary> [JsonProperty(PropertyName = "componentstate")] public int? Componentstate { get; set; } /// <summary> /// Gets or sets unique identifier of the template. /// </summary> [JsonProperty(PropertyName = "templateid")] public string Templateid { get; set; } /// <summary> /// Gets or sets indicates whether the solution component is part of a /// managed solution. /// </summary> [JsonProperty(PropertyName = "ismanaged")] public bool? Ismanaged { get; set; } /// <summary> /// Gets or sets shows the open rate of this template. This is based on /// number of opens on followed emails that use this template. /// </summary> [JsonProperty(PropertyName = "openrate")] public int? Openrate { get; set; } /// <summary> /// Gets or sets title of the template. /// </summary> [JsonProperty(PropertyName = "title")] public string Title { get; set; } /// <summary> /// Gets or sets shows the reply rate for this template. This is based /// on number of replies received on followed emails that use this /// template. /// </summary> [JsonProperty(PropertyName = "replyrate")] public int? Replyrate { get; set; } /// <summary> /// Gets or sets date and time when the email template was created. /// </summary> [JsonProperty(PropertyName = "createdon")] public System.DateTimeOffset? Createdon { get; set; } /// <summary> /// Gets or sets for internal use only. /// </summary> [JsonProperty(PropertyName = "overwritetime")] public System.DateTimeOffset? Overwritetime { get; set; } /// <summary> /// Gets or sets subject associated with the email template. /// </summary> [JsonProperty(PropertyName = "subject")] public string Subject { get; set; } /// <summary> /// Gets or sets indicates if a template is recommended by Dynamics /// 365. /// </summary> [JsonProperty(PropertyName = "isrecommended")] public bool? Isrecommended { get; set; } /// <summary> /// Gets or sets version in which the form is introduced. /// </summary> [JsonProperty(PropertyName = "introducedversion")] public string Introducedversion { get; set; } /// <summary> /// Gets or sets for internal use only. Shows the number of times /// emails that use this template have received replies. /// </summary> [JsonProperty(PropertyName = "replycount")] public int? Replycount { get; set; } /// <summary> /// Gets or sets shows the number of sent emails that use this /// template. /// </summary> [JsonProperty(PropertyName = "usedcount")] public int? Usedcount { get; set; } /// <summary> /// Gets or sets language of the email template. /// </summary> [JsonProperty(PropertyName = "languagecode")] public int? Languagecode { get; set; } /// <summary> /// Gets or sets version number of the template. /// </summary> [JsonProperty(PropertyName = "versionnumber")] public string Versionnumber { get; set; } /// <summary> /// Gets or sets unique identifier of the delegate user who created the /// template. /// </summary> [JsonProperty(PropertyName = "_createdonbehalfby_value")] public string _createdonbehalfbyValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "createdby")] public MicrosoftDynamicsCRMsystemuser Createdby { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "owningbusinessunit")] public MicrosoftDynamicsCRMbusinessunit Owningbusinessunit { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "modifiedby")] public MicrosoftDynamicsCRMsystemuser Modifiedby { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "Template_AsyncOperations")] public IList<MicrosoftDynamicsCRMasyncoperation> TemplateAsyncOperations { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "Template_BulkDeleteFailures")] public IList<MicrosoftDynamicsCRMbulkdeletefailure> TemplateBulkDeleteFailures { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "createdonbehalfby")] public MicrosoftDynamicsCRMsystemuser Createdonbehalfby { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "owningteam")] public MicrosoftDynamicsCRMteam Owningteam { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "template_activity_mime_attachments")] public IList<MicrosoftDynamicsCRMactivitymimeattachment> TemplateActivityMimeAttachments { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "ownerid")] public MicrosoftDynamicsCRMprincipal Ownerid { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "Template_SyncErrors")] public IList<MicrosoftDynamicsCRMsyncerror> TemplateSyncErrors { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "owninguser")] public MicrosoftDynamicsCRMsystemuser Owninguser { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "Template_Organization")] public IList<MicrosoftDynamicsCRMorganization> TemplateOrganization { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "modifiedonbehalfby")] public MicrosoftDynamicsCRMsystemuser Modifiedonbehalfby { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "Email_EmailTemplate")] public IList<MicrosoftDynamicsCRMemail> EmailEmailTemplate { get; set; } } }
46.870213
2,981
0.637932
[ "Apache-2.0" ]
GeorgeWalker/jag-pill-press-registry
pill-press-interfaces/Dynamics-Autorest/Models/MicrosoftDynamicsCRMtemplate.cs
22,029
C#
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated> using System; using System.Collections.Generic; #nullable disable namespace T0001 { public partial class TempEbsResult { public DateTime TransactionDate { get; set; } public string Attribute11 { get; set; } public decimal? TransactionSourceId { get; set; } public string SubinventoryCode { get; set; } public decimal? LocatorId { get; set; } public decimal? InventoryItemId { get; set; } public string Attribute7 { get; set; } public decimal? Qty1 { get; set; } public decimal? Qty2 { get; set; } } }
33.47619
97
0.631579
[ "MIT" ]
twoutlook/BlazorServerDbContextExample
BlazorServerEFCoreSample/T0001/TempEbsResult.cs
705
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Github.Domain; using Github.Models; using Microsoft.AspNetCore.Mvc; namespace Github.App.Controllers { [Route("api/[controller]")] [ApiController] public class GithubController : ControllerBase { private readonly DomainService _domain = new DomainService(); // GET 3 deep followers id search [HttpGet("/github/follower/{githubId}")] public async Task<ActionResult<IEnumerable<User>>> FindFollowersByGithubId(long githubId) { var followers = (await _domain.FindFollowersByGithubId(githubId, 3)).ToList(); if (!followers.Any()) { return new List<User> { new User { Login = "Error: User not found", Id = -1 }}; } return followers; } // GET 3 deep followers username search [HttpGet("/github/followers/{username}")] public async Task<ActionResult<IEnumerable<User>>> FindFollowersByUsername(string username) { var followers = (await _domain.FindFollowersByUsername(username, 3)).ToList(); if (!followers.Any()) { return new List<User> { new User { Login = "Error: User not found", Id = -1 }}; } return followers; } // GET 1 deep followers id search [HttpGet("/github/singlefollower/{githubId}")] public async Task<ActionResult<IEnumerable<User>>> FindFollowersByGithubIdSingle(long githubId) { var followers = (await _domain.FindFollowersByGithubId(githubId, 1)).ToList(); if (!followers.Any()) { return new List<User> { new User { Login = "Error: User not found", Id = -1 }}; } return followers; } // GET 1 deep followers username search [HttpGet("/github/singlefollowers/{username}")] public async Task<ActionResult<IEnumerable<User>>> FindFollowersByUsernameSingle(string username) { var followers = (await _domain.FindFollowersByUsername(username, 1)).ToList(); if (!followers.Any()) { return new List<User> { new User { Login = "Error: User not found", Id = -1 }}; } return followers; } // GET 3 deep repos id search [HttpGet("/github/repo/{githubId}")] public async Task<ActionResult<IEnumerable<Repo>>> FindReposByGithubId(long githubId) { var repos = (await _domain.FindReposByGithubId(githubId, 3)).ToList(); if (!repos.Any()) { return new List<Repo> { new Repo { Name = "Error: User not found", Id = -1 }}; } return repos; } // GET 3 deep repos username search [HttpGet("/github/repos/{username}")] public async Task<ActionResult<IEnumerable<Repo>>> FindReposByUsername(string username) { var repos = (await _domain.FindReposByUsername(username, 3)).ToList(); if (!repos.Any()) { return new List<Repo> { new Repo { Name = "Error: User not found", Id = -1 }}; } return repos; } // GET 1 deep repos id search [HttpGet("/github/singlerepo/{githubId}")] public async Task<ActionResult<IEnumerable<Repo>>> FindReposByGithubIdSingle(long githubId) { var repos = (await _domain.FindReposByGithubId(githubId, 1)).ToList(); if (!repos.Any()) { return new List<Repo> { new Repo { Name = "Error: User not found", Id = -1 }}; } return repos; } // GET 1 deep repos username search [HttpGet("/github/singlerepos/{username}")] public async Task<ActionResult<IEnumerable<Repo>>> FindReposByUsernameSingle(string username) { var repos = (await _domain.FindReposByUsername(username, 1)).ToList(); if (!repos.Any()) { return new List<Repo> { new Repo { Name = "Error: User not found", Id = -1 }}; } return repos; } } }
34.176923
105
0.546703
[ "MIT" ]
Snepsts/github
Github/Controllers/GithubController.cs
4,445
C#
namespace Microsoft.Maui { public interface IViewHandler { void SetMauiContext(IMauiContext mauiContext); void SetVirtualView(IView view); void UpdateValue(string property); void DisconnectHandler(); object? NativeView { get; } IView? VirtualView { get; } bool HasContainer { get; set; } Size GetDesiredSize(double widthConstraint, double heightConstraint); void SetFrame(Rectangle frame); } }
27.6
71
0.758454
[ "MIT" ]
renovate-testing/test-9463-cakefile-maui
src/Core/src/Handlers/IViewHandler.cs
414
C#
using Amazon.JSII.Runtime.Deputy; [assembly: JsiiAssembly("@alicloud/ros-cdk-fnf", "1.0.3", "alicloud-ros-cdk-fnf-1.0.3.tgz")]
32
92
0.710938
[ "Apache-2.0" ]
aliyun/Resource-Orchestration-Service-Cloud-Development-K
multiple-languages/dotnet/AlibabaCloud.SDK.ROS.CDK.Fnf/AssemblyInfo.cs
128
C#
using Pims.Api.Areas.Project.Controllers; using Pims.Core.Extensions; using Pims.Core.Test; using Pims.Dal.Security; using System.Diagnostics.CodeAnalysis; using Xunit; namespace Pims.Api.Test.Routes.Project { /// <summary> /// WorkflowControllerTest class, provides a way to test endpoint routes. /// </summary> [Trait("category", "unit")] [Trait("category", "api")] [Trait("area", "projects")] [Trait("group", "project")] [Trait("group", "route")] [ExcludeFromCodeCoverage] public class WorkflowControllerTest { #region Variables #endregion #region Constructors public WorkflowControllerTest() { } #endregion #region Tests [Fact] public void Workflow_Route() { // Arrange // Act // Assert var type = typeof(WorkflowController); type.HasArea("projects"); type.HasRoute("[area]/workflows"); type.HasRoute("v{version:apiVersion}/[area]/workflows"); type.HasApiVersion("1.0"); type.HasAuthorize(); } [Fact] public void GetWorkflow_Route() { // Arrange var endpoint = typeof(WorkflowController).FindMethod(nameof(WorkflowController.GetWorkflowStatus), typeof(string)); // Act // Assert Assert.NotNull(endpoint); endpoint.HasGet("{workflowCode}/status"); endpoint.HasPermissions(Permissions.ProjectView); } [Fact] public void GetTasksForWorkflow_Code_Route() { // Arrange var endpoint = typeof(WorkflowController).FindMethod(nameof(WorkflowController.GetWorkflowTasks), typeof(string)); // Act // Assert Assert.NotNull(endpoint); endpoint.HasGet("{workflowCode}/tasks"); endpoint.HasPermissions(Permissions.ProjectView); } #endregion } }
27.849315
127
0.577472
[ "Apache-2.0" ]
Bruce451/PIMS
backend/tests/unit/api/Routes/Project/WorkflowControllerTest.cs
2,033
C#
using Microsoft.Extensions.DependencyInjection; namespace Cpnucleo.Domain.Configuration; public static class DomainConfig { public static void AddDomainSetup(this IServiceCollection services) { } }
19.363636
71
0.788732
[ "MIT" ]
jonathanperis/cpnucleo
src/Cpnucleo.Domain/Configuration/DomainConfig.cs
215
C#
using System; using System.Threading.Tasks; namespace Telega.CallMiddleware { sealed class FloodMiddleware : ITgCallMiddleware { DateTime _unlockTimestamp; public TgCallHandler<T> Handle<T>(TgCallHandler<T> next) => async func => { var lockSpan = _unlockTimestamp - DateTime.Now; if (lockSpan > TimeSpan.Zero) { throw new TgFloodException(lockSpan); } var receive = await next(func).ConfigureAwait(false); async Task<T> ReceiveWrapper() { try { return await receive.ConfigureAwait(false); } catch (TgFloodException e) { _unlockTimestamp = DateTime.Now + e.Delay; throw; } } return ReceiveWrapper(); }; } }
29.862069
83
0.535797
[ "MIT" ]
TelegramFileCloud/Telega
Telega/CallMiddleware/FloodMiddleware.cs
866
C#
using System; using System.Runtime.InteropServices; using System.Text; namespace Mezzo.Interop { [StructLayout(LayoutKind.Sequential)] public unsafe readonly struct CString { private readonly byte* _pointer; public CString(byte* pointer) => _pointer = pointer; public CString(nint address) => _pointer = (byte*)address; public CString(byte* pointer, int capacity, string value) : this(pointer) { SetValue(capacity, value); } public CString(byte* pointer, int capacity, ReadOnlySpan<char> chars) : this(pointer) { SetValue(capacity, chars); } public nint Address => (nint)_pointer; public bool IsValid => Address != 0; public static int GetCapacity(int length) { return Encoding.UTF8.GetMaxByteCount(length) + 1; } public int GetLength(int capacity = int.MaxValue) { if (!IsValid) { throw new NullPointerException(); } for (int i = 0; i < capacity; i++) { if (*(_pointer + i) == 0) { return i; } } return 0; } public Span<char> GetValue(Span<char> buffer) { if (!IsValid) { throw new NullPointerException(); } return buffer.Slice(0, Encoding.UTF8.GetChars(AsSpan(buffer.Length * sizeof(char)), buffer)); } private void SetValue(int capacity, ReadOnlySpan<char> chars) { if (!IsValid) { throw new NullPointerException(); } var bytes = new Span<byte>(_pointer, capacity); int length = Encoding.UTF8.GetBytes(chars, bytes[0..^1]); bytes[length] = 0; } public Span<byte> AsSpan(int capacity = int.MaxValue) { if (!IsValid) { throw new NullPointerException(); } return new Span<byte>(_pointer, GetLength(capacity)); } public override string ToString() { if (!IsValid) { throw new NullPointerException(); } return Marshal.PtrToStringUTF8(Address) ?? ""; } public static implicit operator CString(byte* pointer) => new(pointer); public static implicit operator byte*(CString cstring) => cstring._pointer; } }
27.806452
105
0.513921
[ "MIT" ]
TechInterMezzo/Mezzo.NET
src/Mezzo.Interop/CString.cs
2,588
C#
/* * This project is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ * Any copyright is dedicated to the NominalNimbus. * https://github.com/NominalNimbus */ using System; namespace Com.Lmax.Api.Internal.Xml { public interface IStructuredWriter { IStructuredWriter StartElement(string name); IStructuredWriter EndElement(string name); IStructuredWriter WriteEmptyTag(string name); IStructuredWriter ValueUTF8(string name, string value); IStructuredWriter ValueOrEmpty(string name, string value); IStructuredWriter ValueOrNone(string name, string value); IStructuredWriter ValueOrEmpty(string name, long? value); IStructuredWriter ValueOrNone(string name, long? value); IStructuredWriter ValueOrEmpty(string name, decimal? value); IStructuredWriter ValueOrNone(string name, decimal? value); IStructuredWriter ValueOrEmpty(string name, bool value); } }
33.470588
76
0.689807
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
NominalNimbus/ServiceNimbus
ApiLibraries/LmaxClientLibrary/Api/Internal/Xml/IStructuredWriter.cs
1,140
C#
using System; using System.Reflection; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using Microsoft.SmartDevice.Connectivity.Interface; using Microsoft.SmartDevice.MultiTargeting.Connectivity; using System.Net; namespace wptool { class wptool { static int Main(string[] args) { if (args.Length == 0) { return showHelp(); } string command = null; string wpsdk = null; string udid = null; Guid appid = Guid.Empty; int i; for (i = 0; i < args.Length; i++) { if (args[i] == "--wpsdk") { if (i + 1 < args.Length) { wpsdk = args[++i]; } } else if (command == null) { command = args[i]; if (command == "connect" && i + 1 < args.Length) { udid = args[++i]; } else if (command == "launch" && i + 1 < args.Length) { udid = args[++i]; string rawAppId = args[++i]; try { appid = Guid.Parse(rawAppId); } catch (FormatException fe) { return showHelp("Invalid app GUID format: " + rawAppId); } } } } if (wpsdk == null) { wpsdk = "10.0"; } else { // trim whatever version number they pass in to 2 digits string[] parts = wpsdk.Split(new Char [] {'.'}); wpsdk = ""; i = 0; while (i < 2) { if (wpsdk.Length > 0) { wpsdk += '.'; } if (i < parts.Length) { wpsdk += parts[i]; } else { wpsdk += '0'; } i++; } } if (!wpsdk.Equals("10.0") && !wpsdk.Equals("8.1")) { return showHelp("Unsupported wpsdk value. Please use '10.0' or '8.1'."); } int localeId = CultureInfo.CurrentUICulture.LCID; MultiTargetingConnectivity multiTargetingConnectivity = new MultiTargetingConnectivity(localeId); Collection<ConnectableDevice> devices = multiTargetingConnectivity.GetConnectableDevices(); List<ConnectableDevice> deviceList = new List<ConnectableDevice>(); i = 0; foreach (ConnectableDevice dev in devices) { // Filter to device and emulators that match the given SDK. We use 6.3 Version as the marker for 8.1 emus, assume rest are 10.0 string versionString = dev.Version.ToString(); if (!dev.IsEmulator() || (wpsdk == "8.1" && versionString.Equals("6.3")) || (wpsdk == "10.0" && !versionString.Equals("6.3"))) { deviceList.Add(dev); i++; } } if (command == "enumerate") { int id = 0; int j = 0; Console.WriteLine("{"); Console.WriteLine("\t\"devices\": ["); foreach (ConnectableDevice dev in deviceList) { string versionString = dev.Version.ToString(); if (!dev.IsEmulator()) { if (j > 0) { Console.WriteLine(","); } string sdk = "null"; if (versionString == "6.3") { sdk = "\"8.1\""; } else if (versionString == "10.0") { sdk = "\"10.0\""; // skip invalid device } else if (versionString.StartsWith("2147483647")) { continue; } Console.WriteLine("\t\t{\n"); Console.WriteLine("\t\t\t\"name\": \"" + dev.Name.Replace("\"", "\\\"") + "\","); Console.WriteLine("\t\t\t\"udid\": " + id + ","); Console.WriteLine("\t\t\t\"index\": " + id + ","); Console.WriteLine("\t\t\t\"version\": \"" + versionString + "\","); // windows 8.1: "6.3", windows 10: "10.0" Console.WriteLine("\t\t\t\"wpsdk\": " + sdk); Console.Write("\t\t}"); j++; } id++; } Console.WriteLine("\n\t],"); id = 0; j = 0; Console.WriteLine("\t\"emulators\": ["); foreach (ConnectableDevice dev in deviceList) { if (dev.IsEmulator()) { if (j > 0) { Console.WriteLine(","); } Console.WriteLine("\t\t{\n"); Console.WriteLine("\t\t\t\"name\": \"" + dev.Name.Replace("\"", "\\\"") + "\","); Console.WriteLine("\t\t\t\"udid\": \"" + wpsdk.Replace('.', '-') + "-" + id + "\","); Console.WriteLine("\t\t\t\"index\": " + id + ","); Console.WriteLine("\t\t\t\"guid\": \"" + dev.Id + "\","); Console.WriteLine("\t\t\t\"version\": \"" + dev.Version + "\","); // 6.3 for 8.1 emulators, 6.4 for 10 emulators, 2147483647.2147483647.2147483647.2147483647 for device Console.WriteLine("\t\t\t\"uapVersion\": \"" + dev.UapVersion + "\","); // blank/empty for 8.1 emulators and device, 10.0.10586.0 for win 10 emulators Console.WriteLine("\t\t\t\"wpsdk\": \"" + wpsdk + "\""); Console.Write("\t\t}"); j++; } id++; } Console.WriteLine("\n\t]"); Console.WriteLine("}"); return 0; } // This won't just connect, it will launch the emulator! if (command == "connect" || command == "launch") { if (udid == null) { return showHelp("Missing device/emulator UDID"); } // TODO Validate that the udid is either our generated udid (i.e. 10-0-1), or it's GUID, or it's an integer index value! int id = 0; // Search devices for udid! ConnectableDevice connectableDevice = null; foreach (ConnectableDevice dev in deviceList) { // Is it a matching GUID, matching UDID or matching Index value? if (dev.Id.Equals(udid) || (wpsdk.Replace('.', '-') + "-" + id).Equals(udid) || udid.Equals(id.ToString())) { connectableDevice = dev; break; } id++; } if (connectableDevice == null) { return showHelp(String.Format("Invalid device UDID '{0:D}'", udid)); } try { IDevice device = connectableDevice.Connect(); if (command == "launch") { IRemoteApplication app = device.GetApplication(appid); app.Launch(); Console.WriteLine("{"); Console.WriteLine("\t\"success\": true"); Console.WriteLine("}"); } else { try { string destinationIp; string sourceIp; int destinationPort; device.GetEndPoints(0, out sourceIp, out destinationIp, out destinationPort); var address = IPAddress.Parse(destinationIp); ISystemInfo systemInfo = device.GetSystemInfo(); Version version = new Version(systemInfo.OSMajor, systemInfo.OSMinor, systemInfo.OSBuildNo); Console.WriteLine("{"); Console.WriteLine("\t\"success\": true,"); Console.WriteLine("\t\"ip\": \"" + address.ToString() + "\","); Console.WriteLine("\t\"port\": " + destinationPort.ToString() + ","); Console.WriteLine("\t\"osVersion\": \"" + version.ToString() + "\","); Console.WriteLine("\t\"availablePhysical\": " + systemInfo.AvailPhys.ToString() + ","); Console.WriteLine("\t\"totalPhysical\": " + systemInfo.TotalPhys.ToString() + ","); Console.WriteLine("\t\"availableVirtual\": " + systemInfo.AvailVirtual.ToString() + ","); Console.WriteLine("\t\"totalVirtual\": " + systemInfo.TotalVirtual.ToString() + ","); Console.WriteLine("\t\"architecture\": \"" + systemInfo.ProcessorArchitecture.ToString() + "\","); Console.WriteLine("\t\"instructionSet\": \"" + systemInfo.InstructionSet.ToString() + "\","); Console.WriteLine("\t\"processorCount\": " + systemInfo.NumberOfProcessors.ToString() + ""); Console.WriteLine("}"); } catch (Exception ex) { // // ConnectableDevice throws an error when connecting to a physical Windows 10 device // physical Windows 10 devices can be connected to using 127.0.0.1. // From some point of Windows 10 SDK, IDevice.GetEndPoints throws Exception for Windows Phone 8.1 device too. // Interestingly ConnectableDevice.Version returns 8.1 _or_ 6.3 in this case. // Returning ok for now because we can still connect to the device. // if (command == "connect" && !connectableDevice.IsEmulator()) { Console.WriteLine("{"); Console.WriteLine("\t\"success\": true,"); Console.WriteLine("\t\"ip\": \"127.0.0.1\","); Console.WriteLine("\t\"osVersion\": \"" + connectableDevice.Version.ToString() + "\""); Console.WriteLine("}"); return 0; } } } return 0; } catch (Exception ex) { Console.WriteLine("{"); Console.WriteLine("\t\"success\": false,"); Console.WriteLine("\t\"message\": \"" + ex.Message.Trim().Replace("\"", "\\\"") + "\""); Console.WriteLine("}"); return 1; } } if (command != null) { return showHelp(String.Format("Invalid command '{0}'", command)); } return showHelp(); } static int showHelp(string msg = "") { Console.WriteLine("Appcelerator Windows Phone Tool v1.0\n"); if (msg.Length > 0) { Console.WriteLine("ERROR: " + msg + "\n"); } Console.WriteLine("Usage:"); Console.WriteLine(" wptool <command> [--wpsdk <ver>]"); Console.WriteLine(""); Console.WriteLine("Commands:"); Console.WriteLine(" enumerate List all devices and emulators"); Console.WriteLine(" connect <udid> Connects to the specified device"); Console.WriteLine(" launch <udid> <product-guid> Connects to the specified device and launches the app with the given product guid"); Console.WriteLine(""); Console.WriteLine("Options:"); Console.WriteLine(" --wpsdk <ver> The version of the Windows Phone SDK emulators to use (e.g. '10.0', or '8.1')"); Console.WriteLine(" Defaults to Windows 10 Mobile (e.g. 10.0)"); Console.WriteLine(""); return msg.Length > 0 ? 1 : 0; } } }
34.773234
174
0.581997
[ "Apache-2.0" ]
jeffbonnes/titanium_mobile
node_modules/windowslib/wptool/wptool.cs
9,354
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public static class MonoBehaviourExtensions { public static void Activate(this MonoBehaviour mono) { mono.gameObject.SetActive(true); } public static void Deactivate(this MonoBehaviour mono) { mono.gameObject.SetActive(false); } }
20.764706
58
0.719547
[ "MIT" ]
Treyboyland/SpoopyJam2019
Assets/Scripts/MonoBehaviourExtensions.cs
355
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reactive.Linq; using System.Threading.Tasks; using System.Windows.Input; using Prism.Commands; using Prism.Ioc; using WDE.Common.Managers; using WDE.Module.Attributes; using WDE.MVVM; using WDE.SmartScriptEditor.Models; using PropertyChanged.SourceGenerator; using WDE.Common.Disposables; using WDE.Common.Utils; using WDE.MVVM.Observable; namespace WDE.SmartScriptEditor.Editor.ViewModels; [AutoRegister] public partial class VariablePickerViewModel : ObservableBase, IDialog { private readonly GlobalVariableType type; private readonly SmartScriptBase script; public VariablePickerViewModel(GlobalVariableType type, SmartScriptBase script, long? initial) { this.type = type; this.script = script; Items = new(script.GlobalVariables.Where(gv => gv.VariableType == type) .OrderBy(i => i.Key) .Distinct(Compare.By<GlobalVariable, long>(i => i!.Key)) .Select(gv => new VariableItemViewModel(gv))); SelectedItem = initial.HasValue ? Items.FirstOrDefault(i => i.Id == initial) : null; if (SelectedItem == null && initial != null) { var phantom = VariableItemViewModel.CreatePhantom(initial.Value); Items.Add(phantom); SelectedItem = phantom; } Cancel = new DelegateCommand(() => { CloseCancel?.Invoke(); }); Accept = new DelegateCommand(() => { var dict = Items.Where(i => !i.IsPhantom).SafeToDictionary(i => i.OriginalId ?? i.Id, i => i); for (var i = script.GlobalVariables.Count - 1; i >= 0; i--) { var existing = script.GlobalVariables[i]; if (existing.VariableType == type) { if (dict.TryGetValue(existing.Key, out var item)) { existing.Key = item.Id; existing.Name = item.Name; existing.Comment = item.Comment; dict.Remove(item.OriginalId ?? item.Id); } else script.GlobalVariables.RemoveAt(i); } } foreach (var pair in dict) { script.GlobalVariables.Add(new GlobalVariable() { Key = pair.Key, Name = pair.Value.Name, Comment = pair.Value.Comment, VariableType = type }); } CloseOk?.Invoke(); }); AddItemCommand = new DelegateCommand(() => { var phantom = VariableItemViewModel.CreatePhantom((Items.Count > 0 ? Items.Max(i => i.Id) : 0) + 1); Items.Add(phantom); SelectedItem = phantom; }); RemoveItemCommand = new DelegateCommand(() => { if (SelectedItem != null) { Items.Remove(SelectedItem); SelectedItem = null; } }, () => SelectedItem != null).ObservesProperty(() => SelectedItem); Items.DisposeOnRemove(); AutoDispose(new ActionDisposable(() => Items.Clear())); } [Notify] private VariableItemViewModel? selectedItem; public ObservableCollection<VariableItemViewModel> Items { get; } public DelegateCommand AddItemCommand { get; } public DelegateCommand RemoveItemCommand { get; } public int DesiredWidth => 700; public int DesiredHeight => 500; public string Title => "Pick a variable"; public bool Resizeable => true; public ICommand Accept { get; set; } public ICommand Cancel { get; set; } public event Action? CloseCancel; public event Action? CloseOk; } public partial class VariableItemViewModel : ObservableBase { [Notify] private long id; [Notify] private string name; [Notify] private string? comment; [Notify] private bool isPhantom; public readonly long? OriginalId; private VariableItemViewModel(long id, string name) { this.id = id; this.name = name; this.comment = null; isPhantom = true; AutoDispose(this.ToObservable(o => o.Name) .Skip(1) .SubscribeAction(_ => IsPhantom = false)); } public VariableItemViewModel(GlobalVariable variable) { id = variable.Key; name = variable.Name; comment = variable.Comment; OriginalId = id; } public static VariableItemViewModel CreatePhantom(long id) { return new VariableItemViewModel(id, "(unnamed)"); } } public interface IVariablePickerService { Task<long?> PickVariable(GlobalVariableType type, SmartScriptBase script, long? currentValue); } [AutoRegister] [SingleInstance] public class VariablePickerService : IVariablePickerService { private readonly IWindowManager windowManager; private readonly IContainerProvider containerProvider; public VariablePickerService(IWindowManager windowManager, IContainerProvider containerProvider) { this.windowManager = windowManager; this.containerProvider = containerProvider; } public async Task<long?> PickVariable(GlobalVariableType type, SmartScriptBase script, long? currentValue) { var vm = containerProvider.Resolve<VariablePickerViewModel>((typeof(GlobalVariableType), type), (typeof(SmartScriptBase), script), (typeof(long?), currentValue)); if (await windowManager.ShowDialog(vm)) { return vm.SelectedItem?.Id; } return null; } }
31.715847
112
0.605445
[ "Unlicense" ]
lyosky/WoWDatabaseEditor
WDE.SmartScriptEditor/Editor/ViewModels/VariablePickerViewModel.cs
5,804
C#
//////////////////////////////////////////////////////////////////////////////// //EF Core Provider for LCPI OLE DB. // IBProvider and Contributors. 05.06.2021. namespace Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.Basement.EF.Root.Query.Local.Expressions.Converts.MasterCode{ //////////////////////////////////////////////////////////////////////////////// using T_SOURCE =System.Byte; using T_TARGET =System.Byte; //////////////////////////////////////////////////////////////////////////////// //class Convert_MasterCode__Byte__Byte static class Convert_MasterCode__Byte__Byte { public static T_TARGET Exec(T_SOURCE v) { return v; }//Exec };//class Convert_MasterCode__Byte__Byte //////////////////////////////////////////////////////////////////////////////// }//namespace Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.Basement.EF.Root.Query.Local.Expressions.Converts.MasterCode
34.851852
121
0.501594
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Code/Provider/Source/Basement/EF/Root/Query/Local/Expressions/Converts/MasterCode/Byte/Convert_MasterCode__Byte__Byte.cs
943
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Cube : MonoBehaviour { public MeshRenderer Renderer; [SerializeField] Material cubeMaterial; [SerializeField] protected float speed = 10f; void Start() { transform.position = new Vector3(0, 0, 0); transform.localScale = Vector3.one * 1.5f; //Material material = Renderer.material; //material.color = new Color(1.0f, 1.0f, 0.3f, 0.4f); } void Update() { transform.Rotate(20.0f * Time.deltaTime * speed, 0.0f, 0.0f); } }
23.384615
69
0.625
[ "MIT" ]
autoshgame/Create-With-Code-Unit2
Assets/ModTheCube/Cube.cs
610
C#
using Bonsai.Expressions; using OpenCV.Net; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Linq.Expressions; using System.Reactive.Linq; namespace Bonsai.Dsp { /// <summary> /// Represents an operator that converts each array or collection in the sequence into /// a managed array. /// </summary> [WorkflowElementCategory(ElementCategory.Transform)] [Description("Converts each array or collection in the sequence into a managed array.")] public class ConvertToArray : SelectBuilder { /// <summary> /// Gets or sets the bit depth of each element in the input array. /// </summary> /// <remarks> /// If this property is not specified, the default depth will be automatically /// selected based on the type of the input array elements. /// </remarks> [TypeConverter(typeof(DepthConverter))] [Description("The bit depth of each element in the input array.")] public Depth? Depth { get; set; } /// <summary> /// Returns the expression that maps the array or collection into /// a managed array. /// </summary> /// <inheritdoc/> protected override Expression BuildSelector(Expression expression) { var depth = Depth; var arrayType = expression.Type; if (depth.HasValue) { var elementType = GetElementType(depth.Value); var depthExpression = Expression.Constant(depth.Value); return Expression.Call(typeof(ConvertToArray), nameof(Process), new[] { arrayType, elementType }, expression, depthExpression); } else if (!typeof(Arr).IsAssignableFrom(arrayType)) { var elementType = ExpressionHelper.GetGenericTypeBindings(typeof(IEnumerable<>), expression.Type).FirstOrDefault(); if (elementType == null) throw new InvalidOperationException("The input buffer must be an array or enumerable type."); return Expression.Call(typeof(Enumerable), nameof(Enumerable.ToArray), new[] { elementType }, expression); } else return Expression.Call(typeof(ConvertToArray), nameof(Process), new[] { arrayType }, expression); } static Type GetElementType(Depth depth) { switch (depth) { case OpenCV.Net.Depth.U16: return typeof(ushort); case OpenCV.Net.Depth.S16: return typeof(short); case OpenCV.Net.Depth.S32: return typeof(int); case OpenCV.Net.Depth.F32: return typeof(float); case OpenCV.Net.Depth.F64: return typeof(double); case OpenCV.Net.Depth.U8: case OpenCV.Net.Depth.S8: case OpenCV.Net.Depth.UserType: default: return typeof(byte); } } static byte[] Process<TArray>(TArray input) where TArray : Arr { var inputHeader = input.GetMat(); return ArrHelper.ToArray(inputHeader); } static TElement[] Process<TArray, TElement>(TArray input, Depth depth) where TArray : Arr where TElement : struct { var inputHeader = input.GetMat(); var output = new TElement[inputHeader.Rows * inputHeader.Cols]; using (var outputHeader = Mat.CreateMatHeader(output, inputHeader.Rows, inputHeader.Cols, depth, 1)) { CV.Convert(inputHeader, outputHeader); } return output; } } }
40.817204
144
0.585353
[ "MIT" ]
glopesdev/bonsai
Bonsai.Dsp/ConvertToArray.cs
3,798
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ZigBeeNet.Security; using ZigBeeNet.ZCL.Clusters.IasAce; using ZigBeeNet.ZCL.Field; using ZigBeeNet.ZCL.Protocol; namespace ZigBeeNet.ZCL.Clusters.IasAce { /// <summary> /// Panel Status Changed Command value object class. /// /// Cluster: IAS ACE. Command ID 0x04 is sent FROM the server. /// This command is a specific command used for the IAS ACE cluster. /// /// This command updates ACE clients in the system of changes to panel status recorded by the /// ACE server (e.g., IAS CIE device).Sending the Panel Status Changed command (vs.the Get /// Panel Status and Get Panel Status Response method) is generally useful only when there /// are IAS ACE clients that data poll within the retry timeout of the network (e.g., less /// than 7.68 seconds). <br> An IAS ACE server shall send a Panel Status Changed command upon /// a change to the IAS CIE’s panel status (e.g., Disarmed to Arming Away/Stay/Night, /// Arming Away/Stay/Night to Armed, Armed to Disarmed) as defined in the Panel Status /// field. <br> When Panel Status is Arming Away/Stay/Night, an IAS ACE server should send /// Panel Status Changed commands every second in order to update the Seconds Remaining. In /// some markets (e.g., North America), the final 10 seconds of the Arming Away/Stay/Night /// sequence requires a separate audible notification (e.g., a double tone). /// /// Code is auto-generated. Modifications may be overwritten! /// </summary> public class PanelStatusChangedCommand : ZclCommand { /// <summary> /// The cluster ID to which this command belongs. /// </summary> public const ushort CLUSTER_ID = 0x0501; /// <summary> /// The command ID. /// </summary> public const byte COMMAND_ID = 0x04; /// <summary> /// Panel Status command message field. /// /// Indicates the number of seconds remaining for the server to be in the state /// indicated in the PanelStatus parameter. The SecondsRemaining parameter shall be /// provided if the PanelStatus parameter has a value of 0x04 (Exit delay) or 0x05 /// (Entry delay). /// The default value shall be 0x00. /// </summary> public byte PanelStatus { get; set; } /// <summary> /// Seconds Remaining command message field. /// </summary> public byte SecondsRemaining { get; set; } /// <summary> /// Audible Notification command message field. /// </summary> public byte AudibleNotification { get; set; } /// <summary> /// Alarm Status command message field. /// </summary> public byte AlarmStatus { get; set; } /// <summary> /// Default constructor. /// </summary> public PanelStatusChangedCommand() { ClusterId = CLUSTER_ID; CommandId = COMMAND_ID; GenericCommand = false; CommandDirection = ZclCommandDirection.SERVER_TO_CLIENT; } internal override void Serialize(ZclFieldSerializer serializer) { serializer.Serialize(PanelStatus, DataType.ENUMERATION_8_BIT); serializer.Serialize(SecondsRemaining, DataType.UNSIGNED_8_BIT_INTEGER); serializer.Serialize(AudibleNotification, DataType.ENUMERATION_8_BIT); serializer.Serialize(AlarmStatus, DataType.ENUMERATION_8_BIT); } internal override void Deserialize(ZclFieldDeserializer deserializer) { PanelStatus = deserializer.Deserialize<byte>(DataType.ENUMERATION_8_BIT); SecondsRemaining = deserializer.Deserialize<byte>(DataType.UNSIGNED_8_BIT_INTEGER); AudibleNotification = deserializer.Deserialize<byte>(DataType.ENUMERATION_8_BIT); AlarmStatus = deserializer.Deserialize<byte>(DataType.ENUMERATION_8_BIT); } public override string ToString() { var builder = new StringBuilder(); builder.Append("PanelStatusChangedCommand ["); builder.Append(base.ToString()); builder.Append(", PanelStatus="); builder.Append(PanelStatus); builder.Append(", SecondsRemaining="); builder.Append(SecondsRemaining); builder.Append(", AudibleNotification="); builder.Append(AudibleNotification); builder.Append(", AlarmStatus="); builder.Append(AlarmStatus); builder.Append(']'); return builder.ToString(); } } }
40.161017
97
0.640641
[ "EPL-1.0" ]
JanneMattila/ZigbeeNet
libraries/ZigBeeNet/ZCL/Clusters/IasAce/PanelStatusChangedCommand.cs
4,741
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AWSSDK.XRay")] [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS X-Ray. AWS X-Ray helps developers analyze and debug distributed applications. With X-Ray, you can understand how your application and its underlying services are performing to identify and troubleshoot the root cause of performance issues and errors.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.3")] [assembly: AssemblyFileVersion("3.3.102.68")]
50.125
334
0.756234
[ "Apache-2.0" ]
alefranz/aws-sdk-net
sdk/code-analysis/ServiceAnalysis/XRay/Properties/AssemblyInfo.cs
1,604
C#
// Generated on 12/11/2014 19:02:01 using System; using System.Collections.Generic; using System.Linq; using BlueSheep.Common.Protocol.Types; using BlueSheep.Common.IO; using BlueSheep.Engine.Types; namespace BlueSheep.Common.Protocol.Messages { public class KrosmasterAuthTokenMessage : Message { public new const uint ID =6351; public override uint ProtocolID { get { return ID; } } public string token; public KrosmasterAuthTokenMessage() { } public KrosmasterAuthTokenMessage(string token) { this.token = token; } public override void Serialize(BigEndianWriter writer) { writer.WriteUTF(token); } public override void Deserialize(BigEndianReader reader) { token = reader.ReadUTF(); } } }
18.403846
64
0.572623
[ "MIT" ]
Sadikk/BlueSheep
BlueSheep/Common/Protocol/messages/web/krosmaster/KrosmasterAuthTokenMessage.cs
957
C#
using System.Windows.Forms; using System.Collections.Generic; using System.Linq; using System; namespace GoldBoxExplorer.Lib.Plugins.DaxEcl { public class EclFileViewer : IGoldBoxViewer { public event EventHandler<ChangeFileEventArgs> ChangeSelectedFile; private readonly DaxEclFile _file; private TabControl tab; private int findNext = 0; public EclFileViewer(DaxEclFile file) { _file = file; } // dynamically create ECL code listing when the tab is clicked on private void ECLTabControlUnloadDeselected(Object sender, TabControlEventArgs e) { if (e.TabPage != null && e.TabPage.Controls.Find("codepanel", false).Length > 0) { EmptyECLCodePanel(e.TabPage); } } // dynamically create ECL code listing when the tab is clicked on private void ECLTabControlLoadSelected(Object sender, TabControlEventArgs e) { if (e.TabPage != null && e.TabPage.Controls.Find("codepanel", false).Length > 0) { FillECLCodePanel(e.TabPage); } } public Control GetControl() { tab = new TabControl { Dock = DockStyle.Fill }; Control bookmarkedRow = null; // the row we want to start at foreach (var ecl in _file.eclDumps) { var page = new TabPage(ecl._blockName); Panel codePanel = (Panel) ViewerHelper.CreatePanel(); codePanel.Name = "codepanel"; codePanel.Tag = ecl; //page.AutoScroll = true; page.Controls.Add(codePanel); // fill the code panel with the decoded ecl code bookmarkedRow = FillECLCodePanel(page); // add a search bar and 'select all' button to the top of the ecl listing var selectAll = ViewerHelper.CreateButton(); selectAll.Text = "Copy to clipboard"; selectAll.MouseClick += selectAllRows; selectAll.Dock = DockStyle.Right; var findNext = ViewerHelper.CreateButton(); findNext.Text = "find next"; findNext.MouseClick += searchEclNext; findNext.Dock = DockStyle.Right; TextBox headerText = (TextBox) ViewerHelper.CreateTextBox(); headerText.ReadOnly = false; headerText.Text = "Type text to find"; headerText.TextChanged += searchEcl; headerText.KeyDown += searchEclKeyPressed; headerText.Dock = DockStyle.Fill; var row1 = ViewerHelper.CreateRow(); page.Controls.Add(row1); row1.Controls.Add(headerText); row1.Controls.Add(findNext); row1.Controls.Add(selectAll); tab.TabPages.Add(page); if (page.Text == ChangeFileEventArgs.currentDaxId.ToString()) { tab.SelectedTab = page; codePanel.ScrollControlIntoView(bookmarkedRow); } } var stringPage = new TabPage("ECL Text"); stringPage.AutoScroll = true; var control = ViewerHelper.CreateTextBoxMultiline(); control.Text = _file.ToString(); stringPage.Controls.Add(control); tab.TabPages.Add(stringPage); tab.Selected += ECLTabControlLoadSelected; tab.Deselected += ECLTabControlUnloadDeselected; return tab; } private static void EmptyECLCodePanel(TabPage tabPage) { Panel codePanel = (Panel)tabPage.Controls.Find("codepanel", false)[0]; codePanel.Controls.Clear(); } private static Control FillECLCodePanel(TabPage page) { // this can take a while, so make sure the cursor is set to wait Application.UseWaitCursor = true; Application.DoEvents(); Control bookmarkedRow = null; Panel codePanel = (Panel)page.Controls.Find("codepanel", false)[0]; EclDump.EclDump ecl = (EclDump.EclDump) codePanel.Tag; // decode ecl files, and put each line in its own textbox foreach (var eclAddr in ecl.decodedEcl.Keys.Reverse()) { var eclText = ViewerHelper.CreateTextBox(); eclText.Text = ecl.decodedEcl[eclAddr]; eclText.Dock = DockStyle.Fill; var eclAnnotation = ViewerHelper.CreateTextBox(); if (ecl.annotations.ContainsKey(eclAddr)) { eclAnnotation.Text = ecl.annotations[eclAddr]; eclText.BackColor = System.Drawing.Color.LightBlue; eclAnnotation.BackColor = System.Drawing.Color.LightBlue; } eclAnnotation.Width = 300; eclAnnotation.Dock = DockStyle.Right; var row = ViewerHelper.CreateRow(); codePanel.Controls.Add(row); row.Controls.Add(eclText); row.Controls.Add(eclAnnotation); if (ChangeFileEventArgs.targetPlace != "" && eclAnnotation.Text.Contains(ChangeFileEventArgs.targetPlace) && page.Text == ChangeFileEventArgs.currentDaxId.ToString()) bookmarkedRow = row; } Application.UseWaitCursor = false; Application.DoEvents(); return bookmarkedRow; } public float Zoom { get; set; } public void findInEcl(object sender, int index = 0) { var findTextBox = (TextBox)sender; var text = findTextBox.Text; Panel eclListing = (Panel)findTextBox.Parent.Parent.Controls[0]; string textFound = ""; // clear all selections foreach (var c in eclListing.Controls) { var co = (System.Windows.Forms.Panel)c; var tb = (System.Windows.Forms.TextBox)co.Controls[0]; tb.HideSelection = true; } // search through the textboxes to find the text, select it for (int i = eclListing.Controls.Count-1; i > 0; i--) { System.Windows.Forms.Panel rowControl = (System.Windows.Forms.Panel) eclListing.Controls[i]; System.Windows.Forms.TextBox tb = (System.Windows.Forms.TextBox)rowControl.Controls[0]; System.Windows.Forms.TextBox atb = (System.Windows.Forms.TextBox)rowControl.Controls[1]; int textStart = tb.Text.IndexOf(text, StringComparison.CurrentCultureIgnoreCase); if (textStart > -1) { if (index <= 1) { scrollIntoViewAndHighlight(text, eclListing, rowControl, tb, textStart); return; } else index--; } else { // can't find the text in the ecl code textbox, so try the annotations textbox next to it textStart = atb.Text.IndexOf(text, StringComparison.CurrentCultureIgnoreCase); if (textStart > -1) { if (index <= 1) { scrollIntoViewAndHighlight(text, eclListing, rowControl, atb, textStart); return; } else index--; } } } // nothing found! reset the find next counter findNext = 0; } private static void scrollIntoViewAndHighlight(string text, Panel eclListing, System.Windows.Forms.Panel co, System.Windows.Forms.TextBox tb, int textStart) { eclListing.ScrollControlIntoView(co); tb.Select(textStart, text.Length); tb.HideSelection = false; return; } public void searchEcl(object sender, EventArgs e) { findInEcl(sender); } public void searchEclNext(object sender, MouseEventArgs e) { var b = (System.Windows.Forms.ButtonBase)sender; findNext++; findInEcl(b.Parent.Controls[0], findNext); } void searchEclKeyPressed(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { var b = (System.Windows.Forms.TextBoxBase)sender; findNext++; findInEcl(b.Parent.Controls[0], findNext); } } public void selectAllRows(object sender, MouseEventArgs e) { // select all the ecl code in the panel and send it to the clipboard var b = (System.Windows.Forms.ButtonBase) sender; var eclListing = b.Parent.Parent.Controls[0]; string text = ""; foreach (System.Windows.Forms.Panel co in eclListing.Controls) { System.Windows.Forms.TextBox tb = (System.Windows.Forms.TextBox) co.Controls[0]; text = tb.Text + "\r\n" + text; } Clipboard.SetText(text); } public int ContainerWidth { get; set; } } }
40.327801
182
0.532154
[ "MIT" ]
bsimser/Gold-Box-Explorer
src/Common/Plugins/DaxEcl/EclFileViewer.cs
9,719
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Dns.Fluent.Models { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.Dns; using Microsoft.Azure.Management.Dns.Fluent; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.Runtime; using System.Runtime.Serialization; /// <summary> /// Defines values for RecordType. /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum RecordType { [EnumMember(Value = "A")] A, [EnumMember(Value = "AAAA")] AAAA, [EnumMember(Value = "CNAME")] CNAME, [EnumMember(Value = "MX")] MX, [EnumMember(Value = "NS")] NS, [EnumMember(Value = "PTR")] PTR, [EnumMember(Value = "SOA")] SOA, [EnumMember(Value = "SRV")] SRV, [EnumMember(Value = "TXT")] TXT } }
27.565217
74
0.621451
[ "MIT" ]
graemefoster/azure-libraries-for-net
src/ResourceManagement/Dns/Generated/Models/RecordType.cs
1,268
C#
using Microsoft.EntityFrameworkCore; using ProductMan.API.Domain.Context.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ProductMan.API.Domain.Context { public class ProductDBContext : DbContext { public DbSet<Product> Products { get; set; } public ProductDBContext(DbContextOptions<ProductDBContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.ApplyConfiguration(new ProductConfiguration()); base.OnModelCreating(modelBuilder); } } }
27.75
91
0.707207
[ "MIT" ]
aliemrahpekesen/dotnet_core_xunitWithMoq_unittest
ProductMan.API/Domain/Context/ProductDBContext.cs
668
C#
using System; using System.Collections.Generic; using System.Linq; namespace AwsTools { class TryCatch { /// <summary> /// Catch exceptions which may be deep within an aggregate exception. /// </summary> public static void Try(Action tryAction, Action<Exception> catchAction, List<Type> catchableExceptions) { try { tryAction(); } catch (Exception caughtException) { if (catchableExceptions.Any(catchableException => catchableException == caughtException.GetType())) { catchAction(caughtException); return; } if (caughtException is AggregateException aggregateException) { aggregateException = aggregateException.Flatten(); if (aggregateException.InnerExceptions != null) { Exception innerCaughtException = aggregateException .InnerExceptions .FirstOrDefault(innerException => catchableExceptions .Any(catchableException => catchableException == innerException.GetType())); if (innerCaughtException != default(Exception)) { catchAction(innerCaughtException); return; } } } throw; } } } }
32.28
115
0.484511
[ "Apache-2.0" ]
timg456789/AwsTools
AwsTools/TryCatch.cs
1,616
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("RecognizeAPI")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RecognizeAPI")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f2535455-f618-435d-9f60-927e52033f0a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.694444
84
0.74871
[ "MIT" ]
vinegreti2010/CFRFServers
RecognizeAPI/Properties/AssemblyInfo.cs
1,360
C#
using System; namespace DataImporter { /// <summary> /// This program acts as a basic driver and test harness for developers to use when testing code changes in /// the Cotton Harvester HID File Import Plugin. This is a handy method for stepping through the plugin code /// before final testing is performed with the ADAPT Visualizer. /// </summary> class Program { static void Main(string[] args) { //First, create a new instance of the Cotton Harvester HID plugin below CottonHarvesterHIDFileImportPlugin.Plugin plugin = new CottonHarvesterHIDFileImportPlugin.Plugin(); //Set the path to your test file below string dataPath = @"C:\Projects\OAGi\ADAPT\JD"; //Call the RunPlugin method, passing in the path to your test data file plugin.RunPlugin(dataPath); } } }
37.333333
112
0.660714
[ "EPL-1.0" ]
ADAPT/CottonHarvesterHIDFileImportPlugin
DataImporter/Program.cs
898
C#
using Newtonsoft.Json; namespace XCommas.Net.Objects { public class AccountTableData { [JsonProperty("account_state_entry_id")] public long AccountStateEntryId { get; set; } [JsonProperty("currency_code")] public string CurrencyCode { get; set; } [JsonProperty("currency_name")] public string CurrencyName { get; set; } [JsonProperty("currency_icon")] public string CurrencyIconUrl { get; set; } [JsonProperty("percentage")] public decimal Percentage { get; set; } [JsonProperty("position")] public decimal Position { get; set; } [JsonProperty("current_price")] public decimal CurrentPrice { get; set; } [JsonProperty("current_price_usd")] public decimal CurrentPriceUsd { get; set; } [JsonProperty("day_change_percent")] public decimal? DayChangePercent { get; set; } [JsonProperty("btc_value")] public decimal BtcValue { get; set; } [JsonProperty("usd_value")] public decimal UsdValue { get; set; } [JsonProperty("134645")] public int AccountId { get; set; } } }
35.484848
54
0.622545
[ "Unlicense" ]
Grepsy/3Commas.Net
XCommas.Net/XCommas.Net/Objects/AccountTableData.cs
1,173
C#
/* * Copyright 2017 Mikhail Shiryaev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * Product : Rapid SCADA * Module : KpModbus * Summary : Device library user interface * * Author : Mikhail Shiryaev * Created : 2012 * Modified : 2017 */ using Scada.Comm.Devices.Modbus.Protocol; using Scada.Comm.Devices.Modbus.UI; using Scada.Data.Configuration; using Scada.UI; using System; using System.Collections.Generic; using System.IO; namespace Scada.Comm.Devices { /// <summary> /// Device library user interface /// <para>Пользовательский интерфейс библиотеки КП</para> /// </summary> public class KpModbusView : KPView { /// <summary> /// Версия библиотеки КП /// </summary> internal const string KpVersion = "5.1.0.0"; /// <summary> /// Конструктор для общей настройки библиотеки КП /// </summary> public KpModbusView() : this(0) { } /// <summary> /// Конструктор для настройки конкретного КП /// </summary> public KpModbusView(int number) : base(number) { CanShowProps = true; } /// <summary> /// Описание библиотеки КП /// </summary> public override string KPDescr { get { return Localization.UseRussian ? "Взаимодействие с контроллерами по протоколу Modbus.\n\n" + "Пользовательский параметр линии связи:\n" + "TransMode - режим передачи данных (RTU, ASCII, TCP).\n\n" + "Параметр командной строки:\n" + "имя файла шаблона.\n\n" + "Команды ТУ:\n" + "определяются шаблоном (стандартные или бинарные)." : "Interacting with controllers via Modbus protocol.\n\n" + "Custom communication line parameter:\n" + "TransMode - data transmission mode (RTU, ASCII, TCP).\n\n" + "Command line parameter:\n" + "template file name.\n\n" + "Commands:\n" + "defined by template (standard or binary)."; } } /// <summary> /// Получить версию библиотеки КП /// </summary> public override string Version { get { return KpVersion; } } /// <summary> /// Получить прототипы каналов КП по умолчанию /// </summary> public override KPCnlPrototypes DefaultCnls { get { // получение имени файла шаблона устройства string templateName = KPProps == null ? "" : KPProps.CmdLine.Trim(); string fileName = AppDirs.ConfigDir + templateName; if (!File.Exists(fileName)) return null; // загрузка шаблона устройства DeviceTemplate template = new DeviceTemplate(); string errMsg; if (!template.Load(fileName, out errMsg)) throw new Exception(errMsg); // создание прототипов каналов КП KPCnlPrototypes prototypes = new KPCnlPrototypes(); List<InCnlPrototype> inCnls = prototypes.InCnls; List<CtrlCnlPrototype> ctrlCnls = prototypes.CtrlCnls; // создание прототипов входных каналов int signal = 1; foreach (ElemGroup elemGroup in template.ElemGroups) { bool isTS = elemGroup.TableType == TableTypes.DiscreteInputs || elemGroup.TableType == TableTypes.Coils; foreach (Elem elem in elemGroup.Elems) { InCnlPrototype inCnl = isTS ? new InCnlPrototype(elem.Name, BaseValues.CnlTypes.TS) : new InCnlPrototype(elem.Name, BaseValues.CnlTypes.TI); inCnl.Signal = signal++; if (isTS) { inCnl.ShowNumber = false; inCnl.UnitName = BaseValues.UnitNames.OffOn; inCnl.EvEnabled = true; inCnl.EvOnChange = true; } inCnls.Add(inCnl); } } // создание прототипов каналов управления foreach (ModbusCmd modbusCmd in template.Cmds) { CtrlCnlPrototype ctrlCnl = modbusCmd.TableType == TableTypes.Coils && modbusCmd.Multiple ? new CtrlCnlPrototype(modbusCmd.Name, BaseValues.CmdTypes.Binary) : new CtrlCnlPrototype(modbusCmd.Name, BaseValues.CmdTypes.Standard); ctrlCnl.CmdNum = modbusCmd.CmdNum; if (modbusCmd.TableType == TableTypes.Coils && !modbusCmd.Multiple) ctrlCnl.CmdValName = BaseValues.CmdValNames.OffOn; ctrlCnls.Add(ctrlCnl); } return prototypes; } } /// <summary> /// Отобразить свойства КП /// </summary> public override void ShowProps() { // загрузка словарей string errMsg; if (Localization.LoadDictionaries(AppDirs.LangDir, "KpModbus", out errMsg)) KpPhrases.Init(); else ScadaUiUtils.ShowError(errMsg); if (Number > 0) // отображение свойств КП FrmDevProps.ShowDialog(Number, KPProps, AppDirs); else // отображение редактора шаблонов устройств FrmDevTemplate.ShowDialog(AppDirs); } } }
33.840206
110
0.520792
[ "Apache-2.0" ]
JoygenZhang/Rapid-SCADA-sources
ScadaComm/OpenKPs/KpModbus/KpModbusView.cs
7,210
C#