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; namespace PsefApiOData.Models { /// <summary> /// Represents Permohonan update data. /// </summary> public class PermohonanSystemUpdate { /// <summary> /// Gets or sets the update Permohonan unique identifier. /// </summary> /// <value>The update Permohonan's unique identifier.</value> public uint PermohonanId { get; set; } /// <summary> /// Gets or sets the update reason. /// </summary> /// <value>The update's reason.</value> public string Reason { get; set; } } }
27.681818
69
0.582923
[ "MIT" ]
martinussuherman/PsefApiOData
Models/ViewModels/PermohonanSystemUpdate.cs
609
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 personalize-2018-05-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.Personalize.Model { /// <summary> /// An object that provides information about a solution. A solution is a trained model /// that can be deployed as a campaign. /// </summary> public partial class Solution { private AutoMLResult _automlResult; private DateTime? _creationDateTime; private string _datasetGroupArn; private string _eventType; private DateTime? _lastUpdatedDateTime; private SolutionVersionSummary _latestSolutionVersion; private string _name; private bool? _performAutoML; private bool? _performhpo; private string _recipeArn; private string _solutionArn; private SolutionConfig _solutionConfig; private string _status; /// <summary> /// Gets and sets the property AutoMLResult. /// <para> /// When <code>performAutoML</code> is true, specifies the best recipe found. /// </para> /// </summary> public AutoMLResult AutoMLResult { get { return this._automlResult; } set { this._automlResult = value; } } // Check to see if AutoMLResult property is set internal bool IsSetAutoMLResult() { return this._automlResult != null; } /// <summary> /// Gets and sets the property CreationDateTime. /// <para> /// The creation date and time (in Unix time) of the solution. /// </para> /// </summary> public DateTime CreationDateTime { get { return this._creationDateTime.GetValueOrDefault(); } set { this._creationDateTime = value; } } // Check to see if CreationDateTime property is set internal bool IsSetCreationDateTime() { return this._creationDateTime.HasValue; } /// <summary> /// Gets and sets the property DatasetGroupArn. /// <para> /// The Amazon Resource Name (ARN) of the dataset group that provides the training data. /// </para> /// </summary> [AWSProperty(Max=256)] public string DatasetGroupArn { get { return this._datasetGroupArn; } set { this._datasetGroupArn = value; } } // Check to see if DatasetGroupArn property is set internal bool IsSetDatasetGroupArn() { return this._datasetGroupArn != null; } /// <summary> /// Gets and sets the property EventType. /// <para> /// The event type (for example, 'click' or 'like') that is used for training the model. /// </para> /// </summary> [AWSProperty(Max=256)] public string EventType { get { return this._eventType; } set { this._eventType = value; } } // Check to see if EventType property is set internal bool IsSetEventType() { return this._eventType != null; } /// <summary> /// Gets and sets the property LastUpdatedDateTime. /// <para> /// The date and time (in Unix time) that the solution was last updated. /// </para> /// </summary> public DateTime LastUpdatedDateTime { get { return this._lastUpdatedDateTime.GetValueOrDefault(); } set { this._lastUpdatedDateTime = value; } } // Check to see if LastUpdatedDateTime property is set internal bool IsSetLastUpdatedDateTime() { return this._lastUpdatedDateTime.HasValue; } /// <summary> /// Gets and sets the property LatestSolutionVersion. /// <para> /// Describes the latest version of the solution, including the status and the ARN. /// </para> /// </summary> public SolutionVersionSummary LatestSolutionVersion { get { return this._latestSolutionVersion; } set { this._latestSolutionVersion = value; } } // Check to see if LatestSolutionVersion property is set internal bool IsSetLatestSolutionVersion() { return this._latestSolutionVersion != null; } /// <summary> /// Gets and sets the property Name. /// <para> /// The name of the solution. /// </para> /// </summary> [AWSProperty(Min=1, Max=63)] 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; } /// <summary> /// Gets and sets the property PerformAutoML. /// <para> /// When true, Amazon Personalize performs a search for the best USER_PERSONALIZATION /// recipe from the list specified in the solution configuration (<code>recipeArn</code> /// must not be specified). When false (the default), Amazon Personalize uses <code>recipeArn</code> /// for training. /// </para> /// </summary> public bool PerformAutoML { get { return this._performAutoML.GetValueOrDefault(); } set { this._performAutoML = value; } } // Check to see if PerformAutoML property is set internal bool IsSetPerformAutoML() { return this._performAutoML.HasValue; } /// <summary> /// Gets and sets the property PerformHPO. /// <para> /// Whether to perform hyperparameter optimization (HPO) on the chosen recipe. The default /// is <code>false</code>. /// </para> /// </summary> public bool PerformHPO { get { return this._performhpo.GetValueOrDefault(); } set { this._performhpo = value; } } // Check to see if PerformHPO property is set internal bool IsSetPerformHPO() { return this._performhpo.HasValue; } /// <summary> /// Gets and sets the property RecipeArn. /// <para> /// The ARN of the recipe used to create the solution. /// </para> /// </summary> [AWSProperty(Max=256)] public string RecipeArn { get { return this._recipeArn; } set { this._recipeArn = value; } } // Check to see if RecipeArn property is set internal bool IsSetRecipeArn() { return this._recipeArn != null; } /// <summary> /// Gets and sets the property SolutionArn. /// <para> /// The ARN of the solution. /// </para> /// </summary> [AWSProperty(Max=256)] public string SolutionArn { get { return this._solutionArn; } set { this._solutionArn = value; } } // Check to see if SolutionArn property is set internal bool IsSetSolutionArn() { return this._solutionArn != null; } /// <summary> /// Gets and sets the property SolutionConfig. /// <para> /// Describes the configuration properties for the solution. /// </para> /// </summary> public SolutionConfig SolutionConfig { get { return this._solutionConfig; } set { this._solutionConfig = value; } } // Check to see if SolutionConfig property is set internal bool IsSetSolutionConfig() { return this._solutionConfig != null; } /// <summary> /// Gets and sets the property Status. /// <para> /// The status of the solution. /// </para> /// /// <para> /// A solution can be in one of the following states: /// </para> /// <ul> <li> /// <para> /// CREATE PENDING &gt; CREATE IN_PROGRESS &gt; ACTIVE -or- CREATE FAILED /// </para> /// </li> <li> /// <para> /// DELETE PENDING &gt; DELETE IN_PROGRESS /// </para> /// </li> </ul> /// </summary> [AWSProperty(Max=256)] public string Status { get { return this._status; } set { this._status = value; } } // Check to see if Status property is set internal bool IsSetStatus() { return this._status != null; } } }
30.909385
109
0.557533
[ "Apache-2.0" ]
Singh400/aws-sdk-net
sdk/src/Services/Personalize/Generated/Model/Solution.cs
9,551
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; using Microsoft.UI.Xaml.Controls.Primitives; using Microsoft.UI.Xaml.Data; using Microsoft.UI.Xaml.Input; using Microsoft.UI.Xaml.Media; using Microsoft.UI.Xaml.Navigation; // The User Control item template is documented at https://go.microsoft.com/fwlink/?LinkId=234236 namespace MyExtensionsApp { public sealed partial class FilterFlyout : Flyout { public FilterFlyout() { this.InitializeComponent(); } } }
24.066667
97
0.753463
[ "Apache-2.0" ]
twins2020/uno.extensions
src/Uno.Extensions.Templates/content/unoapp-extensions/MyExtensionsApp.Shared/Views/FilterFlyout.xaml.cs
724
C#
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // 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.PinpointSMSVoice")] #if BCL35 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon Pinpoint SMS and Voice Service. With Amazon Pinpoint Voice, you can use text-to-speech technology to deliver personalized voice messages to your customers. Amazon Pinpoint Voice is a way to deliver transactional messages -- such as one-time passwords and appointment confirmations to customers.")] #elif BCL45 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - Amazon Pinpoint SMS and Voice Service. With Amazon Pinpoint Voice, you can use text-to-speech technology to deliver personalized voice messages to your customers. Amazon Pinpoint Voice is a way to deliver transactional messages -- such as one-time passwords and appointment confirmations to customers.")] #elif PCL [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (PCL) - Amazon Pinpoint SMS and Voice Service. With Amazon Pinpoint Voice, you can use text-to-speech technology to deliver personalized voice messages to your customers. Amazon Pinpoint Voice is a way to deliver transactional messages -- such as one-time passwords and appointment confirmations to customers.")] #elif UNITY [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (Unity) - Amazon Pinpoint SMS and Voice Service. With Amazon Pinpoint Voice, you can use text-to-speech technology to deliver personalized voice messages to your customers. Amazon Pinpoint Voice is a way to deliver transactional messages -- such as one-time passwords and appointment confirmations to customers.")] #elif NETSTANDARD13 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3)- Amazon Pinpoint SMS and Voice Service. With Amazon Pinpoint Voice, you can use text-to-speech technology to deliver personalized voice messages to your customers. Amazon Pinpoint Voice is a way to deliver transactional messages -- such as one-time passwords and appointment confirmations to customers.")] #elif NETSTANDARD20 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0)- Amazon Pinpoint SMS and Voice Service. With Amazon Pinpoint Voice, you can use text-to-speech technology to deliver personalized voice messages to your customers. Amazon Pinpoint Voice is a way to deliver transactional messages -- such as one-time passwords and appointment confirmations to customers.")] #else #error Unknown platform constant - unable to set correct AssemblyDescription #endif [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.100.186")] #if WINDOWS_PHONE || UNITY [assembly: System.CLSCompliant(false)] # else [assembly: System.CLSCompliant(true)] #endif #if BCL [assembly: System.Security.AllowPartiallyTrustedCallers] #endif
68.118644
392
0.787758
[ "Apache-2.0" ]
Melvinerall/aws-sdk-net
sdk/src/Services/PinpointSMSVoice/Properties/AssemblyInfo.cs
4,019
C#
using System; using System.Collections.Generic; using System.Linq; using System.Data; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class frmTripwiseOverSpeedingRpt : DBUtility { string strQry = ""; DataSet dsObj; protected void Page_Load(object sender, EventArgs e) { if (Session["UserType_Id"] != null && Session["User_Id"] != null) { Label lblTitle = new Label(); lblTitle = (Label)Page.Master.FindControl("lblPageTitle"); lblTitle.Visible = true; lblTitle.Text = "Tripwise Over Speeding Report"; if (!IsPostBack) { FillRoute(); txtFrmDate.Text = DateTime.Now.ToString("dd/MM/yyyy"); txtToDate.Text = DateTime.Now.ToString("dd/MM/yyyy"); } } else { Response.Redirect("~\\frmlogin.aspx", false); } } protected void ddlTrip_SelectedIndexChanged(object sender, EventArgs e) { try { if (ddlTrip.SelectedValue != "0") { strQry = ""; strQry = "exec usp_TripwiseReport @type='OverSpeedingReport',@dtAttendance_date='" + Convert.ToDateTime(txtFrmDate.Text).ToString("MM/dd/yyyy") + "',@Todate1='" + Convert.ToDateTime(txtToDate.Text).ToString("MM/dd/yyyy") + "',@intRoute_id='" + Convert.ToString(ddlRoute.SelectedValue) + "',@intTrip_id='" + Convert.ToString(ddlTrip.SelectedValue) + "',@intSchoolid='" + Session["School_id"] + "'"; dsObj = new DataSet(); dsObj = sGetDataset(strQry); if (dsObj.Tables[0].Rows.Count > 0) { grvTripDetails.DataSource = dsObj; grvTripDetails.DataBind(); } else { grvTripDetails.DataSource = null; grvTripDetails.DataBind(); } } } catch { } } public void FillRoute() { try { strQry = ""; strQry = "exec usp_TripwiseReport @type='FillRoute',@intSchoolid='" + Session["School_Id"] + "'"; sBindDropDownList(ddlRoute, strQry, "vchRoute_name", "intRoute_id"); } catch { } } public void FillTrip() { try { strQry = ""; strQry = "exec usp_TripwiseReport @type='FillTrip',@intRoute_id='" + Convert.ToString(ddlRoute.SelectedValue) + "',@intSchoolid='" + Session["School_Id"] + "'"; sBindDropDownList(ddlTrip, strQry, "vchTrip_name", "intTrip_id"); } catch { } } protected void ddlRoute_SelectedIndexChanged(object sender, EventArgs e) { try { if (ddlRoute.SelectedValue != "0") { FillTrip(); } else { ddlTrip.DataSource = null; } } catch { } } protected void txtFrmDate_TextChanged(object sender, EventArgs e) { try { strQry = ""; strQry = "exec usp_TripwiseReport @type='OverSpeedingReport',@dtAttendance_date='" + Convert.ToDateTime(txtFrmDate.Text).ToString("MM/dd/yyyy") + "',@Todate1='" + Convert.ToDateTime(txtToDate.Text).ToString("MM/dd/yyyy") + "',@intSchoolid='" + Session["School_Id"] + "',@intRoute_id='" + Convert.ToString(ddlRoute.SelectedValue) + "',@intTrip_id='" + Convert.ToString(ddlTrip.SelectedValue) + "'"; dsObj = new DataSet(); dsObj = sGetDataset(strQry); if (dsObj.Tables[0].Rows.Count > 0) { grvTripDetails.DataSource = dsObj; grvTripDetails.DataBind(); } else { grvTripDetails.DataSource = null; grvTripDetails.DataBind(); } } catch { } } protected void txtToDate_TextChanged(object sender, EventArgs e) { try { strQry = ""; strQry = "exec usp_TripwiseReport @type='OverSpeedingReport',@dtAttendance_date='" + Convert.ToDateTime(txtFrmDate.Text).ToString("MM/dd/yyyy") + "',@Todate1='" + Convert.ToDateTime(txtToDate.Text).ToString("MM/dd/yyyy") + "',@intSchoolid='" + Session["School_Id"] + "',@intRoute_id='" + Convert.ToString(ddlRoute.SelectedValue) + "',@intTrip_id='" + Convert.ToString(ddlTrip.SelectedValue) + "'"; dsObj = new DataSet(); dsObj = sGetDataset(strQry); if (dsObj.Tables[0].Rows.Count > 0) { grvTripDetails.DataSource = dsObj; grvTripDetails.DataBind(); } else { grvTripDetails.DataSource = null; grvTripDetails.DataBind(); } } catch { } } }
32.833333
413
0.514057
[ "MIT" ]
clearcodetechnologies/cctSchoolApplication
frmTripwiseOverSpeedingRpt.aspx.cs
5,124
C#
/* | Version 10.1.84 | Copyright 2013 Esri | | Licensed under the Apache License, Version 2.0 (the "License"); | you may not use this file except in compliance with the License. | You may obtain a copy of the License at | | http://www.apache.org/licenses/LICENSE-2.0 | | Unless required by applicable law or agreed to in writing, software | distributed under the License is distributed on an "AS IS" BASIS, | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | See the License for the specific language governing permissions and | limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using ESRI.ArcLogistics.App.Pages; using ESRI.ArcLogistics.DomainObjects; using System.Collections; using System.Collections.ObjectModel; using ESRI.ArcLogistics.Geocoding; using ESRI.ArcLogistics.Data; namespace ESRI.ArcLogistics.App.Commands { /// <summary> /// Command geocode locations /// </summary> class GeocodeOrdersCmd : OrdersCommandBase { #region Public Fields public const string COMMAND_NAME = "ArcLogistics.Commands.GeocodeOrdersCmd"; #endregion #region Override members public override string Name { get { return COMMAND_NAME; } } public override string Title { get { return (string)App.Current.FindResource("GeocodeCommandTitle"); } } public override bool IsEnabled { get { return base.IsEnabled; } protected set { base.IsEnabled = value; if (value) TooltipText = (string)App.Current.FindResource("RematchAddressCommandEnabledTooltip"); else TooltipText = (string)App.Current.FindResource("RematchAddressCommandDisabledTooltip"); } } public override string TooltipText { get { return _tooltipText; } protected set { _tooltipText = value; _NotifyPropertyChanged(TOOLTIP_PROPERTY_NAME); } } protected override void _Execute(params object[] args) { _Geocode(); } /// <summary> /// Method checks is command enabled /// </summary> protected override void _CheckEnabled() { IsEnabled = !OptimizePage.IsLocked && !OptimizePage.IsEditingInProgress && OptimizePage.SelectedItems.Count == 1 && OptimizePage.SelectedItems[0] is Order; } #endregion #region GeocodeCommandBase Protected Methods /// <summary> /// Geocode order /// </summary> private void _Geocode() { if (OptimizePage.SelectedItems.Count == 1) { IGeocodable order = (IGeocodable)OptimizePage.SelectedItems[0]; OptimizePage.StartGeocoding(order); } } #endregion GeocodeCommandBase Protected Methods #region Private Fields private const string TOOLTIP_PROPERTY_NAME = "TooltipText"; private string _tooltipText = null; #endregion } }
26.553846
107
0.58372
[ "Apache-2.0" ]
Esri/route-planner-csharp
RoutePlanner_DeveloperTools/Source/ArcLogisticsApp/Commands/GeocodeOrdersCmd.cs
3,454
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using UnityEngine; namespace Nova { [Serializable] public class GlobalSave { // Node name -> dialogue index -> node history hash -> GameStateRestoreEntry // TODO: deduplicate restoreDatas public readonly Dictionary<string, Dictionary<int, Dictionary<ulong, GameStateRestoreEntry>>> reachedDialogues = new Dictionary<string, Dictionary<int, Dictionary<ulong, GameStateRestoreEntry>>>(); // Node name -> branch name -> node history hash -> bool public readonly Dictionary<string, Dictionary<string, SerializableHashSet<ulong>>> reachedBranches = new Dictionary<string, Dictionary<string, SerializableHashSet<ulong>>>(); // End name -> bool public readonly SerializableHashSet<string> reachedEnds = new SerializableHashSet<string>(); // Node history hash -> NodeHistory // TODO: use a radix tree to store node histories public readonly Dictionary<ulong, NodeHistoryData> cachedNodeHistories = new Dictionary<ulong, NodeHistoryData>(); public readonly long identifier = DateTime.Now.ToBinary(); /// The global data of the game. For example, the global variables and the unlock status of images and musics. /// It is the game author's job to make sure all values are serializable. public readonly Dictionary<string, object> data = new Dictionary<string, object>(); } #region Bookmark classes [Serializable] public class Bookmark { public const int ScreenshotWidth = 320; public const int ScreenshotHeight = 180; public readonly ulong nodeHistoryHash; public readonly int dialogueIndex; public string description; public readonly DateTime creationTime = DateTime.Now; public long globalSaveIdentifier; private byte[] screenshotBytes; [NonSerialized] private Texture2D screenshotTexture; public Texture2D screenshot { get { if (screenshotBytes == null) { Utils.RuntimeAssert(screenshotTexture == null, "Screenshot cache is not consistent."); return null; } if (screenshotTexture == null) { screenshotTexture = new Texture2D(ScreenshotWidth, ScreenshotHeight, TextureFormat.RGB24, false); screenshotTexture.LoadImage(screenshotBytes); } return screenshotTexture; } set { screenshotTexture = value; screenshotBytes = screenshotTexture.EncodeToJPG(); } } // NOTE: Do not use default parameters in constructor or it will fail to compile silently... /// <summary> /// Create a bookmark based on all reached nodes in current gameplay. /// </summary> /// <param name="nodeHistory">List of all reached nodes, including the current node as the last one.</param> /// <param name="dialogueIndex">Index of the current dialogue.</param> public Bookmark(NodeHistory nodeHistory, int dialogueIndex) { nodeHistoryHash = nodeHistory.Hash; this.dialogueIndex = dialogueIndex; } public void TryDestroyTexture() { Utils.DestroyObject(screenshotTexture); } } public enum BookmarkType { AutoSave = 101, QuickSave = 201, NormalSave = 301 } public enum SaveIDQueryType { Latest, Earliest } public class BookmarkMetadata { private int _saveID; public int saveID { get => _saveID; set { type = SaveIDToBookmarkType(value); _saveID = value; } } public BookmarkType type { get; private set; } public DateTime modifiedTime; public static BookmarkType SaveIDToBookmarkType(int saveID) { if (saveID >= (int)BookmarkType.NormalSave) { return BookmarkType.NormalSave; } if (saveID >= (int)BookmarkType.QuickSave) { return BookmarkType.QuickSave; } return BookmarkType.AutoSave; } } #endregion /// <summary> /// Manager component providing ability to manage the game progress and save files. /// </summary> public class CheckpointManager : MonoBehaviour { public string saveFolder; private string savePathBase; private string globalSavePath; private GlobalSave globalSave; private readonly Dictionary<int, Bookmark> cachedSaveSlots = new Dictionary<int, Bookmark>(); public readonly Dictionary<int, BookmarkMetadata> saveSlotsMetadata = new Dictionary<int, BookmarkMetadata>(); private readonly CheckpointSerializer serializer = new CheckpointSerializer(); private bool inited; // Should be called in Start, not in Awake public void Init() { if (inited) { return; } savePathBase = Path.Combine(Application.persistentDataPath, "Save", saveFolder); globalSavePath = Path.Combine(savePathBase, "global.nsav"); Directory.CreateDirectory(savePathBase); if (File.Exists(globalSavePath)) { try { globalSave = serializer.SafeRead<GlobalSave>(globalSavePath); } catch (Exception e) { Debug.LogError($"Nova: Cannot load global save file.\n{e.Message}"); Alert.Show( null, I18n.__("bookmark.load.globalfail"), ResetGlobalSave, Utils.Quit ); } } else { ResetGlobalSave(); } foreach (string fileName in Directory.GetFiles(savePathBase, "sav*.nsav*")) { var result = Regex.Match(fileName, @"sav([0-9]+)\.nsav"); if (result.Groups.Count > 1 && int.TryParse(result.Groups[1].Value, out int id)) { saveSlotsMetadata.Add(id, new BookmarkMetadata { saveID = id, modifiedTime = File.GetLastWriteTime(fileName) }); } } // Debug.Log("Nova: CheckpointManager initialized."); inited = true; } private void Start() { Init(); } private void OnDestroy() { UpdateGlobalSave(); foreach (var bookmark in cachedSaveSlots.Values) { bookmark.TryDestroyTexture(); } } #region Global save public void GetNodeHistory(ulong nodeHistoryHash, NodeHistory nodeHistory) { if (!globalSave.cachedNodeHistories.TryGetValue(nodeHistoryHash, out var data)) { throw new ArgumentException("Nova: Node history not found."); } nodeHistory.Clear(); nodeHistory.AddRange(data.nodeNames); nodeHistory.interrupts.Clear(); foreach (var pair in data.interrupts) { nodeHistory.interrupts[pair.Key] = new SortedDictionary<int, ulong>((IDictionary<int, ulong>)pair.Value); } } public string GetLastNodeName(ulong nodeHistoryHash) { if (!globalSave.cachedNodeHistories.TryGetValue(nodeHistoryHash, out var data)) { throw new ArgumentException("Nova: Node history not found."); } return data.nodeNames.Last(); } /// <summary> /// Set a dialogue to "reached" state and save the restore entry for the dialogue. /// </summary> /// <param name="nodeHistory">The list of all reached nodes.</param> /// <param name="dialogueIndex">The index of the dialogue.</param> /// <param name="entry">Restore entry for the dialogue.</param> public void SetReached(NodeHistory nodeHistory, int dialogueIndex, GameStateRestoreEntry entry) { var nodeName = nodeHistory.Last().Key; globalSave.reachedDialogues.Ensure(nodeName).Ensure(dialogueIndex)[nodeHistory.Hash] = entry; if (!globalSave.cachedNodeHistories.ContainsKey(nodeHistory.Hash)) { globalSave.cachedNodeHistories[nodeHistory.Hash] = new NodeHistoryData(nodeHistory); } } /// <summary> /// Set a branch to "reached" state. /// </summary> /// <param name="nodeHistory">The list of all reached nodes.</param> /// <param name="branchName">The name of the branch.</param> public void SetBranchReached(NodeHistory nodeHistory, string branchName) { var nodeName = nodeHistory.Last().Key; globalSave.reachedBranches.Ensure(nodeName).Ensure(branchName).Add(nodeHistory.Hash); if (!globalSave.cachedNodeHistories.ContainsKey(nodeHistory.Hash)) { globalSave.cachedNodeHistories[nodeHistory.Hash] = new NodeHistoryData(nodeHistory); } } /// <summary> /// Set an end point to "reached" state. /// </summary> /// <param name="endName">The name of the end point.</param> public void SetEndReached(string endName) { globalSave.reachedEnds.Add(endName); } public void UnsetReached(ulong nodeHistoryHash) { var nodeName = GetLastNodeName(nodeHistoryHash); globalSave.reachedDialogues.Remove(nodeName); globalSave.reachedBranches.Remove(nodeName); } public void UnsetReachedAfter(NodeHistory nodeHistory, int dialogueIndex) { var nodeName = nodeHistory.Last().Key; if (globalSave.reachedDialogues.TryGetValue(nodeName, out var dict)) { foreach (var key in dict.Keys.Where(key => key > dialogueIndex).ToList()) { dict.Remove(key); } } } public GameStateRestoreEntry GetReached(ulong nodeHistoryHash, string nodeName, int dialogueIndex) { return globalSave.reachedDialogues.TryGetValue(nodeName, out var dict) && dict.TryGetValue(dialogueIndex, out var dict2) && dict2.TryGetValue(nodeHistoryHash, out var entry) ? entry : null; } /// <summary> /// Get the restore entry for a dialogue. /// </summary> /// <param name="nodeHistory">The list of all reached nodes.</param> /// <param name="dialogueIndex">The index of the dialogue.</param> /// <returns>The restore entry for the dialogue. Null if not reached.</returns> public GameStateRestoreEntry GetReached(NodeHistory nodeHistory, int dialogueIndex) { var nodeName = nodeHistory.Last().Key; return GetReached(nodeHistory.Hash, nodeName, dialogueIndex); } public bool IsReachedAnyHistory(string nodeName, int dialogueIndex) { return globalSave.reachedDialogues.TryGetValue(nodeName, out var dict) && dict.ContainsKey(dialogueIndex); } public bool IsBranchReached(ulong nodeHistoryHash, string nodeName, string branchName) { return globalSave.reachedBranches.TryGetValue(nodeName, out var dict) && dict.TryGetValue(branchName, out var hashSet) && hashSet.Contains(nodeHistoryHash); } /// <summary> /// Check if the branch has been reached. /// </summary> /// <param name="nodeHistory">The list of all reached nodes.</param> /// <param name="branchName">The name of the branch.</param> /// <returns>Whether the branch has been reached.</returns> public bool IsBranchReached(NodeHistory nodeHistory, string branchName) { var nodeName = nodeHistory.Last().Key; return IsBranchReached(nodeHistory.Hash, nodeName, branchName); } public bool IsBranchReachedAnyHistory(string nodeName, string branchName) { return globalSave.reachedBranches.TryGetValue(nodeName, out var dict) && dict.ContainsKey(branchName); } /// <summary> /// Check if the end point has been reached. /// </summary> /// <param name="endName">The name of the end point.</param> /// <returns>Whether the end point has been reached.</returns> public bool IsEndReached(string endName) { return globalSave.reachedEnds.Contains(endName); } /// <summary> /// Update the global save file. /// </summary> /// TODO: UpdateGlobalSave() is slow when there are many saved dialogue entries public void UpdateGlobalSave() { serializer.SafeWrite(globalSave, globalSavePath); } /// <summary> /// Reset the global save file to clear all progress. /// Note that all bookmarks will be invalid. /// </summary> public void ResetGlobalSave() { var saveDir = new DirectoryInfo(savePathBase); foreach (var file in saveDir.GetFiles()) file.Delete(); globalSave = new GlobalSave(); serializer.SafeWrite(globalSave, globalSavePath); } #endregion #region Bookmarks private string GetBookmarkFileName(int saveID) { return Path.Combine(savePathBase, $"sav{saveID:D3}.nsav"); } private Bookmark ReplaceCache(int saveID, Bookmark bookmark) { if (cachedSaveSlots.ContainsKey(saveID)) { var old = cachedSaveSlots[saveID]; if (old == bookmark) { return bookmark; } Destroy(old.screenshot); } if (bookmark == null) { cachedSaveSlots.Remove(saveID); } else { cachedSaveSlots[saveID] = bookmark; } return bookmark; } /// <summary> /// Save a bookmark to disk, and update the global save file. /// Will throw exception if it fails. /// </summary> /// <param name="saveID">ID of the bookmark.</param> /// <param name="bookmark">The bookmark to save.</param> public void SaveBookmark(int saveID, Bookmark bookmark) { var screenshot = new Texture2D(bookmark.screenshot.width, bookmark.screenshot.height, bookmark.screenshot.format, false); screenshot.SetPixels32(bookmark.screenshot.GetPixels32()); screenshot.Apply(); bookmark.screenshot = screenshot; bookmark.globalSaveIdentifier = globalSave.identifier; serializer.SafeWrite(ReplaceCache(saveID, bookmark), GetBookmarkFileName(saveID)); UpdateGlobalSave(); var metadata = saveSlotsMetadata.Ensure(saveID); metadata.saveID = saveID; metadata.modifiedTime = DateTime.Now; } /// <summary> /// Load a bookmark from disk. Never uses cache. /// Will throw exception if it fails. /// </summary> /// <param name="saveID">ID of the bookmark.</param> /// <returns>The loaded bookmark.</returns> public Bookmark LoadBookmark(int saveID) { var bookmark = serializer.SafeRead<Bookmark>(GetBookmarkFileName(saveID)); if (bookmark.globalSaveIdentifier != globalSave.identifier) { Debug.LogWarning($"Nova: Save file is incompatible with the global save file, saveID {saveID}"); bookmark = null; } return ReplaceCache(saveID, bookmark); } /// <summary> /// Delete a specified bookmark. /// </summary> /// <param name="saveID">ID of the bookmark.</param> public void DeleteBookmark(int saveID) { File.Delete(GetBookmarkFileName(saveID)); saveSlotsMetadata.Remove(saveID); ReplaceCache(saveID, null); } /// <summary> /// Load the contents of all existing bookmark in the given range eagerly. /// </summary> /// <param name="beginSaveID">The beginning of the range, inclusive.</param> /// <param name="endSaveID">The end of the range, exclusive.</param> public void EagerLoadRange(int beginSaveID, int endSaveID) { for (; beginSaveID < endSaveID; beginSaveID++) { if (saveSlotsMetadata.ContainsKey(beginSaveID)) LoadBookmark(beginSaveID); } } /// <summary> /// Load / Save a bookmark by ID. Will use cached result if exists. /// </summary> /// <param name="saveID">ID of the bookmark.</param> /// <returns>The cached or loaded bookmark</returns> public Bookmark this[int saveID] { get { if (!saveSlotsMetadata.ContainsKey(saveID)) return null; if (!cachedSaveSlots.ContainsKey(saveID)) LoadBookmark(saveID); return cachedSaveSlots[saveID]; } set => SaveBookmark(saveID, value); } /// <summary> /// Query the ID of the latest / earliest bookmark. /// </summary> /// <param name="begin">Beginning ID of the query range, inclusive.</param> /// <param name="end">Ending ID of the query range, exclusive.</param> /// <param name="type">Type of this query.</param> /// <returns>The ID to query. If no bookmark is found in range, the return value will be "begin".</returns> public int QuerySaveIDByTime(int begin, int end, SaveIDQueryType type) { var filtered = saveSlotsMetadata.Values.Where(m => m.saveID >= begin && m.saveID < end).ToList(); if (!filtered.Any()) return begin; if (type == SaveIDQueryType.Earliest) return filtered.Aggregate((agg, val) => agg.modifiedTime < val.modifiedTime ? agg : val).saveID; else return filtered.Aggregate((agg, val) => agg.modifiedTime > val.modifiedTime ? agg : val).saveID; } public int QueryMaxSaveID(int begin) { if (!saveSlotsMetadata.Any()) { return begin; } return Math.Max(saveSlotsMetadata.Keys.Max(), begin); } public int QueryMinUnusedSaveID(int begin, int end) { int saveID = begin; while (saveID < end && saveSlotsMetadata.ContainsKey(saveID)) { ++saveID; } return saveID; } #endregion #region Auxiliary data /// <summary> /// Get global data /// </summary> /// <see cref="GlobalSave"/> /// <param name="key">the key of the data</param> /// <param name="defaultValue">the default value if the key is not found</param> /// <typeparam name="T">the type of the data</typeparam> /// <returns>the stored data</returns> public T Get<T>(string key, T defaultValue = default) { if (globalSave.data.TryGetValue(key, out var value)) { return (T)Convert.ChangeType(value, typeof(T)); } else { return defaultValue; } } /// <summary> /// Set global data /// </summary> /// <see cref="GlobalSave"/> /// <param name="key">the key of the data</param> /// <param name="value">the data to store</param> public void Set(string key, object value) { globalSave.data[key] = value; } #endregion } }
34.811352
121
0.563927
[ "MIT" ]
kalifo/Nova
Assets/Nova/Sources/Core/Restoration/CheckpointManager.cs
20,854
C#
// // Copyright (c) 2019-2021 Ryujinx // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // using Ryujinx.Audio.Backends.Common; using Ryujinx.Audio.Common; using System; using System.Runtime.InteropServices; namespace Ryujinx.Audio.Backends.CompatLayer { class CompatLayerHardwareDeviceSession : HardwareDeviceSessionOutputBase { private HardwareDeviceSessionOutputBase _realSession; private uint _userChannelCount; public CompatLayerHardwareDeviceSession(HardwareDeviceSessionOutputBase realSession, uint userChannelCount) : base(realSession.MemoryManager, realSession.RequestedSampleFormat, realSession.RequestedSampleRate, userChannelCount) { _realSession = realSession; _userChannelCount = userChannelCount; } public override void Dispose() { _realSession.Dispose(); } public override ulong GetPlayedSampleCount() { return _realSession.GetPlayedSampleCount(); } public override float GetVolume() { return _realSession.GetVolume(); } public override void PrepareToClose() { _realSession.PrepareToClose(); } public override void QueueBuffer(AudioBuffer buffer) { _realSession.QueueBuffer(buffer); } public override bool RegisterBuffer(AudioBuffer buffer, byte[] samples) { if (RequestedSampleFormat != SampleFormat.PcmInt16) { throw new NotImplementedException("Downmixing formats other than PCM16 is not supported."); } if (samples == null) { return false; } short[] downmixedBufferPCM16; ReadOnlySpan<short> samplesPCM16 = MemoryMarshal.Cast<byte, short>(samples); if (_userChannelCount == 6) { downmixedBufferPCM16 = Downmixing.DownMixSurroundToStereo(samplesPCM16); if (_realSession.RequestedChannelCount == 1) { downmixedBufferPCM16 = Downmixing.DownMixStereoToMono(downmixedBufferPCM16); } } else if (_userChannelCount == 2 && _realSession.RequestedChannelCount == 1) { downmixedBufferPCM16 = Downmixing.DownMixStereoToMono(samplesPCM16); } else { throw new NotImplementedException($"Downmixing from {_userChannelCount} to {_realSession.RequestedChannelCount} not implemented."); } byte[] downmixedBuffer = MemoryMarshal.Cast<short, byte>(downmixedBufferPCM16).ToArray(); AudioBuffer fakeBuffer = new AudioBuffer { BufferTag = buffer.BufferTag, DataPointer = buffer.DataPointer, DataSize = (ulong)downmixedBuffer.Length }; bool result = _realSession.RegisterBuffer(fakeBuffer, downmixedBuffer); if (result) { buffer.Data = fakeBuffer.Data; buffer.DataSize = fakeBuffer.DataSize; } return result; } public override void SetVolume(float volume) { _realSession.SetVolume(volume); } public override void Start() { _realSession.Start(); } public override void Stop() { _realSession.Stop(); } public override void UnregisterBuffer(AudioBuffer buffer) { _realSession.UnregisterBuffer(buffer); } public override bool WasBufferFullyConsumed(AudioBuffer buffer) { return _realSession.WasBufferFullyConsumed(buffer); } } }
31.680851
235
0.617864
[ "MIT" ]
0MrDarn0/Ryujinx
Ryujinx.Audio/Backends/CompatLayer/CompatLayerHardwareDeviceSession.cs
4,469
C#
using System.Resources; 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("AssistantComputerControl")] [assembly: AssemblyDescription("Control your computer using your personal assistant.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AssistantComputerControl")] [assembly: AssemblyCopyright("Copyright © 2020")] [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("404b42f4-e135-4d2f-8fd0-20a590814930")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.4.2.0")] [assembly: AssemblyFileVersion("1.4.2.0")] [assembly: NeutralResourcesLanguage("en")]
40.5
87
0.756335
[ "MIT" ]
AnalogCyan/AssistantComputerControl
AssistantComputerControl/Properties/AssemblyInfo.cs
1,542
C#
using System; using System.Net; namespace SmallsOnline.Subnetting.Lib.Models { using SmallsOnline.Subnetting.Lib.Enums; /// <summary> /// A representation of an IPv4 subnet. /// </summary> public class IPv4Subnet { /// <summary> /// Create from an IP address and CIDR mask. /// </summary> /// <param name="ipAddress">An IP address in a subnet.</param> /// <param name="cidr">The CIDR mask for the subnet.</param> public IPv4Subnet(IPAddress ipAddress, double cidr) { _subnetMask = new(cidr); _networkAddress = GetSubnetBoundary(ipAddress, _subnetMask); _broadcastAddress = GetBroadcastAddress(_networkAddress, _subnetMask); _usableHostRange = new(_networkAddress, _broadcastAddress); } /// <summary> /// Create from an IP address and CIDR mask. /// </summary> /// <param name="ipAddress">An IP address in a subnet.</param> /// <param name="subnetMask">The subnet mask.</param> public IPv4Subnet(IPAddress ipAddress, IPv4SubnetMask subnetMask) { _subnetMask = subnetMask; _networkAddress = GetSubnetBoundary(ipAddress, _subnetMask); _broadcastAddress = GetBroadcastAddress(_networkAddress, _subnetMask); _usableHostRange = new(_networkAddress, _broadcastAddress); } /// <summary> /// Create from an IP address and CIDR mask. /// </summary> /// <param name="ipAddress">An IP address in a subnet.</param> /// <param name="subnetMask">The subnet mask.</param> public IPv4Subnet(IPAddress ipAddress, IPAddress subnetMask) { _subnetMask = new(subnetMask.GetAddressBytes()); _networkAddress = GetSubnetBoundary(ipAddress, _subnetMask); _broadcastAddress = GetBroadcastAddress(_networkAddress, _subnetMask); _usableHostRange = new(_networkAddress, _broadcastAddress); } /// <summary> /// Create from a string of a network. /// For example: /// 10.21.6.0/18 /// </summary> /// <param name="networkString">A network written in a string format.</param> public IPv4Subnet(string networkString) { ParsedNetAddressString parsedNetAddress = new(networkString); _subnetMask = parsedNetAddress.ParsedType switch { ParsedNetAddressStringType.SubnetMask => new(parsedNetAddress.SubnetMask.GetAddressBytes()), _ => new(parsedNetAddress.CidrNotation) }; _networkAddress = GetSubnetBoundary(parsedNetAddress.IPAddress, _subnetMask); _broadcastAddress = GetBroadcastAddress(_networkAddress, _subnetMask); _usableHostRange = new(_networkAddress, _broadcastAddress); } /// <summary> /// The network address of the subnet. /// </summary> public IPAddress NetworkAddress { get => _networkAddress; } /// <summary> /// The subnet mask of the subnet. /// </summary> public IPv4SubnetMask SubnetMask { get => _subnetMask; } /// <summary> /// The CIDR mask of the subnet. /// </summary> public double CidrMask { get => _subnetMask.CidrNotation; } /// <summary> /// The broadcast address of the subnet. /// </summary> public IPAddress BroadcastAddress { get => _broadcastAddress; } /// <summary> /// The total amount of addresses in the subnet. /// </summary> public double TotalAddresses { get => _subnetMask.TotalAddresses; } /// <summary> /// The total amount of usable addresses in the subnet. /// </summary> public double UsableAddresses { get => _subnetMask.TotalAddresses - 2; } /// <summary> /// The range of hosts available for use in the subnet. /// </summary> public UsableHostRange UsableHostRange { get => _usableHostRange; } private readonly IPAddress _networkAddress; private readonly IPv4SubnetMask _subnetMask; private readonly IPAddress _broadcastAddress; private readonly UsableHostRange _usableHostRange; /// <summary> /// Display the subnet as a string. /// </summary> /// <returns>A string representation of the subnet with the network address and CIDR mask.</returns> public override string ToString() { return $"{_networkAddress}/{CidrMask}"; } /// <summary> /// Gets the network address of the subnet from the supplied IP address and the subnet mask. /// </summary> /// <param name="ipAddress">The IP address in the subnet.</param> /// <param name="subnetMask">The subnet mask of the subnet.</param> /// <returns>The network address of the subnet.</returns> private static IPAddress GetSubnetBoundary(IPAddress ipAddress, IPv4SubnetMask subnetMask) { // Get the byte arrays of the IP address and the subnet mask. byte[] ipAddressBytes = ipAddress.GetAddressBytes(); byte[] subnetMaskBytes = subnetMask.ToBytes(); // Get the last used octet in the subnet mask. Octet lastUsedOctet = subnetMask.GetLastUsedOctet(); // Create the byte array for generating the network address. byte[] netAddressBytes = new byte[4]; for (int i = 0; i < netAddressBytes.Length; i++) { if (i < lastUsedOctet.OctetPosition - 1) { // If the current loop count is less than the last used octet's position // then set the current index for the network address to the same value as // the IP address. netAddressBytes[i] = ipAddressBytes[i]; } else { // If the current loop count is less than the last used octet's position // then set the current index for the network address to the value of a // bitwise AND operation of the IP address and the subnet mask. netAddressBytes[i] = ipAddressBytes[i] &= subnetMaskBytes[i]; } } return new(netAddressBytes); } /// <summary> /// Gets the broadcast address of the subnet. /// </summary> /// <param name="networkAddress">The network address of the subnet.</param> /// <param name="subnetMask">The subnet mask of the subnet.</param> /// <returns>The broadcast address for the subnet.</returns> private static IPAddress GetBroadcastAddress(IPAddress networkAddress, IPv4SubnetMask subnetMask) { // Create an empty byte array for the broadcast address. byte[] broadcastAddressBytes = new byte[4]; // Get the bytes for the wildcard subnet mask. byte[] networkAddressBytes = networkAddress.GetAddressBytes(); byte[] wildcardBytes = subnetMask.WildcardMask.WildcardBytes; // Iterate through each index of the network address bytes and add the amount from the wildcard bytes. for (int i = 0; i < broadcastAddressBytes.Length; i++) { broadcastAddressBytes[i] = (byte)(networkAddressBytes[i] + wildcardBytes[i]); } return new(broadcastAddressBytes); } } }
38.318627
114
0.584879
[ "MIT" ]
Smalls1652/SmallsOnline.Subnetting
src/SmallsOnline.Subnetting.Lib/models/IPv4Subnet.cs
7,817
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by \generate-code.bat. // // Changes to this file will be lost when the code is regenerated. // The build server regenerates the code before each build and a pre-build // step will regenerate the code on each local build. // // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. // Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // </auto-generated> //------------------------------------------------------------------------------ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; using System.Globalization; using System.Linq; using JetBrains.Annotations; using UnitsNet.Units; using UnitsNet.InternalHelpers; // ReSharper disable once CheckNamespace namespace UnitsNet { /// <summary> /// In computing and telecommunications, a unit of information is the capacity of some standard data storage system or communication channel, used to measure the capacities of other systems and channels. In information theory, units of information are also used to measure the information contents or entropy of random variables. /// </summary> // Windows Runtime Component has constraints on public types: https://msdn.microsoft.com/en-us/library/br230301.aspx#Declaring types in Windows Runtime Components // Public structures can't have any members other than public fields, and those fields must be value types or strings. // Public classes must be sealed (NotInheritable in Visual Basic). If your programming model requires polymorphism, you can create a public interface and implement that interface on the classes that must be polymorphic. public sealed partial class Information : IQuantity { /// <summary> /// The numeric value this quantity was constructed with. /// </summary> private readonly decimal _value; /// <summary> /// The unit this quantity was constructed with. /// </summary> private readonly InformationUnit? _unit; static Information() { BaseDimensions = BaseDimensions.Dimensionless; Info = new QuantityInfo(QuantityType.Information, Units.Cast<Enum>().ToArray(), BaseUnit, Zero, BaseDimensions); } /// <summary> /// Creates the quantity with a value of 0 in the base unit Bit. /// </summary> /// <remarks> /// Windows Runtime Component requires a default constructor. /// </remarks> public Information() { _value = 0; _unit = BaseUnit; } /// <summary> /// Creates the quantity with the given numeric value and unit. /// </summary> /// <param name="value">The numeric value to construct this quantity with.</param> /// <param name="unit">The unit representation to construct this quantity with.</param> /// <remarks>Value parameter cannot be named 'value' due to constraint when targeting Windows Runtime Component.</remarks> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> private Information(decimal value, InformationUnit unit) { if(unit == InformationUnit.Undefined) throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); _value = value; _unit = unit; } #region Static Properties /// <summary> /// Information about the quantity type, such as unit values and names. /// </summary> internal static QuantityInfo Info { get; } /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> public static BaseDimensions BaseDimensions { get; } /// <summary> /// The base unit of Information, which is Bit. All conversions go via this value. /// </summary> public static InformationUnit BaseUnit { get; } = InformationUnit.Bit; /// <summary> /// Represents the largest possible value of Information /// </summary> public static Information MaxValue { get; } = new Information(decimal.MaxValue, BaseUnit); /// <summary> /// Represents the smallest possible value of Information /// </summary> public static Information MinValue { get; } = new Information(decimal.MinValue, BaseUnit); /// <summary> /// The <see cref="QuantityType" /> of this quantity. /// </summary> public static QuantityType QuantityType { get; } = QuantityType.Information; /// <summary> /// All units of measurement for the Information quantity. /// </summary> public static InformationUnit[] Units { get; } = Enum.GetValues(typeof(InformationUnit)).Cast<InformationUnit>().Except(new InformationUnit[]{ InformationUnit.Undefined }).ToArray(); /// <summary> /// Gets an instance of this quantity with a value of 0 in the base unit Bit. /// </summary> public static Information Zero { get; } = new Information(0, BaseUnit); #endregion #region Properties /// <summary> /// The numeric value this quantity was constructed with. /// </summary> public double Value => Convert.ToDouble(_value); /// <inheritdoc cref="IQuantity.Unit"/> object IQuantity.Unit => Unit; /// <summary> /// The unit this quantity was constructed with -or- <see cref="BaseUnit" /> if default ctor was used. /// </summary> public InformationUnit Unit => _unit.GetValueOrDefault(BaseUnit); internal QuantityInfo QuantityInfo => Info; /// <summary> /// The <see cref="QuantityType" /> of this quantity. /// </summary> public QuantityType Type => Information.QuantityType; /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> public BaseDimensions Dimensions => Information.BaseDimensions; #endregion #region Conversion Properties /// <summary> /// Get Information in Bits. /// </summary> public double Bits => As(InformationUnit.Bit); /// <summary> /// Get Information in Bytes. /// </summary> public double Bytes => As(InformationUnit.Byte); /// <summary> /// Get Information in Exabits. /// </summary> public double Exabits => As(InformationUnit.Exabit); /// <summary> /// Get Information in Exabytes. /// </summary> public double Exabytes => As(InformationUnit.Exabyte); /// <summary> /// Get Information in Exbibits. /// </summary> public double Exbibits => As(InformationUnit.Exbibit); /// <summary> /// Get Information in Exbibytes. /// </summary> public double Exbibytes => As(InformationUnit.Exbibyte); /// <summary> /// Get Information in Gibibits. /// </summary> public double Gibibits => As(InformationUnit.Gibibit); /// <summary> /// Get Information in Gibibytes. /// </summary> public double Gibibytes => As(InformationUnit.Gibibyte); /// <summary> /// Get Information in Gigabits. /// </summary> public double Gigabits => As(InformationUnit.Gigabit); /// <summary> /// Get Information in Gigabytes. /// </summary> public double Gigabytes => As(InformationUnit.Gigabyte); /// <summary> /// Get Information in Kibibits. /// </summary> public double Kibibits => As(InformationUnit.Kibibit); /// <summary> /// Get Information in Kibibytes. /// </summary> public double Kibibytes => As(InformationUnit.Kibibyte); /// <summary> /// Get Information in Kilobits. /// </summary> public double Kilobits => As(InformationUnit.Kilobit); /// <summary> /// Get Information in Kilobytes. /// </summary> public double Kilobytes => As(InformationUnit.Kilobyte); /// <summary> /// Get Information in Mebibits. /// </summary> public double Mebibits => As(InformationUnit.Mebibit); /// <summary> /// Get Information in Mebibytes. /// </summary> public double Mebibytes => As(InformationUnit.Mebibyte); /// <summary> /// Get Information in Megabits. /// </summary> public double Megabits => As(InformationUnit.Megabit); /// <summary> /// Get Information in Megabytes. /// </summary> public double Megabytes => As(InformationUnit.Megabyte); /// <summary> /// Get Information in Pebibits. /// </summary> public double Pebibits => As(InformationUnit.Pebibit); /// <summary> /// Get Information in Pebibytes. /// </summary> public double Pebibytes => As(InformationUnit.Pebibyte); /// <summary> /// Get Information in Petabits. /// </summary> public double Petabits => As(InformationUnit.Petabit); /// <summary> /// Get Information in Petabytes. /// </summary> public double Petabytes => As(InformationUnit.Petabyte); /// <summary> /// Get Information in Tebibits. /// </summary> public double Tebibits => As(InformationUnit.Tebibit); /// <summary> /// Get Information in Tebibytes. /// </summary> public double Tebibytes => As(InformationUnit.Tebibyte); /// <summary> /// Get Information in Terabits. /// </summary> public double Terabits => As(InformationUnit.Terabit); /// <summary> /// Get Information in Terabytes. /// </summary> public double Terabytes => As(InformationUnit.Terabyte); #endregion #region Static Methods /// <summary> /// Get unit abbreviation string. /// </summary> /// <param name="unit">Unit to get abbreviation for.</param> /// <returns>Unit abbreviation string.</returns> public static string GetAbbreviation(InformationUnit unit) { return GetAbbreviation(unit, null); } /// <summary> /// Get unit abbreviation string. /// </summary> /// <param name="unit">Unit to get abbreviation for.</param> /// <returns>Unit abbreviation string.</returns> /// <param name="cultureName">Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public static string GetAbbreviation(InformationUnit unit, [CanBeNull] string cultureName) { IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } #endregion #region Static Factory Methods /// <summary> /// Get Information from Bits. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static Information FromBits(double bits) { decimal value = (decimal) bits; return new Information(value, InformationUnit.Bit); } /// <summary> /// Get Information from Bytes. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static Information FromBytes(double bytes) { decimal value = (decimal) bytes; return new Information(value, InformationUnit.Byte); } /// <summary> /// Get Information from Exabits. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static Information FromExabits(double exabits) { decimal value = (decimal) exabits; return new Information(value, InformationUnit.Exabit); } /// <summary> /// Get Information from Exabytes. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static Information FromExabytes(double exabytes) { decimal value = (decimal) exabytes; return new Information(value, InformationUnit.Exabyte); } /// <summary> /// Get Information from Exbibits. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static Information FromExbibits(double exbibits) { decimal value = (decimal) exbibits; return new Information(value, InformationUnit.Exbibit); } /// <summary> /// Get Information from Exbibytes. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static Information FromExbibytes(double exbibytes) { decimal value = (decimal) exbibytes; return new Information(value, InformationUnit.Exbibyte); } /// <summary> /// Get Information from Gibibits. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static Information FromGibibits(double gibibits) { decimal value = (decimal) gibibits; return new Information(value, InformationUnit.Gibibit); } /// <summary> /// Get Information from Gibibytes. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static Information FromGibibytes(double gibibytes) { decimal value = (decimal) gibibytes; return new Information(value, InformationUnit.Gibibyte); } /// <summary> /// Get Information from Gigabits. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static Information FromGigabits(double gigabits) { decimal value = (decimal) gigabits; return new Information(value, InformationUnit.Gigabit); } /// <summary> /// Get Information from Gigabytes. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static Information FromGigabytes(double gigabytes) { decimal value = (decimal) gigabytes; return new Information(value, InformationUnit.Gigabyte); } /// <summary> /// Get Information from Kibibits. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static Information FromKibibits(double kibibits) { decimal value = (decimal) kibibits; return new Information(value, InformationUnit.Kibibit); } /// <summary> /// Get Information from Kibibytes. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static Information FromKibibytes(double kibibytes) { decimal value = (decimal) kibibytes; return new Information(value, InformationUnit.Kibibyte); } /// <summary> /// Get Information from Kilobits. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static Information FromKilobits(double kilobits) { decimal value = (decimal) kilobits; return new Information(value, InformationUnit.Kilobit); } /// <summary> /// Get Information from Kilobytes. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static Information FromKilobytes(double kilobytes) { decimal value = (decimal) kilobytes; return new Information(value, InformationUnit.Kilobyte); } /// <summary> /// Get Information from Mebibits. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static Information FromMebibits(double mebibits) { decimal value = (decimal) mebibits; return new Information(value, InformationUnit.Mebibit); } /// <summary> /// Get Information from Mebibytes. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static Information FromMebibytes(double mebibytes) { decimal value = (decimal) mebibytes; return new Information(value, InformationUnit.Mebibyte); } /// <summary> /// Get Information from Megabits. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static Information FromMegabits(double megabits) { decimal value = (decimal) megabits; return new Information(value, InformationUnit.Megabit); } /// <summary> /// Get Information from Megabytes. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static Information FromMegabytes(double megabytes) { decimal value = (decimal) megabytes; return new Information(value, InformationUnit.Megabyte); } /// <summary> /// Get Information from Pebibits. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static Information FromPebibits(double pebibits) { decimal value = (decimal) pebibits; return new Information(value, InformationUnit.Pebibit); } /// <summary> /// Get Information from Pebibytes. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static Information FromPebibytes(double pebibytes) { decimal value = (decimal) pebibytes; return new Information(value, InformationUnit.Pebibyte); } /// <summary> /// Get Information from Petabits. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static Information FromPetabits(double petabits) { decimal value = (decimal) petabits; return new Information(value, InformationUnit.Petabit); } /// <summary> /// Get Information from Petabytes. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static Information FromPetabytes(double petabytes) { decimal value = (decimal) petabytes; return new Information(value, InformationUnit.Petabyte); } /// <summary> /// Get Information from Tebibits. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static Information FromTebibits(double tebibits) { decimal value = (decimal) tebibits; return new Information(value, InformationUnit.Tebibit); } /// <summary> /// Get Information from Tebibytes. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static Information FromTebibytes(double tebibytes) { decimal value = (decimal) tebibytes; return new Information(value, InformationUnit.Tebibyte); } /// <summary> /// Get Information from Terabits. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static Information FromTerabits(double terabits) { decimal value = (decimal) terabits; return new Information(value, InformationUnit.Terabit); } /// <summary> /// Get Information from Terabytes. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> [Windows.Foundation.Metadata.DefaultOverload] public static Information FromTerabytes(double terabytes) { decimal value = (decimal) terabytes; return new Information(value, InformationUnit.Terabyte); } /// <summary> /// Dynamically convert from value and unit enum <see cref="InformationUnit" /> to <see cref="Information" />. /// </summary> /// <param name="value">Value to convert from.</param> /// <param name="fromUnit">Unit to convert from.</param> /// <returns>Information unit value.</returns> // Fix name conflict with parameter "value" [return: System.Runtime.InteropServices.WindowsRuntime.ReturnValueName("returnValue")] public static Information From(double value, InformationUnit fromUnit) { return new Information((decimal)value, fromUnit); } #endregion #region Static Parse Methods /// <summary> /// Parse a string with one or two quantities of the format "&lt;quantity&gt; &lt;unit&gt;". /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <example> /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// </example> /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> /// <exception cref="ArgumentException"> /// Expected string to have one or two pairs of quantity and unit in the format /// "&lt;quantity&gt; &lt;unit&gt;". Eg. "5.5 m" or "1ft 2in" /// </exception> /// <exception cref="AmbiguousUnitParseException"> /// More than one unit is represented by the specified unit abbreviation. /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. /// </exception> /// <exception cref="UnitsNetException"> /// If anything else goes wrong, typically due to a bug or unhandled case. /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish /// Units.NET exceptions from other exceptions. /// </exception> public static Information Parse(string str) { return Parse(str, null); } /// <summary> /// Parse a string with one or two quantities of the format "&lt;quantity&gt; &lt;unit&gt;". /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <example> /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// </example> /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> /// <exception cref="ArgumentException"> /// Expected string to have one or two pairs of quantity and unit in the format /// "&lt;quantity&gt; &lt;unit&gt;". Eg. "5.5 m" or "1ft 2in" /// </exception> /// <exception cref="AmbiguousUnitParseException"> /// More than one unit is represented by the specified unit abbreviation. /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. /// </exception> /// <exception cref="UnitsNetException"> /// If anything else goes wrong, typically due to a bug or unhandled case. /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish /// Units.NET exceptions from other exceptions. /// </exception> /// <param name="cultureName">Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public static Information Parse(string str, [CanBeNull] string cultureName) { IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return QuantityParser.Default.Parse<Information, InformationUnit>( str, provider, From); } /// <summary> /// Try to parse a string with one or two quantities of the format "&lt;quantity&gt; &lt;unit&gt;". /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <param name="result">Resulting unit quantity if successful.</param> /// <example> /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// </example> public static bool TryParse([CanBeNull] string str, out Information result) { return TryParse(str, null, out result); } /// <summary> /// Try to parse a string with one or two quantities of the format "&lt;quantity&gt; &lt;unit&gt;". /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <param name="result">Resulting unit quantity if successful.</param> /// <returns>True if successful, otherwise false.</returns> /// <example> /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// </example> /// <param name="cultureName">Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public static bool TryParse([CanBeNull] string str, [CanBeNull] string cultureName, out Information result) { IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return QuantityParser.Default.TryParse<Information, InformationUnit>( str, provider, From, out result); } /// <summary> /// Parse a unit string. /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <example> /// Length.ParseUnit("m", new CultureInfo("en-US")); /// </example> /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> /// <exception cref="UnitsNetException">Error parsing string.</exception> public static InformationUnit ParseUnit(string str) { return ParseUnit(str, null); } /// <summary> /// Parse a unit string. /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <example> /// Length.ParseUnit("m", new CultureInfo("en-US")); /// </example> /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> /// <exception cref="UnitsNetException">Error parsing string.</exception> /// <param name="cultureName">Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public static InformationUnit ParseUnit(string str, [CanBeNull] string cultureName) { IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return UnitParser.Default.Parse<InformationUnit>(str, provider); } public static bool TryParseUnit(string str, out InformationUnit unit) { return TryParseUnit(str, null, out unit); } /// <summary> /// Parse a unit string. /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <param name="unit">The parsed unit if successful.</param> /// <returns>True if successful, otherwise false.</returns> /// <example> /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// </example> /// <param name="cultureName">Name of culture (ex: "en-US") to use when parsing number and unit. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public static bool TryParseUnit(string str, [CanBeNull] string cultureName, out InformationUnit unit) { IFormatProvider provider = GetFormatProviderFromCultureName(cultureName); return UnitParser.Default.TryParse<InformationUnit>(str, provider, out unit); } #endregion #region Equality / IComparable public int CompareTo(object obj) { if(obj is null) throw new ArgumentNullException(nameof(obj)); if(!(obj is Information objInformation)) throw new ArgumentException("Expected type Information.", nameof(obj)); return CompareTo(objInformation); } // Windows Runtime Component does not allow public methods/ctors with same number of parameters: https://msdn.microsoft.com/en-us/library/br230301.aspx#Overloaded methods internal int CompareTo(Information other) { return _value.CompareTo(other.AsBaseNumericType(this.Unit)); } [Windows.Foundation.Metadata.DefaultOverload] public override bool Equals(object obj) { if(obj is null || !(obj is Information objInformation)) return false; return Equals(objInformation); } public bool Equals(Information other) { return _value.Equals(other.AsBaseNumericType(this.Unit)); } /// <summary> /// <para> /// Compare equality to another Information within the given absolute or relative tolerance. /// </para> /// <para> /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of /// this quantity's value to be considered equal. /// <example> /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). /// <code> /// var a = Length.FromMeters(2.0); /// var b = Length.FromInches(50.0); /// a.Equals(b, 0.01, ComparisonType.Relative); /// </code> /// </example> /// </para> /// <para> /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into /// this quantity's unit for comparison. /// <example> /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). /// <code> /// var a = Length.FromMeters(2.0); /// var b = Length.FromInches(50.0); /// a.Equals(b, 0.01, ComparisonType.Absolute); /// </code> /// </example> /// </para> /// <para> /// Note that it is advised against specifying zero difference, due to the nature /// of floating point operations and using System.Double internally. /// </para> /// </summary> /// <param name="other">The other quantity to compare to.</param> /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> /// <param name="comparisonType">The comparison type: either relative or absolute.</param> /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> public bool Equals(Information other, double tolerance, ComparisonType comparisonType) { if(tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); double thisValue = (double)this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>A hash code for the current Information.</returns> public override int GetHashCode() { return new { QuantityType, Value, Unit }.GetHashCode(); } #endregion #region Conversion Methods double IQuantity.As(object unit) => As((InformationUnit)unit); /// <summary> /// Convert to the unit representation <paramref name="unit" />. /// </summary> /// <returns>Value converted to the specified unit.</returns> public double As(InformationUnit unit) { if(Unit == unit) return Convert.ToDouble(Value); var converted = AsBaseNumericType(unit); return Convert.ToDouble(converted); } /// <summary> /// Converts this Information to another Information with the unit representation <paramref name="unit" />. /// </summary> /// <returns>A Information with the specified unit.</returns> public Information ToUnit(InformationUnit unit) { var convertedValue = AsBaseNumericType(unit); return new Information(convertedValue, unit); } /// <summary> /// Converts the current value + unit to the base unit. /// This is typically the first step in converting from one unit to another. /// </summary> /// <returns>The value in the base unit representation.</returns> private decimal AsBaseUnit() { switch(Unit) { case InformationUnit.Bit: return _value; case InformationUnit.Byte: return _value*8m; case InformationUnit.Exabit: return (_value) * 1e18m; case InformationUnit.Exabyte: return (_value*8m) * 1e18m; case InformationUnit.Exbibit: return (_value) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024); case InformationUnit.Exbibyte: return (_value*8m) * (1024m * 1024 * 1024 * 1024 * 1024 * 1024); case InformationUnit.Gibibit: return (_value) * (1024m * 1024 * 1024); case InformationUnit.Gibibyte: return (_value*8m) * (1024m * 1024 * 1024); case InformationUnit.Gigabit: return (_value) * 1e9m; case InformationUnit.Gigabyte: return (_value*8m) * 1e9m; case InformationUnit.Kibibit: return (_value) * 1024m; case InformationUnit.Kibibyte: return (_value*8m) * 1024m; case InformationUnit.Kilobit: return (_value) * 1e3m; case InformationUnit.Kilobyte: return (_value*8m) * 1e3m; case InformationUnit.Mebibit: return (_value) * (1024m * 1024); case InformationUnit.Mebibyte: return (_value*8m) * (1024m * 1024); case InformationUnit.Megabit: return (_value) * 1e6m; case InformationUnit.Megabyte: return (_value*8m) * 1e6m; case InformationUnit.Pebibit: return (_value) * (1024m * 1024 * 1024 * 1024 * 1024); case InformationUnit.Pebibyte: return (_value*8m) * (1024m * 1024 * 1024 * 1024 * 1024); case InformationUnit.Petabit: return (_value) * 1e15m; case InformationUnit.Petabyte: return (_value*8m) * 1e15m; case InformationUnit.Tebibit: return (_value) * (1024m * 1024 * 1024 * 1024); case InformationUnit.Tebibyte: return (_value*8m) * (1024m * 1024 * 1024 * 1024); case InformationUnit.Terabit: return (_value) * 1e12m; case InformationUnit.Terabyte: return (_value*8m) * 1e12m; default: throw new NotImplementedException($"Can not convert {Unit} to base units."); } } private decimal AsBaseNumericType(InformationUnit unit) { if(Unit == unit) return _value; var baseUnitValue = AsBaseUnit(); switch(unit) { case InformationUnit.Bit: return baseUnitValue; case InformationUnit.Byte: return baseUnitValue/8m; case InformationUnit.Exabit: return (baseUnitValue) / 1e18m; case InformationUnit.Exabyte: return (baseUnitValue/8m) / 1e18m; case InformationUnit.Exbibit: return (baseUnitValue) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024); case InformationUnit.Exbibyte: return (baseUnitValue/8m) / (1024m * 1024 * 1024 * 1024 * 1024 * 1024); case InformationUnit.Gibibit: return (baseUnitValue) / (1024m * 1024 * 1024); case InformationUnit.Gibibyte: return (baseUnitValue/8m) / (1024m * 1024 * 1024); case InformationUnit.Gigabit: return (baseUnitValue) / 1e9m; case InformationUnit.Gigabyte: return (baseUnitValue/8m) / 1e9m; case InformationUnit.Kibibit: return (baseUnitValue) / 1024m; case InformationUnit.Kibibyte: return (baseUnitValue/8m) / 1024m; case InformationUnit.Kilobit: return (baseUnitValue) / 1e3m; case InformationUnit.Kilobyte: return (baseUnitValue/8m) / 1e3m; case InformationUnit.Mebibit: return (baseUnitValue) / (1024m * 1024); case InformationUnit.Mebibyte: return (baseUnitValue/8m) / (1024m * 1024); case InformationUnit.Megabit: return (baseUnitValue) / 1e6m; case InformationUnit.Megabyte: return (baseUnitValue/8m) / 1e6m; case InformationUnit.Pebibit: return (baseUnitValue) / (1024m * 1024 * 1024 * 1024 * 1024); case InformationUnit.Pebibyte: return (baseUnitValue/8m) / (1024m * 1024 * 1024 * 1024 * 1024); case InformationUnit.Petabit: return (baseUnitValue) / 1e15m; case InformationUnit.Petabyte: return (baseUnitValue/8m) / 1e15m; case InformationUnit.Tebibit: return (baseUnitValue) / (1024m * 1024 * 1024 * 1024); case InformationUnit.Tebibyte: return (baseUnitValue/8m) / (1024m * 1024 * 1024 * 1024); case InformationUnit.Terabit: return (baseUnitValue) / 1e12m; case InformationUnit.Terabyte: return (baseUnitValue/8m) / 1e12m; default: throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } } #endregion #region ToString Methods /// <summary> /// Get default string representation of value and unit. /// </summary> /// <returns>String representation.</returns> public override string ToString() { return ToString(null); } /// <summary> /// Get string representation of value and unit. Using two significant digits after radix. /// </summary> /// <returns>String representation.</returns> /// <param name="cultureName">Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public string ToString([CanBeNull] string cultureName) { var provider = cultureName; return ToString(provider, 2); } /// <summary> /// Get string representation of value and unit. /// </summary> /// <param name="significantDigitsAfterRadix">The number of significant digits after the radix point.</param> /// <returns>String representation.</returns> /// <param name="cultureName">Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public string ToString(string cultureName, int significantDigitsAfterRadix) { var provider = cultureName; var value = Convert.ToDouble(Value); var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); return ToString(provider, format); } /// <summary> /// Get string representation of value and unit. /// </summary> /// <param name="format">String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively."</param> /// <param name="args">Arguments for string format. Value and unit are implicitly included as arguments 0 and 1.</param> /// <returns>String representation.</returns> /// <param name="cultureName">Name of culture (ex: "en-US") to use for localization and number formatting. Defaults to <see cref="GlobalConfiguration.DefaultCulture" /> if null.</param> public string ToString([CanBeNull] string cultureName, [NotNull] string format, [NotNull] params object[] args) { var provider = GetFormatProviderFromCultureName(cultureName); if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); provider = provider ?? GlobalConfiguration.DefaultCulture; var value = Convert.ToDouble(Value); var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } #endregion private static IFormatProvider GetFormatProviderFromCultureName([CanBeNull] string cultureName) { return cultureName != null ? new CultureInfo(cultureName) : (IFormatProvider)null; } } }
45.110338
337
0.600648
[ "MIT-feh" ]
Angerxzer/UnitsNet
UnitsNet.WindowsRuntimeComponent/GeneratedCode/Quantities/Information.g.cs
45,381
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/winnt.h in the Windows SDK for Windows 10.0.22000.0 // Original source is Copyright © Microsoft. All rights reserved. using System.Runtime.CompilerServices; namespace TerraFX.Interop.Windows; /// <include file='IMAGE_CE_RUNTIME_FUNCTION_ENTRY.xml' path='doc/member[@name="IMAGE_CE_RUNTIME_FUNCTION_ENTRY"]/*' /> public partial struct IMAGE_CE_RUNTIME_FUNCTION_ENTRY { /// <include file='IMAGE_CE_RUNTIME_FUNCTION_ENTRY.xml' path='doc/member[@name="IMAGE_CE_RUNTIME_FUNCTION_ENTRY.FuncStart"]/*' /> [NativeTypeName("DWORD")] public uint FuncStart; public uint _bitfield; /// <include file='IMAGE_CE_RUNTIME_FUNCTION_ENTRY.xml' path='doc/member[@name="IMAGE_CE_RUNTIME_FUNCTION_ENTRY.PrologLen"]/*' /> [NativeTypeName("DWORD : 8")] public uint PrologLen { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _bitfield & 0xFFu; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { _bitfield = (_bitfield & ~0xFFu) | (value & 0xFFu); } } /// <include file='IMAGE_CE_RUNTIME_FUNCTION_ENTRY.xml' path='doc/member[@name="IMAGE_CE_RUNTIME_FUNCTION_ENTRY.FuncLen"]/*' /> [NativeTypeName("DWORD : 22")] public uint FuncLen { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (_bitfield >> 8) & 0x3FFFFFu; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { _bitfield = (_bitfield & ~(0x3FFFFFu << 8)) | ((value & 0x3FFFFFu) << 8); } } /// <include file='IMAGE_CE_RUNTIME_FUNCTION_ENTRY.xml' path='doc/member[@name="IMAGE_CE_RUNTIME_FUNCTION_ENTRY.ThirtyTwoBit"]/*' /> [NativeTypeName("DWORD : 1")] public uint ThirtyTwoBit { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (_bitfield >> 30) & 0x1u; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { _bitfield = (_bitfield & ~(0x1u << 30)) | ((value & 0x1u) << 30); } } /// <include file='IMAGE_CE_RUNTIME_FUNCTION_ENTRY.xml' path='doc/member[@name="IMAGE_CE_RUNTIME_FUNCTION_ENTRY.ExceptionFlag"]/*' /> [NativeTypeName("DWORD : 1")] public uint ExceptionFlag { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (_bitfield >> 31) & 0x1u; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { _bitfield = (_bitfield & ~(0x1u << 31)) | ((value & 0x1u) << 31); } } }
32.310345
145
0.631804
[ "MIT" ]
reflectronic/terrafx.interop.windows
sources/Interop/Windows/Windows/um/winnt/IMAGE_CE_RUNTIME_FUNCTION_ENTRY.cs
2,813
C#
using System; using System.Collections; using System.Configuration; using System.Data; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using Interface.Security; using Application.Presentation; using Application.Common; using Interface.Clinical; using System.Text; using Interface.Administration; using System.IO; using System.Drawing; using PresentationApp.ClinicalForms.UserControl; namespace PresentationApp.ClinicalForms { public partial class frmClinical_Nigeria_AdultIE : LogPage { INigeriaARTCard NigAdultIE; IKNHStaticForms KNHStatic; DataTable dtmuiltselect; protected void Page_Load(object sender, EventArgs e) { FemaleControls(); if (Session["AppLocation"] == null || Session.Count == 0 || Session["AppUserID"].ToString() == "") { IQCareMsgBox.Show("SessionExpired", this); Response.Redirect("~/frmlogin.aspx", true); } if (!IsPostBack) { //(Master.FindControl("levelOneNavigationUserControl1").FindControl("lblRoot") as Label).Text = "Clinical Forms >> "; //(Master.FindControl("levelOneNavigationUserControl1").FindControl("lblheader") as Label).Text = "Adult Initial Evaluation"; //(Master.FindControl("levelTwoNavigationUserControl1").FindControl("lblformname") as Label).Text = "Adult Initial Evaluation"; BindChkboxlstControl(cblRiskFactors, "RiskFactors"); BindChkboxlstControl(cblShortTermEffects, "ShortTermEffects"); cblShortTermEffects.Attributes.Add("OnClick", "CheckBoxToggleShowHidePE('" + cblShortTermEffects.ClientID + "','divshorttermeffecttxt','Other Specify','" + txtOtherShortTermEffects.ClientID + "')"); BindChkboxlstControl(cblLongTermEffects, "LongTermEffects"); cblLongTermEffects.Attributes.Add("OnClick", "CheckBoxToggleShowHidePE('" + cblLongTermEffects.ClientID + "','divlongtermeffecttxt','Other specify','" + txtOtherLongtermEffects.ClientID + "')"); BindControl(rblassessment, "NigeriaAssessment"); validate(); UserControlKNH_NextAppointment1.rdoTCAYes.Checked = true; } } public void BindControl(Control cntrl, string fieldname) { DataTable thedeCodeDT = new DataTable(); IQCareUtils iQCareUtils = new IQCareUtils(); BindFunctions BindManager = new BindFunctions(); DataSet theDSXML = new DataSet(); theDSXML.ReadXml(MapPath("..\\XMLFiles\\AllMasters.con")); DataView theCodeDV = new DataView(theDSXML.Tables["MST_CODE"]); theCodeDV.RowFilter = "DeleteFlag=0 and Name='" + fieldname + "'"; DataTable theCodeDT = (DataTable)iQCareUtils.CreateTableFromDataView(theCodeDV); DataView theDV = new DataView(theDSXML.Tables["MST_DECODE"]); if (fieldname.ToString() != "") { if (theCodeDT.Rows.Count > 0) { theDV.RowFilter = "DeleteFlag=0 and SystemID IN(0," + Convert.ToString(Session["SystemId"]) + ") and CodeID=" + theCodeDT.Rows[0]["CodeId"]; theDV.Sort = "SRNo ASC"; thedeCodeDT = (DataTable)iQCareUtils.CreateTableFromDataView(theDV); } if (cntrl is CheckBoxList) { if (thedeCodeDT.Rows.Count > 0) { BindManager.BindCheckedList((CheckBoxList)cntrl, thedeCodeDT, "Name", "ID"); } } else if (cntrl is DropDownList) { if (thedeCodeDT.Rows.Count > 0) { BindManager.BindCombo((DropDownList)cntrl, thedeCodeDT, "Name", "ID"); } } else if (cntrl is RadioButtonList) { if (thedeCodeDT.Rows.Count > 0) { BindManager.RadioButtonList((RadioButtonList)cntrl, thedeCodeDT, "Name", "ID"); } } } else { theDV = new DataView(theDSXML.Tables["MST_DECODE"]); if (theDV.Table.Rows.Count > 0) { theDV.RowFilter = "DeleteFlag=0 and SystemID IN(0," + Convert.ToString(Session["SystemId"]) + ") and CodeID=17 and ModuleId=209"; theDV.Sort = "SRNo ASC"; thedeCodeDT = new DataTable(); thedeCodeDT = (DataTable)iQCareUtils.CreateTableFromDataView(theDV); } if (cntrl is CheckBoxList) { if (thedeCodeDT.Rows.Count > 0) { BindManager.BindCheckedList((CheckBoxList)cntrl, thedeCodeDT, "Name", "ID"); } } else if (cntrl is DropDownList) { if (thedeCodeDT.Rows.Count > 0) { BindManager.BindCombo((DropDownList)cntrl, thedeCodeDT, "Name", "ID"); } } else if (cntrl is RadioButtonList) { if (thedeCodeDT.Rows.Count > 0) { BindManager.RadioButtonList((RadioButtonList)cntrl, thedeCodeDT, "Name", "ID"); } } } } protected void Page_PreRender(object sender, EventArgs e) { if (IsPostBack != true) { if (Convert.ToInt32(Session["PatientVisitId"]) > 0) { BindExistingData(); } else { txtVisitDate.Value = DateTime.Now.ToString("dd-MMM-yyyy"); } } ErrorLoad(); checkIfPreviuosTabSaved(); } public void FemaleControls() { if (!object.Equals(Session["PatientSex"], null))//Add this line by Rahmat for check session object is created or not(16-Feb-17) { if (Session["PatientSex"].ToString() == "Male") { Page.ClientScript.RegisterStartupScript(this.GetType(), "trNigPregnancy", "ShowHide('trNigPregnancy','hide');", true); } } } private void visibleDiv(String divId) { String script = ""; script = "<script language = 'javascript' defer ='defer' id = '" + divId + "'>\n"; script += "ShowHide('" + divId + "','show');\n"; script += "</script>\n"; RegisterStartupScript("'" + divId + "'", script); } public void ErrorLoad() { if (UcAdherence.rdoTreatmentIntrupted.SelectedValue == "0") { visibleDiv("DIVInturptedReason"); } if (UcAdherence.rblstopped.SelectedValue == "0") { visibleDiv("DIVStopedReason"); } if (UserControlKNH_NextAppointment1.rdoTCANo.Checked == true) { visibleDiv("trCareEnd"); } else if (UserControlKNH_NextAppointment1.rdoTCAYes.Checked == true) { visibleDiv("trNextAppointment"); } for (int i = 0; i < this.UcPc.gvPresentingComplaints.Rows.Count; i++) { CheckBox chkPComplaints = (CheckBox)UcPc.gvPresentingComplaints.Rows[i].FindControl("ChkPresenting"); if (chkPComplaints.Checked) { if (chkPComplaints.Text.ToLower() == "other") { visibleDiv("DivOther"); } if (chkPComplaints.Text.ToUpper() == "NONE") { ScriptManager.RegisterStartupScript(this, GetType(), "togglePCChecked", "togglePC('" + chkPComplaints.ClientID + "');", true); } } } if (rdopregnantyesno.SelectedValue == "1") { visibleDiv("hideFP"); } if (UCTreatment.ChkLabEvaluation.Checked) { visibleDiv("DivLabEval"); } if (UCTreatment.chkregimen.Checked) { visibleDiv("DivPrescDrug"); } for (int i = 0; i < this.UCTreatment.gvtreatment.Rows.Count; i++) { CheckBox Chktreatment = (CheckBox)UCTreatment.gvtreatment.Rows[i].FindControl("Chktreatment"); if (Chktreatment.Checked) { if (Chktreatment.Text.ToLower() == "other referrals") { visibleDiv("DivTreatmentOther"); } } } if (UCTreatment.ddlTreatmentplan.SelectedItem.Text.ToLower() == "change treatment") { visibleDiv("divARTchangecode"); } for (int i = 0; i < this.UcAdherence.gvdisclosed.Rows.Count; i++) { CheckBox Chkdisclosed = (CheckBox)UcAdherence.gvdisclosed.Rows[i].FindControl("Chkdisclosed"); if (Chkdisclosed.Checked) { if (Chkdisclosed.Text.ToLower() == "other") { visibleDiv("DivDiscloseOther"); } } } } private Hashtable HtParameters(string Tabname) { dtmuiltselect = CreateTempTable(); Hashtable theHT = new Hashtable(); try { theHT.Add("patientID", Session["PatientId"]); theHT.Add("visitID", Session["PatientVisitId"]); theHT.Add("locationID", Session["AppLocationId"]); // Visit date: theHT.Add("visitDate", txtVisitDate.Value); if (Tabname.ToString() == "Clinical History") { //////////Additional Presenting Complaints////////////// theHT.Add("OtherPresentingComplaints", UcPc.txtOtherPresentingComplaints.Text); theHT.Add("PresentingComplaintsAdditionalNotes", UcPc.txtAdditionalComplaints.Text); //////////Medical History (Disease, diagnosis& treatment)////////////// theHT.Add("MedicalHistoryAdditionalComplaints", idNigeriaMedical.txtAdditionalComplaints.Text); theHT.Add("MedicalHistoryLastHistory", this.idNigeriaMedical.txtlastmedical.Text); theHT.Add("MedicalHistoryFamilyHistory", idNigeriaMedical.txtfamhistory.Text); theHT.Add("MedicalHistoryHospitalization", idNigeriaMedical.txthospitalization.Text); //////////Pregnancy////////////// theHT.Add("Pregnant", rdopregnantyesno.SelectedValue); theHT.Add("LMPDate", txtLMPdate.Value); theHT.Add("EDDDate", txtEDDDate.Value); theHT.Add("GestationalAge", txtgestage.Text); } else if (Tabname.ToString() == "HIV History") { //////////Medical History (Disease, diagnosis& treatment)////////////// int PrevARVExposure = UcPriorArt.rbtnknownYes.Checked ? 1 : UcPriorArt.rbtnknownNo.Checked ? 0 : 9; theHT.Add("PrevARVExposure", PrevARVExposure); theHT.Add("ARTTransferinFrom", UcPriorArt.ddlfacilityname.SelectedValue); theHT.Add("durationcarefrom", UcPriorArt.txtdurationfrom.Value); theHT.Add("durationcareto", UcPriorArt.txtdurationto.Value); theHT.Add("EntryType", UcPriorArt.ddlentrytype.SelectedValue); //////////HIV Related History////////////// theHT.Add("LatestCD4", txtlatestcd4number.Text); theHT.Add("LatestCD4Date", dtlatestcd4date.Value); theHT.Add("LowestCD4", txtlatestcd4number.Text); theHT.Add("LowestCD4Date", txtlbllowestCD4Date.Value); theHT.Add("LatestViralLoad", txtlatestViralLoadCount.Text); theHT.Add("LatestViralLoadDate", txtlatestViralLoadDate.Value); theHT.Add("ComplaintOther", UcCurrentMed.txtOtherComplaints.Text); theHT.Add("ServiceEntry", ddlreferredfrom.SelectedValue); theHT.Add("ParticipatedAdhernce", UcAdherence.rbladherenceYesNo.SelectedValue); theHT.Add("MissedArv3days", UcAdherence.rblmissedarvYesNo.SelectedValue); theHT.Add("ReasomMissedARV", UcAdherence.ddlReasomMissed.SelectedValue); theHT.Add("TreatmentIntrupted", UcAdherence.rdoTreatmentIntrupted.SelectedValue); theHT.Add("IntrupptedDate", UcAdherence.txtdtIntrupptedDate.Value); theHT.Add("intrpdays", UcAdherence.txtintrpdays.Text); theHT.Add("ReasonInterrupted", UcAdherence.ddlreasonInterrupted.SelectedValue); theHT.Add("Treatmentstopped", UcAdherence.rblstopped.SelectedValue); theHT.Add("StopedReasonDate", UcAdherence.txtStopedReasonDate.Value); theHT.Add("stoppeddays", UcAdherence.txtstoppeddays.Text); theHT.Add("StopedReason", UcAdherence.ddlStopedReason.SelectedValue); theHT.Add("Otherdisclosed", UcAdherence.txtOtherdisclosed.Text); theHT.Add("hivdiscussed", UcAdherence.txthivdiscussed.Text); theHT.Add("supportgroup", UcAdherence.rblsupportgroup.SelectedValue); theHT.Add("OtherShortTermEffects", txtOtherShortTermEffects.Text); theHT.Add("OtherLongtermEffects", txtOtherLongtermEffects.Text); } if (Tabname.ToString() == "Examination") { #region "Vital Signs" if (this.idVitalSign.txtTemp.Text != "") { theHT.Add("Temp", this.idVitalSign.txtTemp.Text.ToString()); } else { theHT.Add("Temp", "0"); } if (this.idVitalSign.txtRR.Text != "") { theHT.Add("RR", this.idVitalSign.txtRR.Text); } else { theHT.Add("RR", "0"); } if (this.idVitalSign.txtHeight.Text != "") { theHT.Add("height", this.idVitalSign.txtHeight.Text); } else { theHT.Add("height", "0"); } if (this.idVitalSign.txtWeight.Text != "") { theHT.Add("weight", this.idVitalSign.txtWeight.Text); } else { theHT.Add("weight", "0"); } if (this.idVitalSign.txtBPDiastolic.Text != "") { theHT.Add("BPDiastolic", this.idVitalSign.txtBPDiastolic.Text); } else { theHT.Add("BPDiastolic", "0"); } if (this.idVitalSign.txtBPSystolic.Text != "") { theHT.Add("BPSystolic", this.idVitalSign.txtBPSystolic.Text); } else { theHT.Add("BPSystolic", "0"); } theHT.Add("BMIz", this.idVitalSign.txtBMI.Text); #endregion theHT.Add("OtherNigeriaPEGeneral", UcPE.txtOtherNigeriaPEGeneral.Text); theHT.Add("OtherNigeriaPESkin", UcPE.txtOtherNigeriaPESkin.Text); theHT.Add("OtherNigeriaPEHeadEyeEnt", UcPE.txtOtherNigeriaPEHeadEyeEnt.Text); theHT.Add("OtherNigeriaPECardiovascular", UcPE.txtOtherNigeriaPECardiovascular.Text); theHT.Add("OtherNigeriaPEBreast", UcPE.txtOtherNigeriaPEBreast.Text); theHT.Add("OtherNigeriaPEGenitalia", UcPE.txtOtherNigeriaPEGenitalia.Text); theHT.Add("txtOtherNigeriaPERespiratory", UcPE.txtOtherNigeriaPERespiratory.Text); theHT.Add("OtherNigeriaPEGastrointestinal", UcPE.txtOtherNigeriaPEGastrointestinal.Text); theHT.Add("OtherNigeriaPENeurological", UcPE.txtOtherNigeriaPENeurological.Text); theHT.Add("OtherNigeriaPEMentalstatus", UcPE.txtOtherNigeriaPEMentalstatus.Text); theHT.Add("OtherAdditionaldetailedfindings", UcPE.txtOtherAdditionaldetailedfindings.Text); theHT.Add("Assessment", rblassessment.SelectedValue); theHT.Add("AssessmentDesc", txtAssessmentNotes.Text); theHT.Add("WHOStage", UcWhostaging.ddlwhostage1.SelectedValue); } if (Tabname.ToString() == "Management") { theHT.Add("LabEvaluation", UCTreatment.ChkLabEvaluation.Checked ? 1 : 0); theHT.Add("LabReview", UCTreatment.UcLabEval.txtlabdiagnosticinput.Text); theHT.Add("OtherReferrals", UCTreatment.txtOtherReferrals.Text); theHT.Add("Regimen", UCTreatment.chkregimen.Checked ? 1 : 0); theHT.Add("ARVTherapyPlan", UCTreatment.ddlTreatmentplan.SelectedValue); theHT.Add("OtherARVChangePlan", UCTreatment.txtSpecifyotherARTchangereason.Text); } return theHT; } catch (Exception ex) { throw ex; } } private void GetCheckBoxListData(string savetabname) { dtmuiltselect = CreateTempTable(); if (savetabname == "Clinical History" || tabControl.ActiveTabIndex == 0) { savetabname = "Clinical History"; dtmuiltselect = PresentingComplaints(dtmuiltselect, "PresentingComplaints"); dtmuiltselect = MedicalHistory(dtmuiltselect, "NigeriaSymptoms"); dtmuiltselect = GetCheckBoxListValues(cblRiskFactors, dtmuiltselect, "RiskFactors"); } else if (savetabname == "HIV History" || tabControl.ActiveTabIndex == 1) { savetabname = "HIV History"; dtmuiltselect = CurrentMedication(dtmuiltselect, "NigeriaCurrentMedication"); dtmuiltselect = DisclosedStatus(dtmuiltselect, "NigeriaHIVDisclosure"); dtmuiltselect = GetCheckBoxListValues(cblShortTermEffects, dtmuiltselect, "ShortTermEffects"); dtmuiltselect = GetCheckBoxListValues(cblLongTermEffects, dtmuiltselect, "LongTermEffects"); } else if (savetabname == "Examination" || tabControl.ActiveTabIndex == 2) { savetabname = "Examination"; dtmuiltselect = GetCheckBoxListValues(UcPE.cblNigeriaPEGeneral, dtmuiltselect, "NigeriaPEGeneral"); dtmuiltselect = GetCheckBoxListValues(UcPE.cblNigeriaPESkin, dtmuiltselect, "NigeriaPESkin"); dtmuiltselect = GetCheckBoxListValues(UcPE.cblNigeriaPEHeadEyeEnt, dtmuiltselect, "NigeriaPEHeadEyeEnt"); dtmuiltselect = GetCheckBoxListValues(UcPE.cblNigeriaPECardiovascular, dtmuiltselect, "NigeriaPECardiovascular"); dtmuiltselect = GetCheckBoxListValues(UcPE.cblNigeriaPEBreast, dtmuiltselect, "NigeriaPEBreast"); dtmuiltselect = GetCheckBoxListValues(UcPE.cblNigeriaPEGenitalia, dtmuiltselect, "NigeriaPEGenitalia"); dtmuiltselect = GetCheckBoxListValues(UcPE.cblNigeriaPERespiratory, dtmuiltselect, "NigeriaPERespiratory"); dtmuiltselect = GetCheckBoxListValues(UcPE.cblNigeriaPEGastrointestinal, dtmuiltselect, "NigeriaPEGastrointestinal"); dtmuiltselect = GetCheckBoxListValues(UcPE.cblNigeriaPENeurological, dtmuiltselect, "NigeriaPENeurological"); dtmuiltselect = GetCheckBoxListValues(UcPE.cblNigeriaPEMentalstatus, dtmuiltselect, "NigeriaPEMentalstatus"); //WHO Stage I dtmuiltselect = InsertMultiSelectList(UcWhostaging.gvWHO1, dtmuiltselect, "NigeriaWHOStageIConditions"); //// WHO Stage II dtmuiltselect = InsertMultiSelectList(UcWhostaging.gvWHO2, dtmuiltselect, "NigeriaWHOStageIIConditions"); //// WHO Stage III dtmuiltselect = InsertMultiSelectList(UcWhostaging.gvWHO3, dtmuiltselect, "NigeriaWHOStageIIIConditions"); //// WHO Stage IV dtmuiltselect = InsertMultiSelectList(UcWhostaging.gvWHO4, dtmuiltselect, "NigeriaWHOStageIVConditions"); } else if (savetabname == "Management" || tabControl.ActiveTabIndex == 3) { savetabname = "Management"; dtmuiltselect = TreatmentLab(dtmuiltselect, "NigeriaListLabEvaluation"); dtmuiltselect = EnrollIn(dtmuiltselect, "NigeriaListEnrollin"); dtmuiltselect = GetCheckBoxListValues(UCTreatment.chklistARTchangecode, dtmuiltselect, "NigeriaARVTreamentChangeReason"); } } private DataTable PresentingComplaints(DataTable dtprescompl, string name) { GridView gdview = (GridView)UcPc.FindControl("gvPresentingComplaints"); foreach (GridViewRow row in gdview.Rows) { DataRow dr = dtprescompl.NewRow(); CheckBox chk = (CheckBox)row.FindControl("ChkPresenting"); TextBox txt = (TextBox)row.FindControl("txtPresenting"); Label lbl = (Label)row.FindControl("lblPresenting"); if (chk.Checked) { dr["ID"] = Convert.ToInt32(lbl.Text); dr["FieldName"] = name; if (txt.Text != "") { dr["Other_Notes"] = txt.Text; } dtprescompl.Rows.Add(dr); } } return dtprescompl; } private DataTable MedicalHistory(DataTable dtprescompl, string name) { GridView gdview = (GridView)idNigeriaMedical.FindControl("gvMedicalHistory"); foreach (GridViewRow row in gdview.Rows) { DataRow dr = dtprescompl.NewRow(); CheckBox chk = (CheckBox)row.FindControl("ChkMedical"); TextBox txt = (TextBox)row.FindControl("txtMedical"); Label lbl = (Label)row.FindControl("lblMedical"); if (chk.Checked) { dr["ID"] = Convert.ToInt32(lbl.Text); dr["FieldName"] = name; if (txt.Text != "") { dr["Other_Notes"] = txt.Text; } dtprescompl.Rows.Add(dr); } } return dtprescompl; } private DataTable CurrentMedication(DataTable dtprescompl, string name) { GridView gdview = (GridView)UcCurrentMed.FindControl("gvcurrentmedication"); foreach (GridViewRow row in gdview.Rows) { DataRow dr = dtprescompl.NewRow(); CheckBox chk = (CheckBox)row.FindControl("Chkmedication"); Label lbl = (Label)row.FindControl("lblmedication"); if (chk.Checked) { dr["ID"] = Convert.ToInt32(lbl.Text); dr["FieldName"] = name; dtprescompl.Rows.Add(dr); } } return dtprescompl; } private DataTable DisclosedStatus(DataTable dtprescompl, string name) { GridView gdview = (GridView)UcAdherence.FindControl("gvdisclosed"); foreach (GridViewRow row in gdview.Rows) { DataRow dr = dtprescompl.NewRow(); CheckBox chk = (CheckBox)row.FindControl("Chkdisclosed"); Label lbl = (Label)row.FindControl("lbldisclosed"); if (chk.Checked) { dr["ID"] = Convert.ToInt32(lbl.Text); dr["FieldName"] = name; dtprescompl.Rows.Add(dr); } } return dtprescompl; } private DataTable InsertMultiSelectList(GridView gdview, DataTable dt, string fieldname) { foreach (GridViewRow row in gdview.Rows) { DataRow dr = dt.NewRow(); if (fieldname == "NigeriaWHOStageIConditions") { CheckBox chk = (CheckBox)row.FindControl("Chkwho1"); Label lbl = (Label)row.FindControl("lblwho1"); if (chk.Checked) { dr["ID"] = Convert.ToInt32(lbl.Text); dr["FieldName"] = fieldname; dt.Rows.Add(dr); } } if (fieldname == "NigeriaWHOStageIIConditions") { CheckBox chk = (CheckBox)row.FindControl("Chkwho2"); Label lbl = (Label)row.FindControl("lblwho2"); if (chk.Checked) { dr["ID"] = Convert.ToInt32(lbl.Text); dr["FieldName"] = fieldname; dt.Rows.Add(dr); } } if (fieldname == "NigeriaWHOStageIIIConditions") { CheckBox chk = (CheckBox)row.FindControl("Chkwho3"); Label lbl = (Label)row.FindControl("lblwho3"); if (chk.Checked) { dr["ID"] = Convert.ToInt32(lbl.Text); dr["FieldName"] = fieldname; dt.Rows.Add(dr); } } if (fieldname == "NigeriaWHOStageIVConditions") { CheckBox chk = (CheckBox)row.FindControl("Chkwho4"); Label lbl = (Label)row.FindControl("lblwho4"); if (chk.Checked) { dr["ID"] = Convert.ToInt32(lbl.Text); dr["FieldName"] = fieldname; dt.Rows.Add(dr); } } } return dt; } private DataTable TreatmentLab(DataTable dtprescompl, string name) { GridView gdview = (GridView)UCTreatment.FindControl("gvtreatment"); foreach (GridViewRow row in gdview.Rows) { DataRow dr = dtprescompl.NewRow(); CheckBox chk = (CheckBox)row.FindControl("Chktreatment"); Label lbl = (Label)row.FindControl("lbltreatment"); if (chk.Checked) { dr["ID"] = Convert.ToInt32(lbl.Text); dr["FieldName"] = name; dtprescompl.Rows.Add(dr); } } return dtprescompl; } private DataTable EnrollIn(DataTable dtprescompl, string name) { GridView gdview = (GridView)UCTreatment.FindControl("gvenrollin"); foreach (GridViewRow row in gdview.Rows) { DataRow dr = dtprescompl.NewRow(); CheckBox chk = (CheckBox)row.FindControl("Chkenrollin"); Label lbl = (Label)row.FindControl("lblenrollin"); if (chk.Checked) { dr["ID"] = Convert.ToInt32(lbl.Text); dr["FieldName"] = name; dtprescompl.Rows.Add(dr); } } return dtprescompl; } private DataTable PriorART() { DataTable tbl = CreateTempTable(); if (Session["PriorGridData"] != null) { DataTable Gridtbl = (DataTable)Session["PriorGridData"] as DataTable; foreach (DataRow row in Gridtbl.Rows) { DataRow dr; dr = tbl.NewRow(); dr["DateField1"] = row["DurationFromDate"]; dr["DateField2"] = row["DurationToDate"]; dr["ID"] = row["FacilityId"]; dr["NumericField"] = row["EntrytypeId"]; tbl.Rows.Add(dr); } } return tbl; } private void bindDisclosure(DataTable thedt) { IQCareUtils iQCareUtils = new IQCareUtils(); DataTable dt = new DataTable(); string script = string.Empty; if (thedt.Rows.Count > 0) { DataView theDV = new DataView(thedt); theDV.RowFilter = "FieldName='NigeriaHIVDisclosure'"; dt = (DataTable)iQCareUtils.CreateTableFromDataView(theDV); for (int j = 0; j <= dt.Rows.Count - 1; j++) { for (int i = 0; i < this.UcAdherence.gvdisclosed.Rows.Count; i++) { Label lbldisclosed = (Label)UcAdherence.gvdisclosed.Rows[i].FindControl("lbldisclosed"); CheckBox Chkdisclosed = (CheckBox)UcAdherence.gvdisclosed.Rows[i].FindControl("Chkdisclosed"); if (Convert.ToInt32(dt.Rows[j]["ValueId"]) == Convert.ToInt32(lbldisclosed.Text)) { if (dt.Rows[j]["Name"].ToString().ToLower() == "other") { visibleDiv("DivDiscloseOther", "show"); } Chkdisclosed.Checked = true; if (dt.Rows[j]["Name"].ToString().ToUpper() == "NO ONE") { String pcscript = ""; pcscript = "<script language = 'javascript' defer ='defer' id = 'toggleDisclosedPC'>\n"; pcscript += "toggleDisclosedPC('" + Chkdisclosed.ClientID + "')\n"; pcscript += "</script>\n"; RegisterStartupScript("'toggleDisclosedPC'", pcscript); } } } } } } public void BindChkboxlstControl(CheckBoxList chklst, string fieldname) { DataTable thedeCodeDT = new DataTable(); IQCareUtils iQCareUtils = new IQCareUtils(); BindFunctions BindManager = new BindFunctions(); DataSet theDSXML = new DataSet(); theDSXML.ReadXml(MapPath("..\\XMLFiles\\AllMasters.con")); DataView theCodeDV = new DataView(theDSXML.Tables["MST_CODE"]); theCodeDV.RowFilter = "DeleteFlag=0 and Name='" + fieldname + "'"; DataTable theCodeDT = (DataTable)iQCareUtils.CreateTableFromDataView(theCodeDV); DataView theDV = new DataView(theDSXML.Tables["MST_DECODE"]); if (theCodeDT.Rows.Count > 0) { theDV.RowFilter = "DeleteFlag=0 and SystemID IN(0," + Convert.ToString(Session["SystemId"]) + ") and CodeID=" + theCodeDT.Rows[0]["CodeId"]; theDV.Sort = "SRNo ASC"; thedeCodeDT = (DataTable)iQCareUtils.CreateTableFromDataView(theDV); } if (thedeCodeDT.Rows.Count > 0) { BindManager.BindCheckedList(chklst, thedeCodeDT, "Name", "ID"); } theDV = new DataView(theDSXML.Tables["MST_DECODE"]); if (theDV.Table.Rows.Count > 0) { theDV.RowFilter = "DeleteFlag=0 and SystemID IN(0," + Convert.ToString(Session["SystemId"]) + ") and CodeID=17 and ModuleId=209"; theDV.Sort = "SRNo ASC"; thedeCodeDT = new DataTable(); thedeCodeDT = (DataTable)iQCareUtils.CreateTableFromDataView(theDV); } if (thedeCodeDT.Rows.Count > 0) { BindManager.BindCombo(ddlreferredfrom, thedeCodeDT, "Name", "ID"); } } public void Save(int dqchk) { int tabindex = 0; string savetabname = tabControl.ActiveTab.HeaderText.ToString(); if (fieldValidation(savetabname) == false) { //ErrorLoad(); return; } Hashtable theHT = HtParameters(savetabname); GetCheckBoxListData(savetabname); string tabname = string.Empty; DataSet DsReturns = new DataSet(); NigAdultIE = (INigeriaARTCard)ObjectFactory.CreateInstance("BusinessProcess.Clinical.BNigeriaARTCard, BusinessProcess.Clinical"); if (savetabname == "Clinical History" || tabControl.ActiveTabIndex == 0) { savetabname = "Clinical History"; DsReturns = NigAdultIE.SaveUpdateNigeriaAdultIEClinicalHistoryData(theHT, dtmuiltselect, dqchk, Convert.ToInt32(Session["AppUserId"])); tabindex = 1; } else if (savetabname == "HIV History" || tabControl.ActiveTabIndex == 1) { savetabname = "HIV History"; DataTable dtPrior = PriorART(); DsReturns = NigAdultIE.SaveUpdateNigeriaAdultIEHIVHistoryData(theHT, dtmuiltselect, dqchk, Convert.ToInt32(Session["AppUserId"]), dtPrior); tabindex = 2; } else if (savetabname == "Examination" || tabControl.ActiveTabIndex == 2) { DsReturns = NigAdultIE.SaveUpdateNigeriaAdultIEExaminationData(theHT, dtmuiltselect, dqchk, Convert.ToInt32(Session["AppUserId"])); tabindex = 3; } else if (savetabname == "Management" || tabControl.ActiveTabIndex == 3) { DsReturns = NigAdultIE.SaveUpdateNigeriaAdultIEManagementData(theHT, dtmuiltselect, dqchk, Convert.ToInt32(Session["AppUserId"])); tabindex = 4; } Session["Redirect"] = "0"; if (Convert.ToInt32(DsReturns.Tables[0].Rows[0]["Visit_Id"]) > 0) { Session["PatientVisitId"] = Convert.ToInt32(DsReturns.Tables[0].Rows[0]["Visit_Id"]); SaveCancel(savetabname); checkIfPreviuosTabSaved(); if (tabindex < 4) { tabControl.ActiveTabIndex = tabindex; } } } public void checkIfPreviuosTabSaved() { KNHStatic = (IKNHStaticForms)ObjectFactory.CreateInstance("BusinessProcess.Clinical.BKNHStaticForms, BusinessProcess.Clinical"); DataSet dsClinical = new DataSet(); dsClinical = KNHStatic.CheckIfPreviuosTabSaved("NigAdultIEClinicalHis", Convert.ToInt32(Session["PatientVisitId"])); buttonEnabledAndDisabled(dsClinical, btnHIVHistorySave, btnHIVHistoryPrint); DataSet dsHIV = new DataSet(); dsHIV = KNHStatic.CheckIfPreviuosTabSaved("NigAdultIEHIVHis", Convert.ToInt32(Session["PatientVisitId"])); buttonEnabledAndDisabled(dsHIV, btnExaminationSave, btnExaminationPrint); DataSet dsExam = new DataSet(); dsExam = KNHStatic.CheckIfPreviuosTabSaved("NigAdultIEExam", Convert.ToInt32(Session["PatientVisitId"])); buttonEnabledAndDisabled(dsExam, btnSaveMgt, btnPrintMgt); //For Signature IPatientKNHPEP KNHPEP; KNHPEP = (IPatientKNHPEP)ObjectFactory.CreateInstance("BusinessProcess.Clinical.BPatientKNHPEP, BusinessProcess.Clinical"); DataTable dtSignature = KNHPEP.GetSignature(Convert.ToInt32(ApplicationAccess.NigeriaAdultIE), Convert.ToInt32(Session["PatientVisitId"])); if (dtSignature.Rows.Count > 0) { foreach (DataRow dr in dtSignature.Rows) { if (dr["TabName"].ToString() == "NigAdultIEClinicalHis") this.UserControlKNH_SignatureCH.lblSignature.Text = dr["UserName"].ToString(); if (dr["TabName"].ToString() == "NigAdultIEHIVHis") this.UserControlKNH_SignatureHH.lblSignature.Text = dr["UserName"].ToString(); if (dr["TabName"].ToString() == "NigAdultIEExam") this.UserControlKNH_SignatureExamination.lblSignature.Text = dr["UserName"].ToString(); if (dr["TabName"].ToString() == "NigAdultIEMgt") this.UserControlKNH_SignatureMgt.lblSignature.Text = dr["UserName"].ToString(); } } dtSignature.Dispose(); dsClinical.Dispose(); dsHIV.Dispose(); dsExam.Dispose(); //dsMgt.Dispose(); } private void buttonEnabledAndDisabled(DataSet ds, Button btnSave, Button btnPrint) { if (ds.Tables[0].Rows.Count == 0) { btnSave.Enabled = false; btnPrint.Enabled = false; } else { btnSave.Enabled = true; btnPrint.Enabled = true; securityPertab(); } } public void securityPertab() { IPatientKNHPEP KNHPEP = (IPatientKNHPEP)ObjectFactory.CreateInstance("BusinessProcess.Clinical.BPatientKNHPEP, BusinessProcess.Clinical"); DataTable thePEPDS = KNHPEP.GetTabID(260); IQCareUtils iQCareUtils = new IQCareUtils(); DataTable thedt = new DataTable(); DataView theDV = new DataView(thePEPDS); theDV.RowFilter = "TabName='NigAdultIEClinicalHis'"; thedt = (DataTable)iQCareUtils.CreateTableFromDataView(theDV); AuthenticationManager Authentication = new AuthenticationManager(); //Clinical History if (thedt.Rows.Count > 0) { Authentication.TabUserRights(btnClinicalHistorySave, btnClinicalHistoryPrint, 260, Convert.ToInt32(thedt.Rows[0]["TabId"])); } //HIV HIstory thedt = new DataTable(); theDV = new DataView(thePEPDS); theDV.RowFilter = "TabName='NigAdultIEHIVHis'"; thedt = (DataTable)iQCareUtils.CreateTableFromDataView(theDV); Authentication.TabUserRights(btnHIVHistorySave, btnHIVHistoryPrint, 260, Convert.ToInt32(thedt.Rows[0]["TabId"])); //Examination thedt = new DataTable(); theDV = new DataView(thePEPDS); theDV.RowFilter = "TabName='NigAdultIEExam'"; thedt = (DataTable)iQCareUtils.CreateTableFromDataView(theDV); Authentication.TabUserRights(btnExaminationSave, btnExaminationPrint, 260, Convert.ToInt32(thedt.Rows[0]["TabId"])); //Management thedt = new DataTable(); theDV = new DataView(thePEPDS); theDV.RowFilter = "TabName='NigAdultIEMgt'"; thedt = (DataTable)iQCareUtils.CreateTableFromDataView(theDV); Authentication.TabUserRights(btnSaveMgt, btnPrintMgt, 260, Convert.ToInt32(thedt.Rows[0]["TabId"])); } private DataTable GetCheckBoxListValues(CheckBoxList chklist, DataTable dt, string name) { DataRow dr; for (int i = 0; i < chklist.Items.Count; i++) { if (chklist.Items[i].Selected) { dr = dt.NewRow(); dr["ID"] = Convert.ToInt32(chklist.Items[i].Value); dr["FieldName"] = name; dt.Rows.Add(dr); } } return dt; } private DataTable CreateTempTable() { DataTable dtprescompl = new DataTable(); DataColumn theID = new DataColumn("ID"); theID.DataType = System.Type.GetType("System.Int32"); dtprescompl.Columns.Add(theID); DataColumn theFieldName = new DataColumn("FieldName"); theFieldName.DataType = System.Type.GetType("System.String"); dtprescompl.Columns.Add(theFieldName); DataColumn theDateValue1 = new DataColumn("DateField1"); theDateValue1.DataType = System.Type.GetType("System.String"); dtprescompl.Columns.Add(theDateValue1); DataColumn theDateValue2 = new DataColumn("DateField2"); theDateValue2.DataType = System.Type.GetType("System.String"); dtprescompl.Columns.Add(theDateValue2); DataColumn theValue1 = new DataColumn("NumericField"); theValue1.DataType = System.Type.GetType("System.String"); dtprescompl.Columns.Add(theValue1); DataColumn theOther = new DataColumn("Other_Notes"); theOther.DataType = System.Type.GetType("System.String"); dtprescompl.Columns.Add(theOther); return dtprescompl; } private void validate() { txtVisitDate.Attributes.Add("onblur", "DateFormat(this,this.value,event,true,'3');"); txtVisitDate.Attributes.Add("OnKeyup", "DateFormat(this,this.value,event,false,'3')"); txtlatestViralLoadDate.Attributes.Add("onblur", "DateFormat(this,this.value,event,true,'3');"); txtlatestViralLoadDate.Attributes.Add("OnKeyup", "DateFormat(this,this.value,event,false,'3')"); txtlbllowestCD4Date.Attributes.Add("onblur", "DateFormat(this,this.value,event,true,'3');"); txtlbllowestCD4Date.Attributes.Add("OnKeyup", "DateFormat(this,this.value,event,false,'3')"); txtLMPdate.Attributes.Add("onblur", "DateFormat(this,this.value,event,true,'3');"); txtLMPdate.Attributes.Add("OnKeyup", "DateFormat(this,this.value,event,false,'3')"); txtEDDDate.Attributes.Add("onblur", "DateFormat(this,this.value,event,true,'3');"); txtEDDDate.Attributes.Add("OnKeyup", "DateFormat(this,this.value,event,false,'3')"); txtlatestcd4number.Attributes.Add("onkeyup", "chkDecimal('" + txtlatestcd4number.ClientID + "')"); txtlatestViralLoadCount.Attributes.Add("onkeyup", "chkDecimal('" + txtlatestViralLoadCount.ClientID + "')"); txtlowestCD4Count.Attributes.Add("onkeyup", "chkDecimal('" + txtlowestCD4Count.ClientID + "')"); txtgestage.Attributes.Add("onkeyup", "chkDecimal('" + txtgestage.ClientID + "')"); this.idVitalSign.txtHeight.Attributes.Add("onkeyup", "chkDecimal('" + this.idVitalSign.txtHeight.ClientID + "')"); this.idVitalSign.txtWeight.Attributes.Add("onkeyup", "chkDecimal('" + this.idVitalSign.txtWeight.ClientID + "')"); this.idVitalSign.txtBPSystolic.Attributes.Add("onkeyup", "chkDecimal('" + this.idVitalSign.txtBPSystolic.ClientID + "')"); this.idVitalSign.txtBPDiastolic.Attributes.Add("onkeyup", "chkDecimal('" + this.idVitalSign.txtBPDiastolic.ClientID + "')"); this.idVitalSign.txtRR.Attributes.Add("onkeyup", "chkDecimal('" + this.idVitalSign.txtRR.ClientID + "')"); if (Session["PatientSex"] != DBNull.Value) { if (Session["PatientSex"].ToString().ToUpper() == "MALE") { visibleDiv(pnlpregnantDetail.ClientID, "hide"); } } } //Checking all the required values private Boolean fieldValidation(string TabName) { IQCareUtils theUtil = new IQCareUtils(); MsgBuilder totalMsgBuilder = new MsgBuilder(); if (txtVisitDate.Value.Trim() == "") { totalMsgBuilder.DataElements["MessageText"] = "Enter Visit Date"; IQCareMsgBox.Show("#C1", totalMsgBuilder, this); return false; } if (TabName == "Examination" || TabName == "TabPanelExamination") { if (this.idVitalSign.txtHeight.Text == "") { totalMsgBuilder.DataElements["MessageText"] = "Enter Height"; IQCareMsgBox.Show("#C1", totalMsgBuilder, this); idVitalSign.lblHeight.ForeColor = Color.Red; lblVitalSigns.ForeColor = Color.Red; return false; } else { idVitalSign.lblHeight.ForeColor = Color.FromArgb(0, 0, 142); lblVitalSigns.ForeColor = Color.FromArgb(0, 0, 142); } if (this.idVitalSign.txtWeight.Text == "") { totalMsgBuilder.DataElements["MessageText"] = "Enter Weight"; IQCareMsgBox.Show("#C1", totalMsgBuilder, this); idVitalSign.lblWeight.ForeColor = Color.Red; lblVitalSigns.ForeColor = Color.Red; return false; } else { idVitalSign.lblWeight.ForeColor = Color.FromArgb(0, 0, 142); lblVitalSigns.ForeColor = Color.FromArgb(0, 0, 142); } if (this.idVitalSign.txtBPSystolic.Text == "") { totalMsgBuilder.DataElements["MessageText"] = "Enter BP Systolic"; IQCareMsgBox.Show("#C1", totalMsgBuilder, this); idVitalSign.lblBP.ForeColor = Color.Red; lblVitalSigns.ForeColor = Color.Red; return false; } else { idVitalSign.lblBP.ForeColor = Color.FromArgb(0, 0, 142); lblVitalSigns.ForeColor = Color.FromArgb(0, 0, 142); } if (this.idVitalSign.txtBPDiastolic.Text == "") { totalMsgBuilder.DataElements["MessageText"] = "Enter BP Diastolic"; IQCareMsgBox.Show("#C1", totalMsgBuilder, this); idVitalSign.lblBP.ForeColor = Color.Red; lblVitalSigns.ForeColor = Color.Red; return false; } else { idVitalSign.lblBP.ForeColor = Color.FromArgb(0, 0, 142); lblVitalSigns.ForeColor = Color.FromArgb(0, 0, 142); } if (this.UcWhostaging.ddlwhostage1.SelectedIndex == 0) { totalMsgBuilder.DataElements["MessageText"] = "Select WHO Stage"; IQCareMsgBox.Show("#C1", totalMsgBuilder, this); UcWhostaging.lblWHOStage.ForeColor = Color.Red; lblheadWHOStage.ForeColor = Color.Red; return false; } else { UcWhostaging.lblWHOStage.ForeColor = Color.FromArgb(0, 0, 142); lblheadWHOStage.ForeColor = Color.FromArgb(0, 0, 142); } } else if (TabName == "Management" || TabName == "Tabmanagement") { if (this.UCTreatment.ddlTreatmentplan.SelectedIndex == 0) { totalMsgBuilder.DataElements["MessageText"] = "Select Treatment Plan"; IQCareMsgBox.Show("#C1", totalMsgBuilder, this); UCTreatment.lblTreatmentplan.ForeColor = Color.Red; lblheadregimenpresc.ForeColor = Color.Red; return false; } else { UCTreatment.lblTreatmentplan.ForeColor = Color.FromArgb(0, 0, 142); lblheadregimenpresc.ForeColor = Color.FromArgb(0, 0, 142); } } return true; } //private void SaveCancel() //{ // int PatientID = Convert.ToInt32(Session["PatientId"]); // IQCareMsgBox.NotifyAction("Adult Initial Evaluation Form saved successfully. Do you want to close?", "Adult Initial Evaluation Form", false, this, "window.location.href='frmPatient_History.aspx?sts=" + 0 + "';"); //} private void SaveCancel(string tabname) { int PatientID = Convert.ToInt32(Session["PatientId"]); IQCareMsgBox.NotifyAction(tabname + " Tab saved successfully.", "Adult Initial Evaluation", false, this, ""); } protected void btnSaveTriage_Click(object sender, EventArgs e) { Save(0); } private void visibleDiv(String divId, string showhide) { String script = ""; script = "<script language = 'javascript' defer ='defer' id = '" + divId + "'>\n"; script += "ShowHide('" + divId + "','" + showhide + "');\n"; script += "</script>\n"; RegisterStartupScript("'" + divId + "'", script); } public void BindExistingData() { string script = string.Empty; if (Convert.ToInt32(Session["PatientVisitId"].ToString()) > 0) { NigAdultIE = (INigeriaARTCard)ObjectFactory.CreateInstance("BusinessProcess.Clinical.BNigeriaARTCard, BusinessProcess.Clinical"); DataSet dsGet = NigAdultIE.GetNigeriaAdultIEDetails(Convert.ToInt32(Session["PatientId"].ToString()), Convert.ToInt32(Session["PatientVisitId"].ToString())); if (dsGet.Tables[0].Rows.Count > 0) { //------------------------------section client information if (dsGet.Tables[0].Rows[0]["VisitDate"] != DBNull.Value) { txtVisitDate.Value = String.Format("{0:dd-MMM-yyyy}", dsGet.Tables[0].Rows[0]["VisitDate"]); } bindPresentingComplaint(dsGet.Tables[1]); if (dsGet.Tables[0].Rows[0]["OtherPresentingComplaints"] != DBNull.Value) UcPc.txtOtherPresentingComplaints.Text = dsGet.Tables[0].Rows[0]["OtherPresentingComplaints"].ToString(); if (dsGet.Tables[0].Rows[0]["PresentingComplaintsAdditionalNotes"] != DBNull.Value) UcPc.txtAdditionalComplaints.Text = dsGet.Tables[0].Rows[0]["PresentingComplaintsAdditionalNotes"].ToString(); FillCheckboxlist(cblRiskFactors, dsGet.Tables[1], "RiskFactors"); bindMedicalHistory(dsGet.Tables[1]); if (dsGet.Tables[0].Rows[0]["PastMedicalConditionNotes"] != DBNull.Value) idNigeriaMedical.txtlastmedical.Text = dsGet.Tables[0].Rows[0]["PastMedicalConditionNotes"].ToString(); if (dsGet.Tables[0].Rows[0]["RelevantFamilyHistoryNotes"] != DBNull.Value) idNigeriaMedical.txtfamhistory.Text = dsGet.Tables[0].Rows[0]["RelevantFamilyHistoryNotes"].ToString(); if (dsGet.Tables[0].Rows[0]["HospitalisationNotes"] != DBNull.Value) idNigeriaMedical.txthospitalization.Text = dsGet.Tables[0].Rows[0]["HospitalisationNotes"].ToString(); FillCheckboxlist(cblRiskFactors, dsGet.Tables[1], "RiskFactors"); if (dsGet.Tables[4].Rows.Count > 0) { if (Convert.ToDateTime(dsGet.Tables[4].Rows[0]["LMP"]).ToString("dd-MMM-yyyy") != "01-Jan-1900") txtLMPdate.Value = String.Format("{0:dd-MMM-yyyy}", dsGet.Tables[4].Rows[0]["LMP"]); if (dsGet.Tables[4].Rows[0]["Pregnant"] != System.DBNull.Value) { if (dsGet.Tables[4].Rows[0]["Pregnant"].ToString() == "1") { this.rdopregnantyesno.SelectedValue = "1"; script = ""; script = "<script language = 'javascript' defer ='defer' id = 'divhideFPyes'>\n"; script += "ShowHide('hideFP','show');\n"; script += "</script>\n"; RegisterStartupScript("divhideFPyes", script); } else if (dsGet.Tables[4].Rows[0]["Pregnant"].ToString() == "0") { this.rdopregnantyesno.SelectedValue = "0"; } } if (dsGet.Tables[4].Rows[0]["EDD"] != System.DBNull.Value) { if (Convert.ToDateTime(dsGet.Tables[4].Rows[0]["EDD"]).ToString("dd-MMM-yyyy") != "01-Jan-1900") txtLMPdate.Value = String.Format("{0:dd-MMM-yyyy}", dsGet.Tables[4].Rows[0]["EDD"]); } txtgestage.Text = dsGet.Tables[4].Rows[0]["Gestationalage"].ToString(); } txtlatestcd4number.Text = dsGet.Tables[0].Rows[0]["LatestCD4"].ToString(); txtlowestCD4Count.Text = dsGet.Tables[0].Rows[0]["LowestCD4"].ToString(); if (dsGet.Tables[0].Rows[0]["LowestCD4Date"] != System.DBNull.Value) { if (Convert.ToDateTime(dsGet.Tables[0].Rows[0]["LowestCD4Date"]).ToString("dd-MMM-yyyy") != "01-Jan-1900") txtlbllowestCD4Date.Value = String.Format("{0:dd-MMM-yyyy}", dsGet.Tables[0].Rows[0]["LowestCD4Date"]); } if (dsGet.Tables[0].Rows[0]["LatestCD4Date"] != System.DBNull.Value) { if (Convert.ToDateTime(dsGet.Tables[0].Rows[0]["LatestCD4Date"]).ToString("dd-MMM-yyyy") != "01-Jan-1900") dtlatestcd4date.Value = String.Format("{0:dd-MMM-yyyy}", dsGet.Tables[0].Rows[0]["LatestCD4Date"]); } txtlatestViralLoadCount.Text = dsGet.Tables[0].Rows[0]["LowestViralLoad"].ToString(); if (dsGet.Tables[0].Rows[0]["LowestViralLoadDate"] != System.DBNull.Value) { if (Convert.ToDateTime(dsGet.Tables[0].Rows[0]["LowestViralLoadDate"]).ToString("dd-MMM-yyyy") != "01-Jan-1900") txtlatestViralLoadDate.Value = String.Format("{0:dd-MMM-yyyy}", dsGet.Tables[0].Rows[0]["LowestViralLoadDate"]); } if (dsGet.Tables[0].Rows[0]["LowestCD4LastSeen"] != DBNull.Value) { if (dsGet.Tables[0].Rows[0]["LowestCD4LastSeen"].ToString() == "1") chklowestcd4labrecord.Checked = true; } if (dsGet.Tables[0].Rows[0]["LowestViralLoadLastseen"] != DBNull.Value) { if (dsGet.Tables[0].Rows[0]["LowestViralLoadLastseen"].ToString() == "1") chkviralloadlabrecord.Checked = true; } bindCurrentMedication(dsGet.Tables[1]); UcCurrentMed.txtOtherComplaints.Text = dsGet.Tables[0].Rows[0]["currentmedicationother"].ToString(); bindDisclosure(dsGet.Tables[1]); if (dsGet.Tables[0].Rows[0]["serviceentry"] != DBNull.Value) ddlreferredfrom.SelectedValue = dsGet.Tables[0].Rows[0]["serviceentry"].ToString(); if (dsGet.Tables[7].Rows.Count > 0) { if (dsGet.Tables[7].Rows[0]["ARVAdhere"] != System.DBNull.Value) { if (dsGet.Tables[7].Rows[0]["ARVAdhere"].ToString() == "1") { UcAdherence.rbladherenceYesNo.SelectedValue = "1"; } else if (dsGet.Tables[7].Rows[0]["ARVAdhere"].ToString() == "0") { UcAdherence.rbladherenceYesNo.SelectedValue = "0"; } } if (dsGet.Tables[7].Rows[0]["MissedARV3days"] != System.DBNull.Value) { if (dsGet.Tables[7].Rows[0]["MissedARV3days"].ToString() == "1") { UcAdherence.rblmissedarvYesNo.SelectedValue = "1"; script = ""; script = "<script language = 'javascript' defer ='defer' id = 'DIVmissedarvPyes'>\n"; script += "ShowHide('DIVmissedarv','show');\n"; script += "</script>\n"; RegisterStartupScript("DIVmissedarvyes", script); } else if (dsGet.Tables[7].Rows[0]["MissedARV3days"].ToString() == "0") { UcAdherence.rblmissedarvYesNo.SelectedValue = "0"; } } UcAdherence.ddlReasomMissed.SelectedValue = dsGet.Tables[7].Rows[0]["MissedReason"].ToString(); if (dsGet.Tables[7].Rows[0]["TreatmentInterrupted"] != System.DBNull.Value) { if (dsGet.Tables[7].Rows[0]["TreatmentInterrupted"].ToString() == "1") { UcAdherence.rdoTreatmentIntrupted.SelectedValue = "1"; script = ""; script = "<script language = 'javascript' defer ='defer' id = 'DIVInturptedReasonyes'>\n"; script += "ShowHide('DIVInturptedReason','show');\n"; script += "</script>\n"; RegisterStartupScript("DIVInturptedReasonyes", script); } else if (dsGet.Tables[7].Rows[0]["TreatmentInterrupted"].ToString() == "0") { UcAdherence.rdoTreatmentIntrupted.SelectedValue = "0"; } } if (Convert.ToDateTime(dsGet.Tables[7].Rows[0]["InterruptedDate"]).ToString("dd-MMM-yyyy") != "01-Jan-1900") UcAdherence.txtdtIntrupptedDate.Value = String.Format("{0:dd-MMM-yyyy}", dsGet.Tables[7].Rows[0]["InterruptedDate"]); UcAdherence.txtintrpdays.Text = dsGet.Tables[7].Rows[0]["InterruptedNumDays"].ToString(); //UcAdherence.ddlreasonInterrupted.SelectedValue = dsGet.Tables[7].Rows[0]["InterruptedNumDays"].ToString(); if (dsGet.Tables[7].Rows[0]["TreatmentStopped"] != System.DBNull.Value) { if (dsGet.Tables[7].Rows[0]["TreatmentStopped"].ToString() == "1") { UcAdherence.rblstopped.SelectedValue = "1"; script = ""; script = "<script language = 'javascript' defer ='defer' id = 'DIVStopedReasonyes'>\n"; script += "ShowHide('DIVStopedReason','show');\n"; script += "</script>\n"; RegisterStartupScript("DIVStopedReasonyes", script); } else if (dsGet.Tables[7].Rows[0]["TreatmentStopped"].ToString() == "0") { UcAdherence.rblstopped.SelectedValue = "0"; } } if (Convert.ToDateTime(dsGet.Tables[7].Rows[0]["StoppedDate"]).ToString("dd-MMM-yyyy") != "01-Jan-1900") UcAdherence.txtStopedReasonDate.Value = String.Format("{0:dd-MMM-yyyy}", dsGet.Tables[7].Rows[0]["StoppedDate"]); UcAdherence.txtstoppeddays.Text = dsGet.Tables[7].Rows[0]["StoppedNumDays"].ToString(); UcAdherence.ddlStopedReason.SelectedValue = dsGet.Tables[7].Rows[0]["StoppedReason"].ToString(); UcAdherence.txtOtherdisclosed.Text = dsGet.Tables[0].Rows[0]["Otherdisclosed"].ToString(); UcAdherence.txthivdiscussed.Text = dsGet.Tables[0].Rows[0]["HIVStatusDiscussedwith"].ToString(); if (dsGet.Tables[7].Rows[0]["supportgroup"] != System.DBNull.Value) { if (dsGet.Tables[7].Rows[0]["supportgroup"].ToString() == "1") { UcAdherence.rblsupportgroup.SelectedValue = "1"; } else if (dsGet.Tables[7].Rows[0]["supportgroup"].ToString() == "0") { UcAdherence.rblsupportgroup.SelectedValue = "0"; } } } FillCheckboxlist(cblShortTermEffects, dsGet.Tables[1], "ShortTermEffects"); FillCheckboxlist(cblLongTermEffects, dsGet.Tables[1], "LongTermEffects"); txtOtherShortTermEffects.Text = dsGet.Tables[0].Rows[0]["OtherShortARVSideEffects"].ToString(); txtOtherLongtermEffects.Text = dsGet.Tables[0].Rows[0]["OtherLongARVSideEffects"].ToString(); if (dsGet.Tables[3].Rows.Count > 0) { if (dsGet.Tables[3].Rows[0]["Temp"] != DBNull.Value) this.idVitalSign.txtTemp.Text = dsGet.Tables[3].Rows[0]["Temp"].ToString(); if (dsGet.Tables[3].Rows[0]["RR"] != DBNull.Value) this.idVitalSign.txtRR.Text = dsGet.Tables[3].Rows[0]["RR"].ToString(); if (dsGet.Tables[3].Rows[0]["BPDiastolic"] != DBNull.Value) this.idVitalSign.txtBPDiastolic.Text = dsGet.Tables[3].Rows[0]["BPDiastolic"].ToString(); if (dsGet.Tables[3].Rows[0]["BPSystolic"] != DBNull.Value) this.idVitalSign.txtBPSystolic.Text = dsGet.Tables[3].Rows[0]["BPSystolic"].ToString(); if (dsGet.Tables[3].Rows[0]["Height"] != DBNull.Value) this.idVitalSign.txtHeight.Text = dsGet.Tables[3].Rows[0]["Height"].ToString(); if (dsGet.Tables[3].Rows[0]["Weight"] != DBNull.Value) this.idVitalSign.txtWeight.Text = dsGet.Tables[3].Rows[0]["Weight"].ToString(); if (dsGet.Tables[3].Rows[0]["BMIz"] != DBNull.Value) this.idVitalSign.txtBMI.Text = dsGet.Tables[3].Rows[0]["BMIz"].ToString(); } FillCheckboxlist(UcPE.cblNigeriaPEGeneral, dsGet.Tables[1], "NigeriaPEGeneral"); FillCheckboxlist(UcPE.cblNigeriaPESkin, dsGet.Tables[1], "NigeriaPESkin"); FillCheckboxlist(UcPE.cblNigeriaPEHeadEyeEnt, dsGet.Tables[1], "NigeriaPEHeadEyeEnt"); FillCheckboxlist(UcPE.cblNigeriaPECardiovascular, dsGet.Tables[1], "NigeriaPECardiovascular"); FillCheckboxlist(UcPE.cblNigeriaPEBreast, dsGet.Tables[1], "NigeriaPEBreast"); FillCheckboxlist(UcPE.cblNigeriaPEGenitalia, dsGet.Tables[1], "NigeriaPEGenitalia"); FillCheckboxlist(UcPE.cblNigeriaPERespiratory, dsGet.Tables[1], "NigeriaPERespiratory"); FillCheckboxlist(UcPE.cblNigeriaPEGastrointestinal, dsGet.Tables[1], "NigeriaPEGastrointestinal"); FillCheckboxlist(UcPE.cblNigeriaPENeurological, dsGet.Tables[1], "NigeriaPENeurological"); FillCheckboxlist(UcPE.cblNigeriaPEMentalstatus, dsGet.Tables[1], "NigeriaPEMentalstatus"); UcPE.txtOtherNigeriaPEGeneral.Text = dsGet.Tables[0].Rows[0]["OtherGeneralConditions"].ToString(); UcPE.txtOtherNigeriaPESkin.Text = dsGet.Tables[0].Rows[0]["OtherSkinConditions"].ToString(); UcPE.txtOtherNigeriaPEHeadEyeEnt.Text = dsGet.Tables[0].Rows[0]["HeadEyeENTOther"].ToString(); UcPE.txtOtherNigeriaPECardiovascular.Text = dsGet.Tables[0].Rows[0]["OtherCardiovascularConditions"].ToString(); UcPE.txtOtherNigeriaPEBreast.Text = dsGet.Tables[0].Rows[0]["BreastsOther"].ToString(); UcPE.txtOtherNigeriaPEGenitalia.Text = dsGet.Tables[0].Rows[0]["Genitaliaother"].ToString(); UcPE.txtOtherNigeriaPERespiratory.Text = dsGet.Tables[0].Rows[0]["Respiratoryother"].ToString(); UcPE.txtOtherNigeriaPEGastrointestinal.Text = dsGet.Tables[0].Rows[0]["Gastrointestinalother"].ToString(); UcPE.txtOtherNigeriaPENeurological.Text = dsGet.Tables[0].Rows[0]["Neurologicalother"].ToString(); UcPE.txtOtherNigeriaPEMentalstatus.Text = dsGet.Tables[0].Rows[0]["Mentalstatusother"].ToString(); UcPE.txtOtherAdditionaldetailedfindings.Text = dsGet.Tables[0].Rows[0]["PEAdditionaldetails"].ToString(); if (dsGet.Tables[10].Rows.Count > 0) { if (dsGet.Tables[10].Rows[0]["AssessmentID"] != System.DBNull.Value) { rblassessment.SelectedValue = dsGet.Tables[10].Rows[0]["AssessmentID"].ToString(); } txtAssessmentNotes.Text = dsGet.Tables[10].Rows[0]["Description1"].ToString(); } BindWHOListData(dsGet.Tables[1]); if (dsGet.Tables[2].Rows.Count > 0) { if (dsGet.Tables[2].Rows[0]["WHOStage"] != DBNull.Value) UcWhostaging.ddlwhostage1.SelectedValue = dsGet.Tables[2].Rows[0]["WHOStage"].ToString(); } if (dsGet.Tables[0].Rows[0]["LabEvaluation"] != System.DBNull.Value) { if (dsGet.Tables[0].Rows[0]["LabEvaluation"].ToString() == "1") { UCTreatment.ChkLabEvaluation.Checked = true; script = ""; script = "<script language = 'javascript' defer ='defer' id = 'DivLabEvalyes'>\n"; script += "ShowHide('DivLabEval','show');\n"; script += "</script>\n"; RegisterStartupScript("DivLabEvalyes", script); } else if (dsGet.Tables[0].Rows[0]["LabEvaluation"].ToString() == "0") { UCTreatment.ChkLabEvaluation.Checked = false; } } UCTreatment.UcLabEval.txtlabdiagnosticinput.Text = dsGet.Tables[0].Rows[0]["LabReview"].ToString(); if (dsGet.Tables[0].Rows[0]["Regimen"] != System.DBNull.Value) { if (dsGet.Tables[0].Rows[0]["Regimen"].ToString() == "1") { UCTreatment.chkregimen.Checked = true; script = ""; script = "<script language = 'javascript' defer ='defer' id = 'DivPrescDrugyes'>\n"; script += "ShowHide('DivPrescDrug','show');\n"; script += "</script>\n"; RegisterStartupScript("DivPrescDrugyes", script); } else if (dsGet.Tables[0].Rows[0]["Regimen"].ToString() == "0") { UCTreatment.ChkLabEvaluation.Checked = false; } } bindTreatment(dsGet.Tables[1]); bindEnrollIn(dsGet.Tables[1]); FillCheckboxlist(UCTreatment.chklistARTchangecode, dsGet.Tables[1], "NigeriaARVTreamentChangeReason"); if (dsGet.Tables[8].Rows.Count > 0) { if (dsGet.Tables[8].Rows[0]["TherapyReasonCode"] != DBNull.Value) UCTreatment.ddlTreatmentplan.SelectedValue = dsGet.Tables[8].Rows[0]["TherapyReasonCode"].ToString(); UCTreatment.txtSpecifyotherARTchangereason.Text = dsGet.Tables[8].Rows[0]["specifyOtherARTChangeReason"].ToString(); if (UCTreatment.ddlTreatmentplan.SelectedItem.Text == "Change Treatment") { visibleDiv("divARTchangecode","show"); } } } } } private void BindWHOListData(DataTable theDT) { foreach (DataRow theDR in theDT.Rows) { if (Convert.ToString(theDR["FieldName"]) == "NigeriaWHOStageIConditions") { for (int i = 0; i < this.UcWhostaging.gvWHO1.Rows.Count; i++) { Label lblWHOId = (Label)UcWhostaging.gvWHO1.Rows[i].FindControl("lblwho1"); CheckBox chkWHOId = (CheckBox)UcWhostaging.gvWHO1.Rows[i].FindControl("Chkwho1"); if (Convert.ToInt32(theDR["ValueId"]) == Convert.ToInt32(lblWHOId.Text)) { chkWHOId.Checked = true; } } } else if (Convert.ToString(theDR["FieldName"]) == "NigeriaWHOStageIIConditions") { for (int i = 0; i < this.UcWhostaging.gvWHO2.Rows.Count; i++) { Label lblWHOId = (Label)UcWhostaging.gvWHO2.Rows[i].FindControl("lblwho2"); CheckBox chkWHOId = (CheckBox)UcWhostaging.gvWHO2.Rows[i].FindControl("Chkwho2"); if (Convert.ToInt32(theDR["ValueId"]) == Convert.ToInt32(lblWHOId.Text)) { chkWHOId.Checked = true; } } } else if (Convert.ToString(theDR["FieldName"]) == "NigeriaWHOStageIIIConditions") { for (int i = 0; i < this.UcWhostaging.gvWHO3.Rows.Count; i++) { Label lblWHOId = (Label)UcWhostaging.gvWHO3.Rows[i].FindControl("lblwho3"); CheckBox chkWHOId = (CheckBox)UcWhostaging.gvWHO3.Rows[i].FindControl("Chkwho3"); if (Convert.ToInt32(theDR["ValueId"]) == Convert.ToInt32(lblWHOId.Text)) { chkWHOId.Checked = true; } } } else if (Convert.ToString(theDR["FieldName"]) == "NigeriaWHOStageIVConditions") { for (int i = 0; i < this.UcWhostaging.gvWHO4.Rows.Count; i++) { Label lblWHOId = (Label)UcWhostaging.gvWHO4.Rows[i].FindControl("lblwho4"); CheckBox chkWHOId = (CheckBox)UcWhostaging.gvWHO4.Rows[i].FindControl("Chkwho4"); if (Convert.ToInt32(theDR["ValueId"]) == Convert.ToInt32(lblWHOId.Text)) { chkWHOId.Checked = true; } } } } } public void FillCheckboxlist(CheckBoxList chk, DataTable thedt, string name) { IQCareUtils iQCareUtils = new IQCareUtils(); DataTable dt = new DataTable(); string script = string.Empty; if (thedt.Rows.Count > 0) { DataView theDV = new DataView(thedt); theDV.RowFilter = "FieldName='" + name + "'"; dt = (DataTable)iQCareUtils.CreateTableFromDataView(theDV); for (int i = 0; i < dt.Rows.Count; i++) { for (int j = 0; j < chk.Items.Count; j++) { if (chk.Items[j].Value == dt.Rows[i]["ValueID"].ToString()) { chk.Items[j].Selected = true; if (name == "ShortTermEffects") { if (chk.Items[j].Text.ToLower() == "other specify") { script = ""; script = "<script language = 'javascript' defer ='defer' id = 'divotherShortTermEffects'>\n"; script += "ShowHide('divshorttermeffecttxt','show');\n"; script += "</script>\n"; RegisterStartupScript("divotherShortTermEffects", script); } } if (name == "LongTermEffects") { if (chk.Items[j].Text.ToLower() == "other specify") { script = ""; script = "<script language = 'javascript' defer ='defer' id = 'divotherLongTermEffects'>\n"; script += "ShowHide('divlongtermeffecttxt','show');\n"; script += "</script>\n"; RegisterStartupScript("divotherLongTermEffects", script); } } if (name == "NigeriaPEGeneral") { if (chk.Items[j].Text.ToUpper() == "NSF") { ScriptManager.RegisterStartupScript(this, GetType(), "NigeriaPEGeneral", "$('#" + chk.ClientID + "').trigger('onchange');", true); } else if (chk.Items[j].Text == "Other (specify)") { script = ""; script = "<script language = 'javascript' defer ='defer' id = 'divNigeriaPEGeneralOther'>\n"; script += "ShowHide('divNigeriaPEGeneralOther','show');\n"; script += "</script>\n"; RegisterStartupScript("divNigeriaPEGeneralOther", script); } } if (name == "NigeriaPESkin") { if (chk.Items[j].Text.ToUpper() == "NSF") { ScriptManager.RegisterStartupScript(this, GetType(), "NigeriaPESkin", "$('#" + chk.ClientID + "').trigger('onchange');", true); } else if (chk.Items[j].Text == "Other (specify)") { script = ""; script = "<script language = 'javascript' defer ='defer' id = 'divOtherNigeriaPESkin'>\n"; script += "ShowHide('divOtherNigeriaPESkin','show');\n"; script += "</script>\n"; RegisterStartupScript("divOtherNigeriaPESkin", script); } } if (name == "NigeriaPEHeadEyeEnt") { if (chk.Items[j].Text.ToUpper() == "NSF") { ScriptManager.RegisterStartupScript(this, GetType(), "NigeriaPEHeadEyeEnt", "$('#" + chk.ClientID + "').trigger('onchange');", true); } else if (chk.Items[j].Text == "Other (specify)") { script = ""; script = "<script language = 'javascript' defer ='defer' id = 'divOtherNigeriaPEHeadEyeEnt'>\n"; script += "ShowHide('divOtherNigeriaPEHeadEyeEnt','show');\n"; script += "</script>\n"; RegisterStartupScript("divOtherNigeriaPEHeadEyeEnt", script); } } if (name == "NigeriaPECardiovascular") { if (chk.Items[j].Text.ToUpper() == "NSF") { ScriptManager.RegisterStartupScript(this, GetType(), "NigeriaPECardiovascular", "$('#" + chk.ClientID + "').trigger('onchange');", true); } else if (chk.Items[j].Text.ToLower() == "other (specify)") { script = ""; script = "<script language = 'javascript' defer ='defer' id = 'divOtherNigeriaPECardiovascular'>\n"; script += "ShowHide('divOtherNigeriaPECardiovascular','show');\n"; script += "</script>\n"; RegisterStartupScript("divOtherNigeriaPECardiovascular", script); } } if (name == "NigeriaPEBreast") { if (chk.Items[j].Text.ToUpper() == "NSF") { ScriptManager.RegisterStartupScript(this, GetType(), "NigeriaPEBreast", "$('#" + chk.ClientID + "').trigger('onchange');", true); } else if (chk.Items[j].Text == "Other (specify)") { script = ""; script = "<script language = 'javascript' defer ='defer' id = 'divOtherNigeriaPEBreast'>\n"; script += "ShowHide('divOtherNigeriaPEBreast','show');\n"; script += "</script>\n"; RegisterStartupScript("divOtherNigeriaPEBreast", script); } } if (name == "NigeriaPEGenitalia") { if (chk.Items[j].Text.ToUpper() == "NSF") { ScriptManager.RegisterStartupScript(this, GetType(), "NigeriaPEGenitalia", "$('#" + chk.ClientID + "').trigger('onchange');", true); } else if (chk.Items[j].Text == "Other (specify)") { script = ""; script = "<script language = 'javascript' defer ='defer' id = 'divOtherNigeriaPEGenitalia'>\n"; script += "ShowHide('divOtherNigeriaPEGenitalia','show');\n"; script += "</script>\n"; RegisterStartupScript("divOtherNigeriaPEGenitalia", script); } } if (name == "NigeriaPERespiratory") { if (chk.Items[j].Text.ToUpper() == "NSF") { ScriptManager.RegisterStartupScript(this, GetType(), "NigeriaPERespiratory", "$('#" + chk.ClientID + "').trigger('onchange');", true); } else if (chk.Items[j].Text == "Other (specify)") { script = ""; script = "<script language = 'javascript' defer ='defer' id = 'divOtherNigeriaPERespiratory'>\n"; script += "ShowHide('divOtherNigeriaPERespiratory','show');\n"; script += "</script>\n"; RegisterStartupScript("divOtherNigeriaPERespiratory", script); } } if (name == "NigeriaPEGastrointestinal") { if (chk.Items[j].Text.ToUpper() == "NSF") { ScriptManager.RegisterStartupScript(this, GetType(), "NigeriaPEGastrointestinal", "$('#" + chk.ClientID + "').trigger('onchange');", true); } else if (chk.Items[j].Text.ToLower() == "other (specify)") { script = ""; script = "<script language = 'javascript' defer ='defer' id = 'divOtherNigeriaPEGastrointestinal'>\n"; script += "ShowHide('divOtherNigeriaPEGastrointestinal','show');\n"; script += "</script>\n"; RegisterStartupScript("divOtherNigeriaPEGastrointestinal", script); } } if (name == "NigeriaPENeurological") { if (chk.Items[j].Text.ToUpper() == "NSF") { ScriptManager.RegisterStartupScript(this, GetType(), "NigeriaPENeurological", "$('#" + chk.ClientID + "').trigger('onchange');", true); } else if (chk.Items[j].Text == "Other (specify)") { script = ""; script = "<script language = 'javascript' defer ='defer' id = 'divOtherNigeriaPENeurological'>\n"; script += "ShowHide('divOtherNigeriaPENeurological','show');\n"; script += "</script>\n"; RegisterStartupScript("divOtherNigeriaPENeurological", script); } } if (name == "NigeriaPEMentalstatus") { if (chk.Items[j].Text.ToUpper() == "NSF") { ScriptManager.RegisterStartupScript(this, GetType(), "NigeriaPEMentalstatus", "$('#" + chk.ClientID + "').trigger('onchange');", true); } else if (chk.Items[j].Text.ToLower() == "other (specify)") { script = ""; script = "<script language = 'javascript' defer ='defer' id = 'divOtherNigeriaPEMentalstatus'>\n"; script += "ShowHide('divOtherNigeriaPEMentalstatus','show');\n"; script += "</script>\n"; RegisterStartupScript("divOtherNigeriaPEMentalstatus", script); } } if (name == "NigeriaARVTreamentChangeReason") { if (chk.Items[j].Text.ToLower() == "other(specify)") { script = ""; script = "<script language = 'javascript' defer ='defer' id = 'divSpecifyotherARTchangereason'>\n"; script += "ShowHide('divSpecifyotherARTchangereason','show');\n"; script += "</script>\n"; RegisterStartupScript("divSpecifyotherARTchangereason", script); } } } } } } } private void bindPresentingComplaint(DataTable thedt) { IQCareUtils iQCareUtils = new IQCareUtils(); DataTable dt = new DataTable(); string script = string.Empty; if (thedt.Rows.Count > 0) { DataView theDV = new DataView(thedt); theDV.RowFilter = "FieldName='PresentingComplaints'"; dt = (DataTable)iQCareUtils.CreateTableFromDataView(theDV); for (int j = 0; j <= dt.Rows.Count - 1; j++) { for (int i = 0; i < this.UcPc.gvPresentingComplaints.Rows.Count; i++) { Label lblPComplaintsId = (Label)UcPc.gvPresentingComplaints.Rows[i].FindControl("lblPresenting"); CheckBox chkPComplaints = (CheckBox)UcPc.gvPresentingComplaints.Rows[i].FindControl("ChkPresenting"); TextBox txtPComplaints = (TextBox)UcPc.gvPresentingComplaints.Rows[i].FindControl("txtPresenting"); if (Convert.ToInt32(dt.Rows[j]["ValueId"]) == Convert.ToInt32(lblPComplaintsId.Text)) { if (dt.Rows[j]["Name"].ToString().ToLower() == "other") { visibleDiv("DivOther","show"); } chkPComplaints.Checked = true; txtPComplaints.Text = dt.Rows[j]["Other_notes"].ToString(); if (dt.Rows[j]["Name"].ToString().ToLower() == "none") { String pcscript = ""; pcscript = "<script language = 'javascript' defer ='defer' id = 'togglePresComp'>\n"; pcscript += "togglePC('" + chkPComplaints.ClientID + "')\n"; pcscript += "</script>\n"; RegisterStartupScript("'togglePresComp'", pcscript); } } } } } } private void bindMedicalHistory(DataTable thedt) { IQCareUtils iQCareUtils = new IQCareUtils(); DataTable dt = new DataTable(); string script = string.Empty; if (thedt.Rows.Count > 0) { DataView theDV = new DataView(thedt); theDV.RowFilter = "FieldName='NigeriaSymptoms'"; dt = (DataTable)iQCareUtils.CreateTableFromDataView(theDV); for (int j = 0; j <= dt.Rows.Count - 1; j++) { for (int i = 0; i < this.idNigeriaMedical.gvMedicalHistory.Rows.Count; i++) { Label lblMedical = (Label)idNigeriaMedical.gvMedicalHistory.Rows[i].FindControl("lblMedical"); CheckBox ChkMedical = (CheckBox)idNigeriaMedical.gvMedicalHistory.Rows[i].FindControl("ChkMedical"); TextBox txtMedical = (TextBox)idNigeriaMedical.gvMedicalHistory.Rows[i].FindControl("txtMedical"); if (Convert.ToInt32(dt.Rows[j]["ValueId"]) == Convert.ToInt32(lblMedical.Text)) { if (dt.Rows[j]["Name"].ToString().ToLower() == "other") { visibleDiv("DivtoggleMedicalPC", "show"); } ChkMedical.Checked = true; txtMedical.Text = dt.Rows[j]["Other_notes"].ToString(); if (dt.Rows[j]["Name"].ToString().ToLower() == "none") { String pcscript = ""; pcscript = "<script language = 'javascript' defer ='defer' id = 'toggleMedicalPC'>\n"; pcscript += "toggleMedicalPC('" + ChkMedical.ClientID + "')\n"; pcscript += "</script>\n"; RegisterStartupScript("'toggleMedicalPC'", pcscript); } } } } } } private void bindCurrentMedication(DataTable thedt) { IQCareUtils iQCareUtils = new IQCareUtils(); DataTable dt = new DataTable(); string script = string.Empty; if (thedt.Rows.Count > 0) { DataView theDV = new DataView(thedt); theDV.RowFilter = "FieldName='NigeriaCurrentMedication'"; dt = (DataTable)iQCareUtils.CreateTableFromDataView(theDV); for (int j = 0; j <= dt.Rows.Count - 1; j++) { for (int i = 0; i < this.UcCurrentMed.gvcurrentmedication.Rows.Count; i++) { Label lblmedication = (Label)UcCurrentMed.gvcurrentmedication.Rows[i].FindControl("lblmedication"); CheckBox Chkmedication = (CheckBox)UcCurrentMed.gvcurrentmedication.Rows[i].FindControl("Chkmedication"); if (Convert.ToInt32(dt.Rows[j]["ValueId"]) == Convert.ToInt32(lblmedication.Text)) { if (dt.Rows[j]["Name"].ToString().ToLower() == "other") { visibleDiv("DivOtherComplaint", "show"); } Chkmedication.Checked = true; if (dt.Rows[j]["Name"].ToString().ToLower() == "none") { String pcscript = ""; pcscript = "<script language = 'javascript' defer ='defer' id = 'toggleCurrentPC'>\n"; pcscript += "toggleCurrentPC('" + Chkmedication.ClientID + "')\n"; pcscript += "</script>\n"; RegisterStartupScript("'toggleCurrentPC'", pcscript); } } } } } } private void bindTreatment(DataTable thedt) { IQCareUtils iQCareUtils = new IQCareUtils(); DataTable dt = new DataTable(); string script = string.Empty; if (thedt.Rows.Count > 0) { DataView theDV = new DataView(thedt); theDV.RowFilter = "FieldName='NigeriaListLabEvaluation'"; dt = (DataTable)iQCareUtils.CreateTableFromDataView(theDV); for (int j = 0; j <= dt.Rows.Count - 1; j++) { for (int i = 0; i < this.UCTreatment.gvtreatment.Rows.Count; i++) { Label lbltreatment = (Label)UCTreatment.gvtreatment.Rows[i].FindControl("lbltreatment"); CheckBox Chktreatment = (CheckBox)UCTreatment.gvtreatment.Rows[i].FindControl("Chktreatment"); if (Convert.ToInt32(dt.Rows[j]["ValueId"]) == Convert.ToInt32(lbltreatment.Text)) { Chktreatment.Checked = true; if (dt.Rows[j]["Name"].ToString().ToUpper() == "OTHER REFERRALS") { visibleDiv("DivTreatmentOther", "show"); } } } } } } private void bindEnrollIn(DataTable thedt) { IQCareUtils iQCareUtils = new IQCareUtils(); DataTable dt = new DataTable(); string script = string.Empty; if (thedt.Rows.Count > 0) { DataView theDV = new DataView(thedt); theDV.RowFilter = "FieldName='NigeriaListEnrollin'"; dt = (DataTable)iQCareUtils.CreateTableFromDataView(theDV); for (int j = 0; j <= dt.Rows.Count - 1; j++) { for (int i = 0; i < this.UCTreatment.gvenrollin.Rows.Count; i++) { Label lblenrollin = (Label)UCTreatment.gvenrollin.Rows[i].FindControl("lblenrollin"); CheckBox Chkenrollin = (CheckBox)UCTreatment.gvenrollin.Rows[i].FindControl("Chkenrollin"); if (Convert.ToInt32(dt.Rows[j]["ValueId"]) == Convert.ToInt32(lblenrollin.Text)) { Chkenrollin.Checked = true; } } } } } protected void btnClinicalHistorySave_Click(object sender, EventArgs e) { Save(0); } protected void btnHIVHistorySave_Click(object sender, EventArgs e) { Save(0); } protected void btnExaminationSave_Click(object sender, EventArgs e) { Save(0); } protected void btnClose_Click(object sender, EventArgs e) { if (Request.QueryString["name"] == "Add" && Convert.ToInt32(Session["PatientVisitId"]) > 0) { string theUrl; theUrl = string.Format("frmPatient_Home.aspx"); Response.Redirect(theUrl); } else { string theUrl; theUrl = string.Format("frmPatient_History.aspx"); Response.Redirect(theUrl); } } } }
52.167373
226
0.482181
[ "MIT" ]
uon-crissp/IQCare
SourceBase/Presentation/PresentationApp/ClinicalForms/frmClinical_Nigeria_AdultIE.aspx.cs
98,494
C#
namespace AspNetCoreSpa.Core { public enum Gender { Male, Female } public enum RoleEnum { Admin, Staff, User } public enum TouristTypeEnum { Adult, Children, Kid } }
13.25
31
0.471698
[ "MIT" ]
nvhoor/FlashTour
src/AspNetCoreSpa.Core/Enums/Enums.cs
265
C#
using System; using System.Runtime.InteropServices; namespace CredNet.Interop { [ComConversionLoss] [StructLayout(LayoutKind.Sequential, Pack = 4)] public struct _wireSAFEARR_HAVEIID { public uint Size; [ComConversionLoss] public IntPtr apUnknown; public Guid iid; } }
15.157895
48
0.756944
[ "MIT" ]
Sajidur78/CredNet
CredNet/Interop/_wireSAFEARR_HAVEIID.cs
290
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("DebugMe")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("DebugMe")] [assembly: AssemblyCopyright("Copyright © Microsoft 2010")] [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("6d044253-45a8-4f25-9706-51c0364a6b54")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.972973
84
0.746619
[ "MIT" ]
acken/ClrSequencer
src/DebugMe/Properties/AssemblyInfo.cs
1,408
C#
using System; using System.Collections.Generic; using System.Linq; using TechNoir.Data.Entity.Edmx.Serialization; namespace TechNoir.Data.Entity.Edmx.Model.Map { public class FunctionImportMappingResultMapping { public FunctionImportMapping FunctionImportMapping { get; } public IReadOnlyCollection<FunctionImportComplexTypeMapping> ComplexTypeMappings { get; } public IReadOnlyCollection<FunctionImportEntityTypeMapping> EntityTypeMappings { get; } internal FunctionImportMappingResultMapping(FunctionImportMapping function_import_mapping, TFunctionImportMappingResultMapping t) { if (t == null) throw new ArgumentNullException(nameof(t)); FunctionImportMapping = function_import_mapping ?? throw new ArgumentNullException(nameof(function_import_mapping)); ComplexTypeMappings = t.ComplexTypeMappings.Select(ctm => new FunctionImportComplexTypeMapping(this, ctm)).ToList(); EntityTypeMappings = t.EntityTypeMappings.Select(etm => new FunctionImportEntityTypeMapping(this, etm)).ToList(); } } }
47.916667
137
0.732174
[ "MIT" ]
boone34/Data.Entity.Edmx
Model/Map/FunctionImportMappingResultMapping.cs
1,152
C#
namespace HackTheClimate.Services.Similarity { public class AzureBlobEntitiesConfiguration { public string Endpoint { get; set; } public string BlobContainerName { get; set; } } }
23.222222
53
0.684211
[ "MIT" ]
Zuehlke/hack-the-climate
solution/HackTheClimate/Services/EntityRecognition/AzureBlobEntitiesConfiguration.cs
211
C#
using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Lob.Net { public class LobSerializerSettings : JsonSerializerSettings { public LobSerializerSettings() : base() { ContractResolver = new DefaultContractResolver { NamingStrategy = new SnakeCaseNamingStrategy() }; NullValueHandling = NullValueHandling.Ignore; } } }
23.631579
63
0.608018
[ "MIT" ]
adamreed90/lob.net
src/Lob.Net/Core/LobSerializerSettings.cs
451
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using TMPro; public class LevelTimer : MonoBehaviour { public float timeUntilFail = 100f; private float startTime = 0f; [SerializeField] private bool hasFinished = false; public BaseEvent failedLevelEvent; public Slider slider; public TextMeshProUGUI timerText; private void Start() { startTime = Time.time; } private void UpdateSlider() { if(!hasFinished) { slider.normalizedValue = (Time.time - startTime) / timeUntilFail; timerText.text = ((int)(timeUntilFail - (Time.time - startTime))).ToString(); } } private void Update() { UpdateSlider(); // Check if has failed if (!hasFinished && Time.time - startTime >= timeUntilFail) { failedLevelEvent.Raise(); hasFinished = true; slider.gameObject.SetActive(false); timerText.transform.parent.gameObject.SetActive(false); Debug.Log("Completed level with " + (Time.time - startTime) + " seconds"); } } public void CompletedLevel() { hasFinished = true; slider.gameObject.SetActive(false); timerText.transform.parent.gameObject.SetActive(false); Debug.Log("Completed level with " + (Time.time - startTime) + " seconds"); } }
27.153846
89
0.632436
[ "CC0-1.0" ]
caioguedesam/wildfire_rescue
Assets/Scripts/LevelTimer.cs
1,414
C#
/** * * Request Script of Unity Network Model * * @file Request.cs * @author Uwe Gruenefeld, Tobias Lunte * @version 2020-05-05 * **/ using System; using System.Collections.Generic; using UnityEngine; namespace UnityNetworkModel { /// <summary> /// Request for changes to Objects, Components and Resources to be sent between Client and Server /// </summary> [Serializable] internal class Request : ISerializationCallbackReceiver { private Injector injector; // Types of request public const string RESOURCE = "r"; public const string OBJECT = "o"; public const string COMPONENT = "c"; public const string UPDATE = "u"; public const string DELETE = "d"; // Parameters used by all requests [NonSerialized] public string messageType; [NonSerialized] public string updateType; public string type; public string name; public string channel; public long timestamp; [NonSerialized] public int iteration; // Human-readable parameters for specific types of request [NonSerialized] public string parent; [NonSerialized] public AbstractResource resource; [NonSerialized] public Type resourceType; [NonSerialized] public List<AbstractComponent> components; [NonSerialized] public List<Type> componentTypes; // Serialized parameters that human-readable parameters are mapped to while sending over the network public List<string> string1; public List<string> string2; /// <summary> /// Common constructor used by static Request-generating methdos /// </summary> /// <param name="injector"></param> /// <param name="messageType"></param> /// <param name="updateType"></param> /// <param name="name"></param> private Request(Injector injector, string messageType, string updateType, string name) { this.injector = injector; this.messageType = messageType; this.updateType = updateType; this.name = name; this.channel = ""; this.iteration = 0; this.RefreshTimestamp(); } /// <summary> /// Refreshes current timestamp /// </summary> internal void RefreshTimestamp() { if (injector.configuration.TIME) this.timestamp = DateTime.Now.ToUniversalTime().ToBinary(); else this.timestamp = 0; } /// <summary> /// Create Request to update specific GameObject /// </summary> /// <param name="injector"></param> /// <param name="gameObject"></param> /// <returns>Request</returns> internal static Request UpdateObject(Injector injector, GameObject gameObject) { Request request = new Request(injector, Request.OBJECT, Request.UPDATE, gameObject.name); request.parent = gameObject.transform.parent.name; // If the Parent GameObject is the GameObject with the NetworkModel Configuration attached, then assign the Alias Name of the root GameObject if (request.parent == injector.configuration.gameObject.name) request.parent = Model.ROOT_NAME; return request; } /// <summary> /// Create Request to delete specific GameObject /// </summary> /// <param name="injector"></param> /// <param name="name"></param> /// <returns>Request</returns> internal static Request DeleteObject(Injector injector, string name) { return new Request(injector, Request.OBJECT, Request.DELETE, name); } /// <summary> /// Create Request to update a specific Resource /// </summary> /// <param name="injector"></param> /// <param name="name"></param> /// <param name="resourceType"></param> /// <param name="resource"></param> /// <returns>Request</returns> internal static Request UpdateResource(Injector injector, string name, Type resourceType, AbstractResource resource) { Request request = new Request(injector, Request.RESOURCE, Request.UPDATE, name); request.resource = resource; request.resourceType = resourceType; return request; } /// <summary> /// Create Request to delete a specific Resource /// </summary> /// <param name="injector"></param> /// <param name="name"></param> /// <returns>Request</returns> internal static Request DeleteResource(Injector injector, string name) { return new Request(injector, Request.RESOURCE, Request.DELETE, name); } /// <summary> /// Create Request to update a List of Components belonging to a specific GameObject /// </summary> /// <param name="injector"></param> /// <param name="name"></param> /// <param name="components"></param> /// <returns>Request</returns> internal static Request UpdateComponents(Injector injector, string name, List<AbstractComponent> components) { Request request = new Request(injector, Request.COMPONENT, Request.UPDATE, name); request.components = components; return request; } /// <summary> /// Create Request to delete a List of Components belonging to a specific GameObject /// </summary> /// <param name="injector"></param> /// <param name="name"></param> /// <param name="types"></param> /// <returns>Request</returns> internal static Request DeleteComponents(Injector injector, string name, List<Type> types) { Request request = new Request(injector, Request.COMPONENT, Request.DELETE, name); request.componentTypes = types; return request; } /// <summary> /// Before the request is sent to the server, packs human-readable parameters into serializable parameters /// </summary> public void OnBeforeSerialize() { this.type = this.messageType + this.updateType; switch (type) { case Request.RESOURCE + Request.UPDATE: this.string1 = new List<string>() { this.EncodeClass(resourceType.ToString()) }; this.string2 = new List<string>() { JsonUtility.ToJson(resource) }; break; case Request.OBJECT + Request.UPDATE: this.string1 = new List<string>() { this.parent }; break; case Request.COMPONENT + Request.UPDATE: this.string1 = new List<string>(); this.string2 = new List<string>(); foreach (AbstractComponent component in this.components) { this.string1.Add(this.EncodeClass(component.GetType().ToString())); this.string2.Add(JsonUtility.ToJson(component)); } break; case Request.COMPONENT + Request.DELETE: this.string1 = new List<string>(); foreach (Type type in this.componentTypes) { this.string1.Add(this.EncodeClass(type.ToString())); } break; } } /// <summary> /// Encodes a String representing a NetworkModel class into a string representing a UnityEngine class /// </summary> /// <param name="name"></param> private String EncodeClass(String name) { return name.Replace("UnityNetworkModel.", "").Replace("Serializable", ""); } /// <summary> /// After the response is received from the server, unpacks serialized parameters into human-readable parameters /// </summary> public void OnAfterDeserialize() { this.messageType = this.type.Substring(0, 1); this.updateType = this.type.Substring(1, 1); switch (type) { case Request.RESOURCE + Request.UPDATE: this.resourceType = Type.GetType(this.DecodeClass(string1[0])); this.resource = (AbstractResource)JsonUtility.FromJson(this.string2[0], this.resourceType); break; case Request.OBJECT + Request.UPDATE: this.parent = this.string1[0]; break; case Request.COMPONENT + Request.UPDATE: this.components = new List<AbstractComponent>(); for (int i = 0; i < this.string1.Count && i < this.string2.Count; i++) { Type type = Type.GetType(this.DecodeClass(this.string1[i])); this.components.Add((AbstractComponent)JsonUtility.FromJson(this.string2[i], type)); } break; case Request.COMPONENT + Request.DELETE: this.componentTypes = new List<Type>(); foreach (string typeName in string1) { this.componentTypes.Add(Type.GetType(this.DecodeClass(typeName))); } break; } } /// <summary> /// Encodes a String representing a UnityEngine class into a string representing a NetworkModel class /// </summary> /// <param name="name"></param> private String DecodeClass(String name) { return "UnityNetworkModel." + name + "Serializable"; } } }
38.106464
153
0.559968
[ "MIT" ]
UweGruenefeld/UnityNetworkModel
client/unity/Assets/Scripts/NetworkModel/Network/Request.cs
10,022
C#
using Cloudlucky.GuardClauses.Exceptions; using Cloudlucky.GuardClauses.Extensions; using Cloudlucky.GuardClauses.Runtime.CompilerServices; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; namespace Cloudlucky.GuardClauses; public static partial class GuardClauseExtensions { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static IGuardClause NullOrWhiteSpace(this IGuardClause guard, [NotNull] string? input, string? message = default, NullOrWhiteSpaceOptions? options = default, [CallerArgumentExpression("input")] string? parameterName = default) { if (input.IsNullOrWhiteSpace()) { if (input is null) { throw options.GetNullException().Invoke(message, parameterName); } throw options.GetWhiteSpaceException().Invoke(message, parameterName); } return guard; } #if NET6_0_OR_GREATER [MethodImpl(MethodImplOptions.AggressiveInlining)] public static IGuardClause NullOrWhiteSpace(this IGuardClause guard, [NotNull] string? input, [InterpolatedStringHandlerArgument("input")] ref GuardAgainstNullOrWhiteSpaceInterpolatedStringHandler message, NullOrWhiteSpaceOptions? options = default, [CallerArgumentExpression("input")] string? parameterName = default) #pragma warning disable CS8777 // The parameter input won't be null at this point. => message.IsNull ? throw options.GetNullException().Invoke(message.ToString(), parameterName) : message.IsWhiteSpace ? throw options.GetWhiteSpaceException().Invoke(message.ToString(), parameterName) : guard; #pragma warning restore CS8777 #endif [MethodImpl(MethodImplOptions.AggressiveInlining)] public static IGuardClause NotNullOrWhiteSpace(this IGuardClause guard, string? input, string? message = default, NotNullOrWhiteSpaceOptions? options = default, [CallerArgumentExpression("input")] string? parameterName = default) => !input.IsNullOrWhiteSpace() ? throw options.GetNotNullOrWhiteSpaceException().Invoke(message, parameterName) : guard; #if NET6_0_OR_GREATER [MethodImpl(MethodImplOptions.AggressiveInlining)] public static IGuardClause NotNullOrWhiteSpace(this IGuardClause guard, string? input, [InterpolatedStringHandlerArgument("input")] ref GuardAgainstNotNullOrWhiteSpaceInterpolatedStringHandler message, NotNullOrWhiteSpaceOptions? options = default, [CallerArgumentExpression("input")] string? parameterName = default) => !message.IsNullOrWhiteSpace ? throw options.GetNotNullOrWhiteSpaceException().Invoke(message.ToString(), parameterName) : guard; #endif } public class NullOrWhiteSpaceOptions : IGuardOptions { public static NullOrWhiteSpaceOptions Default { get; set; } = default!; public NullOptions? NullOptions { get; set; } public GuardFunc WhiteSpaceException { get; set; } = default!; internal static void SetDefault(GuardOptionsInitializerConfiguration configuration) { Default = configuration.Exceptions switch { GuardExceptionInitializerType.SystemOnly => new() { WhiteSpaceException = (message, parameterName) => new ArgumentException(message, parameterName) }, _ => new() { WhiteSpaceException = (message, parameterName) => new EmptyException(message, parameterName) }, }; } } public static class NullOrWhiteSpaceOptionsExtensions { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static GuardFunc GetNullException(this NullOrWhiteSpaceOptions? options) => options?.NullOptions?.NullException ?? NullOrWhiteSpaceOptions.Default.NullOptions.GetNullException(); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static GuardFunc GetWhiteSpaceException(this NullOrWhiteSpaceOptions? options) => options?.WhiteSpaceException ?? NullOrWhiteSpaceOptions.Default.WhiteSpaceException; } public class NotNullOrWhiteSpaceOptions : IGuardOptions { public static NotNullOrWhiteSpaceOptions Default { get; set; } = default!; public GuardFunc NotNullOrWhiteSpaceException { get; set; } = default!; internal static void SetDefault(GuardOptionsInitializerConfiguration configuration) { Default = configuration.Exceptions switch { GuardExceptionInitializerType.SystemOnly => new() { NotNullOrWhiteSpaceException = (message, parameterName) => new ArgumentException(GuardMessages.NotNullOrEmpty(message), parameterName) }, _ => new() { NotNullOrWhiteSpaceException = (message, parameterName) => new NotNullOrEmptyException(message, parameterName) }, }; } } public static class NotNullOrWhiteSpaceOptionsExtensions { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static GuardFunc GetNotNullOrWhiteSpaceException(this NotNullOrWhiteSpaceOptions? options) => options?.NotNullOrWhiteSpaceException ?? NotNullOrWhiteSpaceOptions.Default.NotNullOrWhiteSpaceException; }
44.401709
322
0.733397
[ "MIT" ]
cloudlucky/GuardClauses
src/Cloudlucky.GuardClauses/GuardClauseExtensions.NullOrWhiteSpace.cs
5,197
C#
using System; using System.Collections.Generic; using System.Linq; namespace NetCoreStack.WebSockets { public static class EnumExtensions { public static IEnumerable<Enum> GetUniqueFlags(this Enum flags) { ulong flag = 1; foreach (var value in Enum.GetValues(flags.GetType()).Cast<Enum>()) { ulong bits = Convert.ToUInt64(value); while (flag < bits) { flag <<= 1; } if (flag == bits && flags.HasFlag(value)) { yield return value; } } } } }
24.25
79
0.472754
[ "Apache-2.0" ]
NetCoreStack/NetCoreStackWebSockets
src/NetCoreStack.WebSockets/EnumExtensions.cs
681
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using ThinkGeo.MapSuite.Drawing; using ThinkGeo.MapSuite.Shapes; using ThinkGeo.MapSuite.Styles; namespace ThinkGeo.MapSuite.WpfDesktop.Extension { [Serializable] public class TextFirstValueStyle : ValueStyle { public TextFirstValueStyle() { this.RequiredColumnNames.Add("LinkFileName"); } protected override void DrawCore(IEnumerable<Feature> features, GeoCanvas canvas , Collection<SimpleCandidate> labelsInThisLayer , Collection<SimpleCandidate> labelsInAllLayers) { foreach (Feature feature in features) { string fieldValue = string.Empty; if (feature.ColumnValues.ContainsKey(ColumnName)) { fieldValue = feature.ColumnValues[ColumnName].Trim(); } ValueItem valueItem = GetValueItem(fieldValue); Feature[] tmpFeatures = new Feature[1] { feature }; if (valueItem.CustomStyles.Count == 0) { if (valueItem.DefaultAreaStyle != null) { valueItem.DefaultAreaStyle.Draw(tmpFeatures, canvas, labelsInThisLayer, labelsInAllLayers); } if (valueItem.DefaultLineStyle != null) { valueItem.DefaultLineStyle.Draw(tmpFeatures, canvas, labelsInThisLayer, labelsInAllLayers); } if (valueItem.DefaultTextStyle != null && tmpFeatures.Any(f => f.ColumnValues.ContainsKey("NoteText") && !String.IsNullOrEmpty(f.ColumnValues["NoteText"]))) { valueItem.DefaultTextStyle.Draw(tmpFeatures, canvas, labelsInThisLayer, labelsInAllLayers); } else if (valueItem.DefaultPointStyle != null) { if (feature.ColumnValues.ContainsKey("LinkFileName") && !string.IsNullOrEmpty(feature.ColumnValues["LinkFileName"])) { if (valueItem.DefaultTextStyle.Name == "FileLinkStyle" && valueItem.DefaultPointStyle.Name == "FileLinkStyle") { TextStyle textStyle = valueItem.DefaultTextStyle; textStyle.PointPlacement = PointPlacement.LowerCenter; if (valueItem.DefaultPointStyle.CustomPointStyles.Count > 0) { textStyle.YOffsetInPixel = -(valueItem.DefaultPointStyle.CustomPointStyles.FirstOrDefault().SymbolSize / 2); } else { textStyle.YOffsetInPixel = -(valueItem.DefaultPointStyle.SymbolSize / 2); } if (textStyle.CustomTextStyles.Count > 0) { foreach (var item in textStyle.CustomTextStyles) { item.YOffsetInPixel = textStyle.YOffsetInPixel; } } Feature cloneFeature = feature.CloneDeep(); string path = cloneFeature.ColumnValues["LinkFileName"]; string columnValue = cloneFeature.ColumnValues["LinkFileName"]; if (columnValue.Contains("||")) { int index = columnValue.IndexOf("||"); path = columnValue.Substring(index + 2, columnValue.Length - index - 2); } string fileName = Path.GetFileName(path); cloneFeature.ColumnValues["LinkFileName"] = fileName; Feature[] fileLinkFeatures = new Feature[1] { cloneFeature }; textStyle.Draw(fileLinkFeatures, canvas, labelsInThisLayer, labelsInAllLayers); valueItem.DefaultPointStyle.Draw(tmpFeatures, canvas, labelsInThisLayer, labelsInAllLayers); } } else { valueItem.DefaultPointStyle.Draw(tmpFeatures, canvas, labelsInThisLayer, labelsInAllLayers); Console.Write(""); } } } else { foreach (Style style in valueItem.CustomStyles) { style.Draw(tmpFeatures, canvas, labelsInThisLayer, labelsInAllLayers); } } canvas.Flush(); } } private ValueItem GetValueItem(string columnValue) { ValueItem result = null; string value = columnValue; if (columnValue.Contains("||")) { int index = columnValue.IndexOf("||"); value = columnValue.Substring(0, index); } foreach (ValueItem valueItem in ValueItems) { if (string.Compare(value, valueItem.Value, StringComparison.OrdinalIgnoreCase) == 0) { result = valueItem; break; } } if (result == null) { result = new ValueItem(); } return result; } } }
43.621795
144
0.50698
[ "Apache-2.0" ]
ThinkGeo/GIS-Editor
MapSuiteGisEditor/WpfDesktopExtension/Styles/TextFirstValueStyle.cs
6,805
C#
namespace QSP.LibraryExtension.Graph { public class Edge<TEdge> { public TEdge Value { get; } public int FromNodeIndex { get; } public int FromIndexInList { get; } public int ToNodeIndex { get; } public int ToIndexInList { get; } private Edge() { } public Edge(TEdge Value, int FromNodeIndex, int FromIndexInList, int ToNodeIndex, int ToIndexInList) { this.Value = Value; this.FromNodeIndex = FromNodeIndex; this.FromIndexInList = FromIndexInList; this.ToNodeIndex = ToNodeIndex; this.ToIndexInList = ToIndexInList; } public static Edge<TEdge> Empty => new Edge<TEdge>(); } }
28.615385
72
0.590054
[ "MIT" ]
JetStream96/QSimPlanner
src/QSP/LibraryExtension/Graph/Edge.cs
746
C#
using EddiCompanionAppService; using EddiDataDefinitions; using EddiDataProviderService; using EddiEvents; using EddiSpeechService; using EddiStarMapService; using Newtonsoft.Json; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using Utilities; namespace Eddi { /// <summary> /// Eddi is the controller for all EDDI operations. Its job is to retain the state of the objects such as the commander, the current system, etc. /// and keep them up-to-date with changes that occur. It also passes on messages to responders to handle as required. /// </summary> public class EDDI { private static EDDI instance; // True if the Speech Responder tab is waiting on a modal dialog window. Accessed by VoiceAttack plugin. public bool SpeechResponderModalWait { get; set; } = false; private static bool started; internal static bool running = true; private static bool allowMarketUpdate = false; private static bool allowOutfittingUpdate = false; private static bool allowShipyardUpdate = false; public bool inCQC { get; private set; } = false; public bool inCrew { get; private set; } = false; public bool inHorizons { get; private set; } = true; private bool _gameIsBeta = false; public bool gameIsBeta { get => _gameIsBeta; private set { _gameIsBeta = value; CompanionAppService.Instance.inBeta = value; } } static EDDI() { // Set up our app directory Directory.CreateDirectory(Constants.DATA_DIR); } private static readonly object instanceLock = new object(); public static EDDI Instance { get { if (instance == null) { lock (instanceLock) { if (instance == null) { Logging.Debug("No EDDI instance: creating one"); instance = new EDDI(); } } } return instance; } } // Upgrade information public bool UpgradeAvailable = false; public bool UpgradeRequired = false; public string UpgradeVersion; public string UpgradeLocation; public string Motd; public List<string> ProductionBuilds = new List<string>() { "r131487/r0" }; public List<EDDIMonitor> monitors = new List<EDDIMonitor>(); private ConcurrentBag<EDDIMonitor> activeMonitors = new ConcurrentBag<EDDIMonitor>(); private static readonly object monitorLock = new object(); public List<EDDIResponder> responders = new List<EDDIResponder>(); private ConcurrentBag<EDDIResponder> activeResponders = new ConcurrentBag<EDDIResponder>(); private static readonly object responderLock = new object(); public string vaVersion { get; set; } // Information obtained from the companion app service public DateTime ApiTimeStamp { get; private set; } // Information obtained from the configuration public StarSystem HomeStarSystem { get; private set; } = new StarSystem(); public Station HomeStation { get; private set; } public StarSystem SquadronStarSystem { get; private set; } = new StarSystem(); // Destination variables public StarSystem DestinationStarSystem { get; private set; } public Station DestinationStation { get; private set; } public decimal DestinationDistanceLy { get; set; } // Information obtained from the player journal public Commander Cmdr { get; private set; } // Also includes information from the configuration and companion app service public string Environment { get; set; } public StarSystem CurrentStarSystem { get; private set; } public StarSystem LastStarSystem { get; private set; } public StarSystem NextStarSystem { get; private set; } public Station CurrentStation { get; private set; } public Body CurrentStellarBody { get; private set; } public DateTime JournalTimeStamp { get; set; } = DateTime.MinValue; // Information from the last jump we initiated (for reference) public FSDEngagedEvent LastFSDEngagedEvent { get; private set; } // Current vehicle of player public string Vehicle { get; set; } = Constants.VEHICLE_SHIP; public Ship CurrentShip { get; set; } public ObservableConcurrentDictionary<string, object> State = new ObservableConcurrentDictionary<string, object>(); // The event queue public ConcurrentQueue<Event> eventQueue { get; private set; } = new ConcurrentQueue<Event>(); private EDDI() { try { Logging.Info(Constants.EDDI_NAME + " " + Constants.EDDI_VERSION + " starting"); // Start by fetching information from the update server, and handling appropriately CheckUpgrade(); if (UpgradeRequired) { // We are too old to continue; initialize in a "safe mode". running = false; } // Ensure that our primary data structures have something in them. This allows them to be updated from any source Cmdr = new Commander(); // Set up the Elite configuration EliteConfiguration eliteConfiguration = EliteConfiguration.FromFile(); gameIsBeta = eliteConfiguration.Beta; Logging.Info(gameIsBeta ? "On beta" : "On live"); inHorizons = eliteConfiguration.Horizons; // Retrieve commander preferences EDDIConfiguration configuration = EDDIConfiguration.FromFile(); List<Task> essentialAsyncTasks = new List<Task>(); if (running) { // Tasks we can start asynchronously but need to complete before other dependent code is called essentialAsyncTasks.AddRange(new List<Task>() { Task.Run(() => responders = findResponders()), // Set up responders Task.Run(() => monitors = findMonitors()), // Set up monitors Task.Run(() => updateHomeSystemStation(configuration)), // Set up home system details Task.Run(() => // Set up squadron details { updateSquadronSystem(configuration); Cmdr.squadronname = configuration.SquadronName; Cmdr.squadronid = configuration.SquadronID; Cmdr.squadronrank = configuration.SquadronRank; Cmdr.squadronallegiance = configuration.SquadronAllegiance; Cmdr.squadronpower = configuration.SquadronPower; Cmdr.squadronfaction = configuration.SquadronFaction; }), }); } else { Logging.Info("Mandatory upgrade required! EDDI initializing in safe mode until upgrade is completed."); } // Tasks we can start asynchronously and don't need to wait for Cmdr.name = configuration.CommanderName; Cmdr.phoneticName = configuration.PhoneticName; Cmdr.gender = configuration.Gender; Task.Run(() => updateDestinationSystemStation(configuration)); Task.Run(() => { // Set up the Frontier API service if (CompanionAppService.Instance.CurrentState == CompanionAppService.State.Authorized) { // Carry out initial population of profile try { refreshProfile(); } catch (Exception ex) { Logging.Debug("Failed to obtain Frontier API profile: " + ex); } } if (CompanionAppService.Instance.CurrentState == CompanionAppService.State.Authorized) { Logging.Info("EDDI access to the Frontier API is enabled."); // Pass our commander's Frontier API name to the StarMapService (if it has been set) // (the Frontier API name may differ from the EDSM name) if (Cmdr?.name != null) { StarMapService.commanderFrontierApiName = Cmdr.name; } } else { Logging.Info("EDDI access to the Frontier API is not enabled."); } }); Task.Run(() => { // Set up the Inara service EddiInaraService.InaraService.Start(gameIsBeta, EddiIsBeta()); }); // Make sure that our essential tasks have completed before we start Task.WaitAll(essentialAsyncTasks.ToArray()); // We always start in normal space Environment = Constants.ENVIRONMENT_NORMAL_SPACE; Logging.Info(Constants.EDDI_NAME + " " + Constants.EDDI_VERSION + " initialised"); } catch (Exception ex) { Logging.Error("Failed to initialise", ex); } } public bool EddiIsBeta() => Constants.EDDI_VERSION.phase < Utilities.Version.TestPhase.rc; public bool ShouldUseTestEndpoints() { #if DEBUG return true; #else // use test endpoints if the game is in beta or EDDI is not release candidate or final return EDDI.Instance.gameIsBeta || EddiIsBeta(); #endif } /// <summary> /// Check to see if an upgrade is available and populate relevant variables /// </summary> public void CheckUpgrade() { // Clear the old values UpgradeRequired = false; UpgradeAvailable = false; UpgradeLocation = null; UpgradeVersion = null; Motd = null; try { ServerInfo updateServerInfo = ServerInfo.FromServer(Constants.EDDI_SERVER_URL); if (updateServerInfo == null) { throw new Exception("Failed to contact update server"); } else { EDDIConfiguration configuration = EDDIConfiguration.FromFile(); InstanceInfo info = configuration.Beta ? updateServerInfo.beta : updateServerInfo.production; string spokenVersion = info.version.Replace(".", $" {Properties.EddiResources.point} "); Motd = info.motd; if (updateServerInfo.productionbuilds != null) { ProductionBuilds = updateServerInfo.productionbuilds; } Utilities.Version minVersion = new Utilities.Version(info.minversion); if (minVersion > Constants.EDDI_VERSION) { // There is a mandatory update available if (!App.FromVA) { string message = String.Format(Properties.EddiResources.mandatory_upgrade, spokenVersion); SpeechService.Instance.Say(null, message, 0); } UpgradeRequired = true; UpgradeLocation = info.url; UpgradeVersion = info.version; return; } Utilities.Version latestVersion = new Utilities.Version(info.version); if (latestVersion > Constants.EDDI_VERSION) { // There is an update available if (!App.FromVA) { string message = String.Format(Properties.EddiResources.update_available, spokenVersion); SpeechService.Instance.Say(null, message, 0); } UpgradeAvailable = true; UpgradeLocation = info.url; UpgradeVersion = info.version; } } } catch (Exception ex) { SpeechService.Instance.Say(null, Properties.EddiResources.update_server_unreachable, 0); Logging.Warn("Failed to access " + Constants.EDDI_SERVER_URL, ex); } } [SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] public void Upgrade() { try { if (UpgradeLocation != null) { Logging.Info("Downloading upgrade from " + UpgradeLocation); SpeechService.Instance.Say(null, Properties.EddiResources.downloading_upgrade, 0); string updateFile = Net.DownloadFile(UpgradeLocation, @"EDDI-update.exe"); if (updateFile == null) { SpeechService.Instance.Say(null, Properties.EddiResources.download_failed, 0); } else { // Inno setup will attempt to restart this application so register it NativeMethods.RegisterApplicationRestart(null, RestartFlags.NONE); Logging.Info("Downloaded update to " + updateFile); Logging.Info("Path is " + Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); File.SetAttributes(updateFile, FileAttributes.Normal); SpeechService.Instance.Say(null, Properties.EddiResources.starting_upgrade, 0); Logging.Info("Starting upgrade."); Process.Start(updateFile, @"/closeapplications /restartapplications /silent /log /nocancel /noicon /dir=""" + Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @""""); } } } catch (Exception ex) { SpeechService.Instance.Say(null, Properties.EddiResources.upgrade_failed, 0); Logging.Error("Upgrade failed", ex); } } public void Start() { if (!started) { EDDIConfiguration configuration = EDDIConfiguration.FromFile(); foreach (EDDIMonitor monitor in monitors) { if (!configuration.Plugins.TryGetValue(monitor.MonitorName(), out bool enabled)) { // No information; default to enabled enabled = true; } if (!enabled) { Logging.Debug(monitor.MonitorName() + " is disabled; not starting"); } else { activeMonitors.Add(monitor); if (monitor.NeedsStart()) { Thread monitorThread = new Thread(() => keepAlive(monitor.MonitorName(), monitor.Start)) { IsBackground = true }; Logging.Info("Starting keepalive for " + monitor.MonitorName()); monitorThread.Start(); } } } foreach (EDDIResponder responder in responders) { if (!configuration.Plugins.TryGetValue(responder.ResponderName(), out bool enabled)) { // No information; default to enabled enabled = true; } if (!enabled) { Logging.Debug(responder.ResponderName() + " is disabled; not starting"); } else { try { bool responderStarted = responder.Start(); if (responderStarted) { activeResponders.Add(responder); Logging.Info("Started " + responder.ResponderName()); } else { Logging.Warn("Failed to start " + responder.ResponderName()); } } catch (Exception ex) { Logging.Error("Failed to start " + responder.ResponderName(), ex); } } } started = true; } } public void Stop() { running = false; // Otherwise keepalive restarts them if (started) { foreach (EDDIResponder responder in responders) { DisableResponder(responder.ResponderName()); } foreach (EDDIMonitor monitor in monitors) { DisableMonitor(monitor.MonitorName()); } } SpeechService.Instance.ShutUp(); started = false; Logging.Info(Constants.EDDI_NAME + " " + Constants.EDDI_VERSION + " stopped"); } /// <summary> /// Reload all monitors and responders /// </summary> public void Reload() { foreach (EDDIResponder responder in responders) { responder.Reload(); } foreach (EDDIMonitor monitor in monitors) { monitor.Reload(); } Logging.Info(Constants.EDDI_NAME + " " + Constants.EDDI_VERSION + " reloaded"); } /// <summary> /// Obtain a named monitor /// </summary> public EDDIMonitor ObtainMonitor(string invariantName) { foreach (EDDIMonitor monitor in monitors) { if (monitor.MonitorName().Equals(invariantName, StringComparison.InvariantCultureIgnoreCase)) { return monitor; } } return null; } /// <summary> Obtain a named responder </summary> public EDDIResponder ObtainResponder(string invariantName) { foreach (EDDIResponder responder in responders) { if (responder.ResponderName().Equals(invariantName, StringComparison.InvariantCultureIgnoreCase)) { return responder; } } return null; } /// <summary> Disable a named responder for this session. This does not update the on-disk status of the responder </summary> public void DisableResponder(string invariantName) { EDDIResponder responder = ObtainResponder(invariantName); if (responder != null) { lock (responderLock) { responder.Stop(); ConcurrentBag<EDDIResponder> newResponders = new ConcurrentBag<EDDIResponder>(); while (activeResponders.TryTake(out EDDIResponder item)) { if (item != responder) { newResponders.Add(item); } } activeResponders = newResponders; } } } /// <summary> Enable a named responder for this session. This does not update the on-disk status of the responder </summary> public void EnableResponder(string invariantName) { EDDIResponder responder = ObtainResponder(invariantName); if (responder != null) { if (!activeResponders.Contains(responder)) { responder.Start(); activeResponders.Add(responder); } } } /// <summary> Disable a named monitor for this session. This does not update the on-disk status of the responder </summary> public void DisableMonitor(string invariantName) { EDDIMonitor monitor = ObtainMonitor(invariantName); if (monitor != null) { lock (monitorLock) { monitor.Stop(); ConcurrentBag<EDDIMonitor> newMonitors = new ConcurrentBag<EDDIMonitor>(); while (activeMonitors.TryTake(out EDDIMonitor item)) { if (item != monitor) { newMonitors.Add(item); } } activeMonitors = newMonitors; } } } /// <summary> Enable a named monitor for this session. This does not update the on-disk status of the responder </summary> public void EnableMonitor(string invariantName) { EDDIMonitor monitor = ObtainMonitor(invariantName); if (monitor != null) { if (!activeMonitors.Contains(monitor)) { if (monitor.NeedsStart()) { activeMonitors.Add(monitor); Thread monitorThread = new Thread(() => keepAlive(monitor.MonitorName(), monitor.Start)) { IsBackground = true }; Logging.Info("Starting keepalive for " + monitor.MonitorName()); monitorThread.Start(); } } } } /// <summary> Reload a specific monitor or responder </summary> public void Reload(string name) { foreach (EDDIResponder responder in responders) { if (responder.ResponderName() == name) { responder.Reload(); return; } } foreach (EDDIMonitor monitor in monitors) { if (monitor.MonitorName() == name) { monitor.Reload(); } } Logging.Info($"{Constants.EDDI_NAME} {Constants.EDDI_VERSION} module {name} reloaded"); } /// <summary> Keep a monitor thread alive, restarting it as required </summary> private void keepAlive(string name, Action start) { try { int failureCount = 0; while (running && failureCount < 5 && activeMonitors.FirstOrDefault(m => m.MonitorName() == name) != null) { try { Thread monitorThread = new Thread(() => start()) { Name = name, IsBackground = true }; Logging.Info("Starting " + name + " (" + failureCount + ")"); monitorThread.Start(); monitorThread.Join(); } catch (ThreadAbortException tax) { Thread.ResetAbort(); if (running) { Logging.Error("Restarting " + name + " after thread abort", tax); } } catch (Exception ex) { if (running) { Logging.Error("Restarting " + name + " after exception", ex); } } failureCount++; } if (running) { DisableMonitor(name); Logging.Warn(name + " stopping after too many failures"); } } catch (ThreadAbortException) { Logging.Debug("Thread aborted"); } catch (Exception ex) { Logging.Warn("keepAlive for " + name + " failed", ex); } } public void enqueueEvent(Event @event) { eventQueue.Enqueue(@event); try { Thread eventHandler = new Thread(() => dequeueEvent()) { Name = "EventHandler", IsBackground = true }; eventHandler.Start(); eventHandler.Join(); } catch (ThreadAbortException tax) { Thread.ResetAbort(); Logging.Debug("Thread aborted", tax); } catch (Exception ex) { Dictionary<string, object> data = new Dictionary<string, object> { { "event", JsonConvert.SerializeObject(@event) }, { "exception", ex.Message }, { "stacktrace", ex.StackTrace } }; Logging.Error("Failed to enqueue event", data); } } private void dequeueEvent() { if (eventQueue.TryDequeue(out Event @event)) { eventHandler(@event); } } private void eventHandler(Event @event) { if (@event != null) { try { Logging.Debug("Handling event " + JsonConvert.SerializeObject(@event)); // We have some additional processing to do for a number of events bool passEvent = true; if (@event is FileHeaderEvent) { passEvent = eventFileHeader((FileHeaderEvent)@event); } else if (@event is LocationEvent) { passEvent = eventLocation((LocationEvent)@event); } else if (@event is DockedEvent) { passEvent = eventDocked((DockedEvent)@event); } else if (@event is UndockedEvent) { passEvent = eventUndocked((UndockedEvent)@event); } else if (@event is DockingRequestedEvent dockingRequestedEvent) { passEvent = eventDockingRequested(dockingRequestedEvent); } else if (@event is TouchdownEvent) { passEvent = eventTouchdown((TouchdownEvent)@event); } else if (@event is LiftoffEvent) { passEvent = eventLiftoff((LiftoffEvent)@event); } else if (@event is FSDEngagedEvent) { passEvent = eventFSDEngaged((FSDEngagedEvent)@event); } else if (@event is FSDTargetEvent) { passEvent = eventFSDTarget((FSDTargetEvent)@event); } else if (@event is JumpedEvent) { passEvent = eventJumped((JumpedEvent)@event); } else if (@event is EnteredSupercruiseEvent) { passEvent = eventEnteredSupercruise((EnteredSupercruiseEvent)@event); } else if (@event is EnteredNormalSpaceEvent) { passEvent = eventEnteredNormalSpace((EnteredNormalSpaceEvent)@event); } else if (@event is CommanderLoadingEvent) { passEvent = eventCommanderLoading((CommanderLoadingEvent)@event); } else if (@event is CommanderContinuedEvent) { passEvent = eventCommanderContinued((CommanderContinuedEvent)@event); } else if (@event is CommanderRatingsEvent) { passEvent = eventCommanderRatings((CommanderRatingsEvent)@event); } else if (@event is CombatPromotionEvent) { passEvent = eventCombatPromotion((CombatPromotionEvent)@event); } else if (@event is TradePromotionEvent) { passEvent = eventTradePromotion((TradePromotionEvent)@event); } else if (@event is ExplorationPromotionEvent) { passEvent = eventExplorationPromotion((ExplorationPromotionEvent)@event); } else if (@event is FederationPromotionEvent) { passEvent = eventFederationPromotion((FederationPromotionEvent)@event); } else if (@event is EmpirePromotionEvent) { passEvent = eventEmpirePromotion((EmpirePromotionEvent)@event); } else if (@event is CrewJoinedEvent) { passEvent = eventCrewJoined((CrewJoinedEvent)@event); } else if (@event is CrewLeftEvent) { passEvent = eventCrewLeft((CrewLeftEvent)@event); } else if (@event is EnteredCQCEvent) { passEvent = eventEnteredCQC((EnteredCQCEvent)@event); } else if (@event is SRVLaunchedEvent) { passEvent = eventSRVLaunched((SRVLaunchedEvent)@event); } else if (@event is SRVDockedEvent) { passEvent = eventSRVDocked((SRVDockedEvent)@event); } else if (@event is FighterLaunchedEvent) { passEvent = eventFighterLaunched((FighterLaunchedEvent)@event); } else if (@event is FighterDockedEvent) { passEvent = eventFighterDocked((FighterDockedEvent)@event); } else if (@event is StarScannedEvent) { passEvent = eventStarScanned((StarScannedEvent)@event); } else if (@event is BodyScannedEvent) { passEvent = eventBodyScanned((BodyScannedEvent)@event); } else if (@event is BodyMappedEvent) { passEvent = eventBodyMapped((BodyMappedEvent)@event); } else if (@event is RingMappedEvent) { passEvent = eventRingMapped((RingMappedEvent)@event); } else if (@event is VehicleDestroyedEvent) { passEvent = eventVehicleDestroyed((VehicleDestroyedEvent)@event); } else if (@event is NearSurfaceEvent) { passEvent = eventNearSurface((NearSurfaceEvent)@event); } else if (@event is SquadronStatusEvent) { passEvent = eventSquadronStatus((SquadronStatusEvent)@event); } else if (@event is SquadronRankEvent) { passEvent = eventSquadronRank((SquadronRankEvent)@event); } else if (@event is FriendsEvent) { passEvent = eventFriends((FriendsEvent)@event); } else if (@event is MarketEvent) { passEvent = eventMarket((MarketEvent)@event); } else if (@event is OutfittingEvent) { passEvent = eventOutfitting((OutfittingEvent)@event); } else if (@event is ShipyardEvent) { passEvent = eventShipyard((ShipyardEvent)@event); } else if (@event is SettlementApproachedEvent) { passEvent = eventSettlementApproached((SettlementApproachedEvent)@event); } else if (@event is DiscoveryScanEvent) { passEvent = eventDiscoveryScan((DiscoveryScanEvent)@event); } else if (@event is SystemScanComplete) { passEvent = eventSystemScanComplete((SystemScanComplete)@event); } else if (@event is PowerplayEvent) { passEvent = eventPowerplay((PowerplayEvent)@event); } else if (@event is PowerDefectedEvent) { passEvent = eventPowerDefected((PowerDefectedEvent)@event); } else if (@event is PowerJoinedEvent) { passEvent = eventPowerJoined((PowerJoinedEvent)@event); } else if (@event is PowerLeftEvent) { passEvent = eventPowerLeft((PowerLeftEvent)@event); } else if (@event is PowerPreparationVoteCast) { passEvent = eventPowerPreparationVoteCast((PowerPreparationVoteCast)@event); } else if (@event is PowerSalaryClaimedEvent) { passEvent = eventPowerSalaryClaimed((PowerSalaryClaimedEvent)@event); } else if (@event is PowerVoucherReceivedEvent) { passEvent = eventPowerVoucherReceived((PowerVoucherReceivedEvent)@event); } // Additional processing is over, send to the event responders if required if (passEvent) { OnEvent(@event); } } catch (Exception ex) { Dictionary<string, object> data = new Dictionary<string, object> { { "event", JsonConvert.SerializeObject(@event) }, { "exception", ex.Message }, { "stacktrace", ex.StackTrace } }; Logging.Error("EDDI core failed to handle event " + @event.type, data); // Even if an error occurs, we still need to pass the raw data // to the EDDN responder to maintain it's integrity. Instance.ObtainResponder("EDDN responder").Handle(@event); } } } private bool eventPowerVoucherReceived(PowerVoucherReceivedEvent @event) { Cmdr.Power = @event.Power; return true; } private bool eventPowerSalaryClaimed(PowerSalaryClaimedEvent @event) { Cmdr.Power = @event.Power; return true; } private bool eventPowerPreparationVoteCast(PowerPreparationVoteCast @event) { Cmdr.Power = @event.Power; return true; } private bool eventPowerLeft(PowerLeftEvent @event) { Cmdr.Power = Power.None; Cmdr.powermerits = null; Cmdr.powerrating = 0; // Store power merits EDDIConfiguration configuration = EDDIConfiguration.FromFile(); configuration.powerMerits = Cmdr.powermerits; configuration.ToFile(); return true; } private bool eventPowerJoined(PowerJoinedEvent @event) { Cmdr.Power = @event.Power; Cmdr.powermerits = 0; Cmdr.powerrating = 1; // Store power merits EDDIConfiguration configuration = EDDIConfiguration.FromFile(); configuration.powerMerits = Cmdr.powermerits; configuration.ToFile(); return true; } private bool eventPowerDefected(PowerDefectedEvent @event) { Cmdr.Power = @event.toPower; // Merits are halved upon defection Cmdr.powermerits = (int)Math.Round((double)Cmdr.powermerits / 2, 0); if (Cmdr.powermerits > 10000) { Cmdr.powerrating = 4; } if (Cmdr.powermerits > 1500) { Cmdr.powerrating = 3; } if (Cmdr.powermerits > 750) { Cmdr.powerrating = 2; } if (Cmdr.powermerits > 100) { Cmdr.powerrating = 1; } else { Cmdr.powerrating = 0; } // Store power merits EDDIConfiguration configuration = EDDIConfiguration.FromFile(); configuration.powerMerits = Cmdr.powermerits; configuration.ToFile(); return true; } private bool eventPowerplay(PowerplayEvent @event) { if (Cmdr.powermerits is null) { // Per the journal, this is written at startup. In actuality, it can also be written whenever switching FSD states // and needs to be filtered to prevent redundant outputs. Cmdr.Power = @event.Power; Cmdr.powerrating = @event.rank; Cmdr.powermerits = @event.merits; // Store power merits EDDIConfiguration configuration = EDDIConfiguration.FromFile(); configuration.powerMerits = @event.merits; configuration.ToFile(); return true; } else { return false; } } private bool eventSystemScanComplete(SystemScanComplete @event) { // There is a bug in the player journal output (as of player journal v.25) that can cause the `SystemScanComplete` event to fire multiple times // in rapid succession when performing a system scan of a star system with only stars and no other bodies. if (CurrentStarSystem != null) { if ((bool)CurrentStarSystem?.systemScanCompleted) { // We will suppress repetitions of the event within the same star system. return false; } CurrentStarSystem.systemScanCompleted = true; } return true; } private bool eventDiscoveryScan(DiscoveryScanEvent @event) { if (CurrentStarSystem != null) { CurrentStarSystem.totalbodies = @event.totalbodies; StarSystemSqLiteRepository.Instance.SaveStarSystem(CurrentStarSystem); } return true; } private bool eventSettlementApproached(SettlementApproachedEvent @event) { Station station = CurrentStarSystem?.stations?.Find(s => s.name == @event.name); if (station == null && @event.systemAddress == CurrentStarSystem?.systemAddress) { // This settlement is unknown to us, might not be in our data source or we might not have connectivity. Use a placeholder station = new Station { name = @event.name, marketId = @event.marketId, systemname = CurrentStarSystem.systemname }; CurrentStarSystem?.stations?.Add(station); } return true; } private bool eventFriends(FriendsEvent @event) { bool passEvent = false; Friend cmdr = new Friend { name = @event.name, status = @event.status }; /// Does this friend exist in our friends list? int index = Cmdr.friends.FindIndex(friend => friend.name == @event.name); if (index >= 0) { if (Cmdr.friends[index].status != @event.status) { /// This is a known friend with a revised status: replace in situ (this is more efficient than removing and re-adding). Cmdr.friends[index] = cmdr; passEvent = true; } } else { /// This is a new friend, add them to the list Cmdr.friends.Add(cmdr); } return passEvent; } private async void OnEvent(Event @event) { // We send the event to all monitors to ensure that their info is up-to-date // All changes to state must be handled here, so this must be synchronous passToMonitorPreHandlers(@event); // Now we pass the data to the responders to process asynchronously, waiting for all to complete // Responders must not change global states. await passToRespondersAsync(@event); // We also pass the event to all active monitors in case they have asynchronous follow-on work, waiting for all to complete await passToMonitorPostHandlersAsync(@event); } private void passToMonitorPreHandlers(Event @event) { foreach (EDDIMonitor monitor in activeMonitors) { try { monitor.PreHandle(@event); } catch (Exception ex) { Dictionary<string, object> data = new Dictionary<string, object> { { "event", JsonConvert.SerializeObject(@event) }, { "exception", ex.Message }, { "stacktrace", ex.StackTrace } }; Logging.Error(monitor.MonitorName() + " failed to handle event " + @event.type, data); } } } private async Task passToRespondersAsync(Event @event) { List<Task> responderTasks = new List<Task>(); foreach (EDDIResponder responder in activeResponders) { try { var responderTask = Task.Run(() => { try { responder.Handle(@event); } catch (Exception ex) { Logging.Error(responder.ResponderName() + " failed to handle event " + JsonConvert.SerializeObject(@event), ex); } }); responderTasks.Add(responderTask); } catch (Exception ex) { Dictionary<string, object> data = new Dictionary<string, object> { { "event", JsonConvert.SerializeObject(@event) }, { "exception", ex.Message }, { "stacktrace", ex.StackTrace } }; Logging.Error(responder.ResponderName() + " failed to handle event " + @event.type, data); } } await Task.WhenAll(responderTasks.ToArray()); } private async Task passToMonitorPostHandlersAsync(Event @event) { List<Task> monitorTasks = new List<Task>(); foreach (EDDIMonitor monitor in activeMonitors) { try { var monitorTask = Task.Run(() => { try { monitor.PostHandle(@event); } catch (Exception ex) { Logging.Error(monitor.MonitorName() + " failed to post-handle event " + JsonConvert.SerializeObject(@event), ex); } }); monitorTasks.Add(monitorTask); } catch (ThreadAbortException tax) { Thread.ResetAbort(); Logging.Debug("Thread aborted", tax); } catch (Exception ex) { Dictionary<string, object> data = new Dictionary<string, object> { { "event", JsonConvert.SerializeObject(@event) }, { "exception", ex.Message }, { "stacktrace", ex.StackTrace } }; Logging.Error(monitor.MonitorName() + " failed to post-handle event " + @event.type, data); } await Task.WhenAll(monitorTasks.ToArray()); } } private bool eventLocation(LocationEvent theEvent) { Logging.Info("Location StarSystem: " + theEvent.systemname); updateCurrentSystem(theEvent.systemname); // Our data source may not include the system address CurrentStarSystem.systemAddress = theEvent.systemAddress; // Always update the current system with the current co-ordinates, just in case things have changed CurrentStarSystem.x = theEvent.x; CurrentStarSystem.y = theEvent.y; CurrentStarSystem.z = theEvent.z; // Update the mutable system data from the journal if (theEvent.population != null) { CurrentStarSystem.population = theEvent.population; CurrentStarSystem.Economies = new List<Economy> { theEvent.Economy, theEvent.Economy2 }; CurrentStarSystem.securityLevel = theEvent.securityLevel; CurrentStarSystem.Faction = theEvent.controllingsystemfaction; } // Update system faction data if available if (theEvent.factions != null) { CurrentStarSystem.factions = theEvent.factions; // Update station controlling faction data foreach (Station station in CurrentStarSystem.stations) { Faction stationFaction = theEvent.factions.FirstOrDefault(f => f.name == station.Faction.name); if (stationFaction != null) { station.Faction = stationFaction; } } // Check if current system is inhabited by or HQ for squadron faction Faction squadronFaction = theEvent.factions.FirstOrDefault(f => (bool)f.presences. FirstOrDefault(p => p.systemName == CurrentStarSystem.systemname)?.squadronhomesystem || f.squadronfaction); if (squadronFaction != null) { updateSquadronData(squadronFaction, CurrentStarSystem.systemname); } } // (When pledged) Powerplay information CurrentStarSystem.Power = theEvent.Power is null ? CurrentStarSystem.Power : theEvent.Power; CurrentStarSystem.powerState = theEvent.powerState is null ? CurrentStarSystem.powerState : theEvent.powerState; if (theEvent.docked || theEvent.bodytype.ToLowerInvariant() == "station") { // In this case body = station and our body information is invalid CurrentStellarBody = null; // Update the station string stationName = theEvent.docked ? theEvent.station : theEvent.bodyname; Logging.Debug("Now at station " + stationName); Station station = CurrentStarSystem.stations.Find(s => s.name == stationName); if (station == null) { // This station is unknown to us, might not be in our data source or we might not have connectivity. Use a placeholder station = new Station { name = stationName, systemname = theEvent.systemname }; CurrentStarSystem.stations.Add(station); } CurrentStation = station; if (theEvent.docked) { // We are docked and in the ship Environment = Constants.ENVIRONMENT_DOCKED; Vehicle = Constants.VEHICLE_SHIP; // Our data source may not include the market id or system address station.marketId = theEvent.marketId; station.systemAddress = theEvent.systemAddress; station.Faction = theEvent.controllingstationfaction; // Kick off the profile refresh if the companion API is available if (CompanionAppService.Instance.CurrentState == CompanionAppService.State.Authorized) { // Refresh station data if (theEvent.fromLoad) { return true; } // Don't fire this event when loading pre-existing logs profileUpdateNeeded = true; profileStationRequired = CurrentStation.name; Thread updateThread = new Thread(() => conditionallyRefreshProfile()) { IsBackground = true }; updateThread.Start(); } } else { Environment = Constants.ENVIRONMENT_NORMAL_SPACE; } } else if (theEvent.bodyname != null) { Environment = Constants.ENVIRONMENT_NORMAL_SPACE; // If we are not at a station then our station information is invalid CurrentStation = null; // Update the body Logging.Debug("Now at body " + theEvent.bodyname); updateCurrentStellarBody(theEvent.bodyname, theEvent.systemname, theEvent.systemAddress); } else { // We are near neither a stellar body nor a station. CurrentStellarBody = null; CurrentStation = null; } return true; } private bool eventDockingRequested(DockingRequestedEvent theEvent) { Station station = CurrentStarSystem.stations.Find(s => s.name == theEvent.station); if (station == null) { // This station is unknown to us, might not be in our data source or we might not have connectivity. Use a placeholder station = new Station { name = theEvent.station, marketId = theEvent.marketId, systemname = CurrentStarSystem.systemname, systemAddress = CurrentStarSystem.systemAddress }; CurrentStarSystem.stations.Add(station); } station.Model = theEvent.stationDefinition; return true; } private bool eventDocked(DockedEvent theEvent) { updateCurrentSystem(theEvent.system); // Upon docking, allow manual station updates once allowMarketUpdate = true; allowOutfittingUpdate = true; allowShipyardUpdate = true; if (Environment == Constants.ENVIRONMENT_DOCKED) { // We are already at this station; nothing to do Logging.Debug("Already at station " + theEvent.station); return false; } // We are docked and in the ship Environment = Constants.ENVIRONMENT_DOCKED; Vehicle = Constants.VEHICLE_SHIP; // Update the station Logging.Debug("Now at station " + theEvent.station); Station station = CurrentStarSystem.stations.Find(s => s.name == theEvent.station); if (station == null) { // This station is unknown to us, might not be in our data source or we might not have connectivity. Use a placeholder station = new Station { name = theEvent.station, systemname = theEvent.system }; CurrentStarSystem.stations.Add(station); } // Not all stations in our database will have a system address or market id, so we set them here station.systemAddress = theEvent.systemAddress; station.marketId = theEvent.marketId; // Information from the event might be more current than our data source so use it in preference station.Faction = theEvent.controllingfaction; station.stationServices = theEvent.stationServices; station.economyShares = theEvent.economyShares; // Update other station information available from the event station.Model = theEvent.stationModel; station.stationServices = theEvent.stationServices; station.distancefromstar = theEvent.distancefromstar; CurrentStation = station; CurrentStellarBody = null; // Kick off the profile refresh if the companion API is available if (CompanionAppService.Instance.CurrentState == CompanionAppService.State.Authorized) { // Refresh station data if (theEvent.fromLoad) { return true; } // Don't fire this event when loading pre-existing logs profileUpdateNeeded = true; profileStationRequired = CurrentStation.name; Thread updateThread = new Thread(() => conditionallyRefreshProfile()) { IsBackground = true }; updateThread.Start(); } return true; } private bool eventUndocked(UndockedEvent theEvent) { Environment = Constants.ENVIRONMENT_NORMAL_SPACE; Vehicle = Constants.VEHICLE_SHIP; // Call refreshProfile() to ensure that our ship is up-to-date refreshProfile(); return true; } private bool eventTouchdown(TouchdownEvent theEvent) { Environment = Constants.ENVIRONMENT_LANDED; if (theEvent.playercontrolled) { Vehicle = Constants.VEHICLE_SHIP; } else { Vehicle = Constants.VEHICLE_SRV; } return true; } private bool eventLiftoff(LiftoffEvent theEvent) { Environment = Constants.ENVIRONMENT_NORMAL_SPACE; if (theEvent.playercontrolled) { Vehicle = Constants.VEHICLE_SHIP; } else { Vehicle = Constants.VEHICLE_SRV; } return true; } private bool eventMarket(MarketEvent theEvent) { if (allowMarketUpdate) { MarketInfoReader info = MarketInfoReader.FromFile(); if (info != null && info.MarketID == theEvent.marketId && info.StarSystem == theEvent.system && info.StationName == theEvent.station) { List<CommodityMarketQuote> quotes = new List<CommodityMarketQuote>(); foreach (MarketInfo item in info.Items) { CommodityMarketQuote quote = CommodityMarketQuote.FromMarketInfo(item); if (quote != null) { quotes.Add(quote); } } if (quotes != null && info.Items.Count == quotes.Count) { if (CurrentStation?.marketId != null && CurrentStation?.marketId == theEvent.marketId) { // Update the current station commodities allowMarketUpdate = false; CurrentStation.commodities = quotes; CurrentStation.commoditiesupdatedat = Dates.fromDateTimeToSeconds(DateTime.UtcNow); // Update the current station information in our backend DB Logging.Debug("Star system information updated from remote server; updating local copy"); StarSystemSqLiteRepository.Instance.SaveStarSystem(CurrentStarSystem); } // Post an update event for new market data if (theEvent.fromLoad) { return true; } // Don't fire this event when loading pre-existing logs Event @event = new MarketInformationUpdatedEvent(info.timestamp, inHorizons, theEvent.system, theEvent.station, theEvent.marketId, quotes, null, null, null); enqueueEvent(@event); } return true; } } return false; } private bool eventOutfitting(OutfittingEvent theEvent) { if (allowOutfittingUpdate) { OutfittingInfoReader info = OutfittingInfoReader.FromFile(); if (info.Items != null && info.MarketID == theEvent.marketId && info.StarSystem == theEvent.system && info.StationName == theEvent.station && info.Horizons == Instance.inHorizons) { List<EddiDataDefinitions.Module> modules = new List<EddiDataDefinitions.Module>(); foreach (OutfittingInfo item in info.Items) { EddiDataDefinitions.Module module = EddiDataDefinitions.Module.FromOutfittingInfo(item); if (module != null) { modules.Add(module); } } if (modules != null && info.Items.Count == modules.Count) { if (CurrentStation?.marketId != null && CurrentStation?.marketId == theEvent.marketId) { // Update the current station outfitting allowOutfittingUpdate = false; CurrentStation.outfitting = modules; CurrentStation.outfittingupdatedat = Dates.fromDateTimeToSeconds(DateTime.UtcNow); // Update the current station information in our backend DB Logging.Debug("Star system information updated from remote server; updating local copy"); StarSystemSqLiteRepository.Instance.SaveStarSystem(CurrentStarSystem); } // Post an update event for new outfitting data if (theEvent.fromLoad) { return true; } // Don't fire this event when loading pre-existing logs Event @event = new MarketInformationUpdatedEvent(info.timestamp, inHorizons, theEvent.system, theEvent.station, theEvent.marketId, null, null, modules, null); enqueueEvent(@event); } return true; } } return false; } private bool eventShipyard(ShipyardEvent theEvent) { if (allowShipyardUpdate) { ShipyardInfoReader info = ShipyardInfoReader.FromFile(); if (info.PriceList != null && info.MarketID == theEvent.marketId && info.StarSystem == theEvent.system && info.StationName == theEvent.station && info.Horizons == Instance.inHorizons) { List<Ship> ships = new List<Ship>(); foreach (ShipyardInfo item in info.PriceList) { Ship ship = Ship.FromShipyardInfo(item); if (ship != null) { ships.Add(ship); } } if (ships != null && info.PriceList.Count == ships.Count) { if (CurrentStation?.marketId != null && CurrentStation?.marketId == theEvent.marketId) { // Update the current station shipyard allowShipyardUpdate = false; CurrentStation.shipyard = ships; CurrentStation.shipyardupdatedat = Dates.fromDateTimeToSeconds(DateTime.UtcNow); // Update the current station information in our backend DB Logging.Debug("Star system information updated from remote server; updating local copy"); StarSystemSqLiteRepository.Instance.SaveStarSystem(CurrentStarSystem); } // Post an update event for new shipyard data if (theEvent.fromLoad) { return true; } // Don't fire this event when loading pre-existing logs Event @event = new MarketInformationUpdatedEvent(info.timestamp, inHorizons, theEvent.system, theEvent.station, theEvent.marketId, null, null, null, ships); enqueueEvent(@event); } return true; } } return false; } private void updateCurrentSystem(string name) { if (name == null || CurrentStarSystem?.systemname == name) { return; } // We have changed system so update the old one as to when we left StarSystemSqLiteRepository.Instance.LeaveStarSystem(CurrentStarSystem); LastStarSystem = CurrentStarSystem; if (NextStarSystem?.systemname == name) { CurrentStarSystem = NextStarSystem; NextStarSystem = null; } else { CurrentStarSystem = StarSystemSqLiteRepository.Instance.GetOrCreateStarSystem(name); } setSystemDistanceFromHome(CurrentStarSystem); setSystemDistanceFromDestination(CurrentStarSystem); setCommanderTitle(); } private void updateCurrentStellarBody(string bodyName, string systemName, long? systemAddress = null) { // Make sure our system information is up to date if (CurrentStarSystem == null || CurrentStarSystem.systemname != systemName) { updateCurrentSystem(systemName); } // Update the body if (CurrentStarSystem != null) { Body body = CurrentStarSystem.bodies?.Find(s => s.bodyname == bodyName); if (body == null) { // We may be near a ring. For rings, we want to select the parent body List<Body> ringedBodies = CurrentStarSystem.bodies? .Where(b => b?.rings?.Count > 0).ToList(); foreach (Body ringedBody in ringedBodies) { Ring ring = ringedBody.rings.FirstOrDefault(r => r.name == bodyName); if (ring != null) { body = ringedBody; break; } } } if (body == null) { // This body is unknown to us, might not be in EDDB or we might not have connectivity. Use a placeholder body = new Body { bodyname = bodyName, systemname = systemName, systemAddress = systemAddress, }; } CurrentStellarBody = body; } } private bool eventFSDEngaged(FSDEngagedEvent @event) { // Keep track of our environment if (@event.target == "Supercruise") { Environment = Constants.ENVIRONMENT_SUPERCRUISE; } else { Environment = Constants.ENVIRONMENT_WITCH_SPACE; } // We are in the ship Vehicle = Constants.VEHICLE_SHIP; // Remove information about the current station and stellar body CurrentStation = null; CurrentStellarBody = null; // Set the destination system as the current star system updateCurrentSystem(@event.system); // Save a copy of this event for later reference LastFSDEngagedEvent = @event; return true; } private bool eventFSDTarget(FSDTargetEvent @event) { // Set and prepare data about the next star system NextStarSystem = StarSystemSqLiteRepository.Instance.GetOrFetchStarSystem(@event.system); return true; } private bool eventFileHeader(FileHeaderEvent @event) { // Test whether we're in beta by checking the filename, version described by the header, // and certain version / build combinations gameIsBeta = ( @event.filename.Contains("Beta") || @event.version.Contains("Beta") || ( @event.version.Contains("2.2") && ( @event.build.Contains("r121645/r0") || @event.build.Contains("r129516/r0") ) ) ); Logging.Info(gameIsBeta ? "On beta" : "On live"); EliteConfiguration config = EliteConfiguration.FromFile(); config.Beta = gameIsBeta; config.ToFile(); return true; } private bool eventJumped(JumpedEvent theEvent) { bool passEvent; Logging.Info("Jumped to " + theEvent.system); if (CurrentStarSystem == null || CurrentStarSystem.systemname != theEvent.system) { // The 'StartJump' event must have been missed updateCurrentSystem(theEvent.system); } passEvent = true; CurrentStarSystem.systemAddress = theEvent.systemAddress; CurrentStarSystem.x = theEvent.x; CurrentStarSystem.y = theEvent.y; CurrentStarSystem.z = theEvent.z; CurrentStarSystem.Faction = theEvent.controllingfaction; CurrentStellarBody = CurrentStarSystem.bodies.Find(b => b.bodyname == theEvent.star) ?? CurrentStarSystem.bodies.Find(b => b.distance == 0); CurrentStarSystem.conflicts = theEvent.conflicts; // Update system faction data if available if (theEvent.factions != null) { CurrentStarSystem.factions = theEvent.factions; // Update station controlling faction data foreach (Station station in CurrentStarSystem.stations) { Faction stationFaction = theEvent.factions.Find(f => f.name == station.Faction.name); if (stationFaction != null) { station.Faction = stationFaction; } } // Check if current system is inhabited by or HQ for squadron faction Faction squadronFaction = theEvent.factions.Find(f => (bool)f.presences. Find(p => p.systemName == CurrentStarSystem.systemname)?.squadronhomesystem || f.squadronfaction); if (squadronFaction != null) { updateSquadronData(squadronFaction, CurrentStarSystem.systemname); } } CurrentStarSystem.Economies = new List<Economy> { theEvent.Economy, theEvent.Economy2 }; CurrentStarSystem.securityLevel = theEvent.securityLevel; if (theEvent.population != null) { CurrentStarSystem.population = theEvent.population; } // If we don't have any information about bodies in the system yet, create a basic star from current and saved event data if (CurrentStellarBody == null && !string.IsNullOrEmpty(theEvent.star)) { CurrentStellarBody = new Body() { bodyname = theEvent.star, bodyType = BodyType.FromEDName("Star"), stellarclass = LastFSDEngagedEvent?.stellarclass, }; CurrentStarSystem.AddOrUpdateBody(CurrentStellarBody); } // (When pledged) Powerplay information CurrentStarSystem.Power = theEvent.Power is null ? CurrentStarSystem.Power : theEvent.Power; CurrentStarSystem.powerState = theEvent.powerState is null ? CurrentStarSystem.powerState : theEvent.powerState; // Update to most recent information CurrentStarSystem.visitLog.Add(theEvent.timestamp); CurrentStarSystem.updatedat = Dates.fromDateTimeToSeconds(theEvent.timestamp); StarSystemSqLiteRepository.Instance.SaveStarSystem(CurrentStarSystem); // After jump has completed we are always in supercruise Environment = Constants.ENVIRONMENT_SUPERCRUISE; // No longer in 'station instance' CurrentStation = null; return passEvent; } private bool eventEnteredSupercruise(EnteredSupercruiseEvent theEvent) { Environment = Constants.ENVIRONMENT_SUPERCRUISE; updateCurrentSystem(theEvent.system); // No longer in 'station instance' CurrentStation = null; // We are in the ship Vehicle = Constants.VEHICLE_SHIP; return true; } private bool eventEnteredNormalSpace(EnteredNormalSpaceEvent theEvent) { Environment = Constants.ENVIRONMENT_NORMAL_SPACE; if (theEvent.bodyType == BodyType.FromEDName("Station")) { // In this case body == station Station station = CurrentStarSystem.stations.Find(s => s.name == theEvent.bodyname); if (station == null) { // This station is unknown to us, might not be in our data source or we might not have connectivity. Use a placeholder station = new Station { name = theEvent.bodyname, systemname = theEvent.systemname }; } CurrentStation = station; } else if (theEvent.bodyname != null) { updateCurrentStellarBody(theEvent.bodyname, theEvent.systemname, theEvent.systemAddress); } updateCurrentSystem(theEvent.systemname); return true; } private bool eventCrewJoined(CrewJoinedEvent theEvent) { inCrew = true; Logging.Info("Entering multicrew session"); return true; } private bool eventCrewLeft(CrewLeftEvent theEvent) { inCrew = false; Logging.Info("Leaving multicrew session"); return true; } private bool eventCommanderLoading(CommanderLoadingEvent theEvent) { // Set our commander name and ID Cmdr.name = theEvent.name; Cmdr.EDID = theEvent.frontierID; return true; } private bool eventCommanderContinued(CommanderContinuedEvent theEvent) { // If we see this it means that we aren't in CQC inCQC = false; // Set our commander name and ID Cmdr.name = theEvent.commander; Cmdr.EDID = theEvent.frontierID; // Set game version inHorizons = theEvent.horizons; EliteConfiguration config = EliteConfiguration.FromFile(); config.Horizons = inHorizons; config.ToFile(); return true; } private bool eventCommanderRatings(CommanderRatingsEvent theEvent) { // Capture commander ratings and add them to the commander object if (Cmdr != null) { Cmdr.combatrating = theEvent.combat; Cmdr.traderating = theEvent.trade; Cmdr.explorationrating = theEvent.exploration; Cmdr.cqcrating = theEvent.cqc; Cmdr.empirerating = theEvent.empire; Cmdr.federationrating = theEvent.federation; } return true; } private bool eventCombatPromotion(CombatPromotionEvent theEvent) { // There is a bug with the journal where it reports superpower increases in rank as combat increases // Hence we check to see if this is a real event by comparing our known combat rating to the promoted rating if ((Cmdr == null || Cmdr.combatrating == null) || theEvent.rating != Cmdr.combatrating.localizedName) { // Real event. Capture commander ratings and add them to the commander object if (Cmdr != null) { Cmdr.combatrating = CombatRating.FromName(theEvent.rating); } return true; } else { // False event return false; } } private bool eventTradePromotion(TradePromotionEvent theEvent) { // Capture commander ratings and add them to the commander object if (Cmdr != null) { Cmdr.traderating = TradeRating.FromName(theEvent.rating); } return true; } private bool eventExplorationPromotion(ExplorationPromotionEvent theEvent) { // Capture commander ratings and add them to the commander object if (Cmdr != null) { Cmdr.explorationrating = ExplorationRating.FromName(theEvent.rating); } return true; } private bool eventFederationPromotion(FederationPromotionEvent theEvent) { // Capture commander ratings and add them to the commander object if (Cmdr != null) { Cmdr.federationrating = FederationRating.FromName(theEvent.rank); } return true; } private bool eventEmpirePromotion(EmpirePromotionEvent theEvent) { // Capture commander ratings and add them to the commander object if (Cmdr != null) { Cmdr.empirerating = EmpireRating.FromName(theEvent.rank); } return true; } private bool eventSquadronStartup(SquadronStartupEvent theEvent) { SquadronRank rank = SquadronRank.FromRank(theEvent.rank + 1); // Update the configuration file EDDIConfiguration configuration = EDDIConfiguration.FromFile(); configuration.SquadronName = theEvent.name; configuration.SquadronRank = rank; configuration.ToFile(); // Update the squadron UI data Application.Current?.Dispatcher?.Invoke(() => { if (Application.Current?.MainWindow != null) { ((MainWindow)Application.Current.MainWindow).eddiSquadronNameText.Text = theEvent.name; ((MainWindow)Application.Current.MainWindow).squadronRankDropDown.SelectedItem = rank.localizedName; } }); // Update the commander object, if it exists if (Cmdr != null) { Cmdr.squadronname = theEvent.name; Cmdr.squadronrank = rank; } return true; } private bool eventSquadronStatus(SquadronStatusEvent theEvent) { EDDIConfiguration configuration = EDDIConfiguration.FromFile(); switch (theEvent.status) { case "created": { SquadronRank rank = SquadronRank.FromRank(1); // Update the configuration file configuration.SquadronName = theEvent.name; configuration.SquadronRank = rank; // Update the squadron UI data Application.Current?.Dispatcher?.Invoke(() => { if (Application.Current?.MainWindow != null) { ((MainWindow)Application.Current.MainWindow).eddiSquadronNameText.Text = theEvent.name; ((MainWindow)Application.Current.MainWindow).squadronRankDropDown.SelectedItem = rank.localizedName; configuration = ((MainWindow)Application.Current.MainWindow).resetSquadronRank(configuration); } }); // Update the commander object, if it exists if (Cmdr != null) { Cmdr.squadronname = theEvent.name; Cmdr.squadronrank = rank; } break; } case "joined": { // Update the configuration file configuration.SquadronName = theEvent.name; // Update the squadron UI data Application.Current?.Dispatcher?.Invoke(() => { if (Application.Current?.MainWindow != null) { ((MainWindow)Application.Current.MainWindow).eddiSquadronNameText.Text = theEvent.name; } }); // Update the commander object, if it exists if (Cmdr != null) { Cmdr.squadronname = theEvent.name; } break; } case "disbanded": case "kicked": case "left": { // Update the configuration file configuration.SquadronName = null; configuration.SquadronID = null; // Update the squadron UI data Application.Current?.Dispatcher?.Invoke(() => { if (Application.Current?.MainWindow != null) { ((MainWindow)Application.Current.MainWindow).eddiSquadronNameText.Text = string.Empty; ((MainWindow)Application.Current.MainWindow).eddiSquadronIDText.Text = string.Empty; configuration = ((MainWindow)Application.Current.MainWindow).resetSquadronRank(configuration); } }); // Update the commander object, if it exists if (Cmdr != null) { Cmdr.squadronname = null; } break; } } configuration.ToFile(); return true; } private bool eventSquadronRank(SquadronRankEvent theEvent) { SquadronRank rank = SquadronRank.FromRank(theEvent.newrank + 1); // Update the configuration file EDDIConfiguration configuration = EDDIConfiguration.FromFile(); configuration.SquadronName = theEvent.name; configuration.SquadronRank = rank; configuration.ToFile(); // Update the squadron UI data Application.Current?.Dispatcher?.Invoke(() => { if (Application.Current?.MainWindow != null) { ((MainWindow)Application.Current.MainWindow).eddiSquadronNameText.Text = theEvent.name; ((MainWindow)Application.Current.MainWindow).squadronRankDropDown.SelectedItem = rank.localizedName; } }); // Update the commander object, if it exists if (Cmdr != null) { Cmdr.squadronname = theEvent.name; Cmdr.squadronrank = rank; } return true; } private bool eventEnteredCQC(EnteredCQCEvent theEvent) { // In CQC we don't want to report anything, so set our CQC flag inCQC = true; return true; } private bool eventSRVLaunched(SRVLaunchedEvent theEvent) { // SRV is always player-controlled, so we are in the SRV Vehicle = Constants.VEHICLE_SRV; return true; } private bool eventSRVDocked(SRVDockedEvent theEvent) { // We are back in the ship Vehicle = Constants.VEHICLE_SHIP; return true; } private bool eventFighterLaunched(FighterLaunchedEvent theEvent) { if (theEvent.playercontrolled) { // We are in the fighter Vehicle = Constants.VEHICLE_FIGHTER; } else { // We are (still) in the ship Vehicle = Constants.VEHICLE_SHIP; } return true; } private bool eventFighterDocked(FighterDockedEvent theEvent) { // We are back in the ship Vehicle = Constants.VEHICLE_SHIP; return true; } private bool eventVehicleDestroyed(VehicleDestroyedEvent theEvent) { // We are back in the ship Vehicle = Constants.VEHICLE_SHIP; return true; } private bool eventNearSurface(NearSurfaceEvent theEvent) { // We won't update CurrentStation with this event, as doing so triggers false / premature updates from the Frontier API CurrentStation = null; if (theEvent.approaching_surface) { // Update the body Body body = CurrentStarSystem?.bodies?.Find(s => s.bodyname == theEvent.bodyname); if (body == null) { // This body is unknown to us, might not be in our data source or we might not have connectivity. Use a placeholder body = new Body { bodyname = theEvent.bodyname, systemname = theEvent.systemname }; } // System address may not be included in our data source, so we add it here. body.systemAddress = theEvent.systemAddress; CurrentStellarBody = body; } else { // Clear the body we are leaving CurrentStellarBody = null; } updateCurrentSystem(theEvent.systemname); return true; } private bool eventStarScanned(StarScannedEvent theEvent) { // We just scanned a star. We can only proceed if we know our current star system updateCurrentSystem(theEvent.star?.systemname); if (CurrentStarSystem == null) { return false; } Body star = CurrentStarSystem?.bodies?.Find(s => s.bodyname == theEvent.bodyname); if (star?.scanned is null) { CurrentStarSystem.AddOrUpdateBody(theEvent.star); StarSystemSqLiteRepository.Instance.SaveStarSystem(CurrentStarSystem); return true; } return false; } private bool eventBodyScanned(BodyScannedEvent theEvent) { // We just scanned a body. We can only proceed if we know our current star system updateCurrentSystem(theEvent.body?.systemname); if (CurrentStarSystem == null) { return false; } // Add this body if it hasn't been previously added to our database, but don't // replace prior data which isn't re-obtainable from this event. // (e.g. alreadydiscovered, scanned, alreadymapped, mapped, mappedEfficiently, etc.) Body body = CurrentStarSystem?.bodies?.Find(s => s.bodyname == theEvent.bodyname); if (body?.scanned is null) { CurrentStarSystem.AddOrUpdateBody(theEvent.body); Logging.Debug("Saving data for scanned body " + theEvent.bodyname); StarSystemSqLiteRepository.Instance.SaveStarSystem(CurrentStarSystem); return true; } return false; } private bool eventBodyMapped(BodyMappedEvent theEvent) { if (CurrentStarSystem != null && theEvent.systemAddress == CurrentStarSystem?.systemAddress) { // We've already updated the body (via the journal monitor) if the CurrentStarSystem isn't null // Here, we just need to save the data and update our current stellar body StarSystemSqLiteRepository.Instance.SaveStarSystem(CurrentStarSystem); updateCurrentStellarBody(theEvent.bodyName, CurrentStarSystem?.systemname, CurrentStarSystem?.systemAddress); } return true; } private bool eventRingMapped(RingMappedEvent theEvent) { if (CurrentStarSystem != null && theEvent.systemAddress == CurrentStarSystem?.systemAddress) { updateCurrentStellarBody(theEvent.ringname, CurrentStarSystem?.systemname, CurrentStarSystem?.systemAddress); } return true; } /// <summary>Obtain information from the companion API and use it to refresh our own data</summary> public bool refreshProfile(bool refreshStation = false) { bool success = true; if (CompanionAppService.Instance?.CurrentState == CompanionAppService.State.Authorized) { try { // Save a timestamp when the API refreshes, so that we can compare whether events are more or less recent ApiTimeStamp = DateTime.UtcNow; Profile profile = CompanionAppService.Instance.Profile(); if (profile != null) { // Update our commander object Cmdr = Commander.FromFrontierApiCmdr(Cmdr, profile.Cmdr, ApiTimeStamp, JournalTimeStamp, out bool cmdrMatches); // Stop if the commander returned from the profile does not match our expected commander name if (!cmdrMatches) { return false; } bool updatedCurrentStarSystem = false; // Only set the current star system if it is not present, otherwise we leave it to events if (CurrentStarSystem == null) { CurrentStarSystem = profile?.CurrentStarSystem; setSystemDistanceFromHome(CurrentStarSystem); setSystemDistanceFromDestination(CurrentStarSystem); setCommanderTitle(); if (profile.docked && profile.CurrentStarSystem?.systemname == CurrentStarSystem.systemname && CurrentStarSystem.stations != null) { CurrentStation = CurrentStarSystem.stations.FirstOrDefault(s => s.name == profile.LastStation.name); if (CurrentStation != null) { // Only set the current station if it is not present, otherwise we leave it to events Logging.Debug("Set current station to " + CurrentStation.name); CurrentStation.updatedat = Dates.fromDateTimeToSeconds(DateTime.UtcNow); updatedCurrentStarSystem = true; } } } if (refreshStation && CurrentStation != null && Environment == Constants.ENVIRONMENT_DOCKED) { // Refresh station data profileUpdateNeeded = true; profileStationRequired = CurrentStation.name; Thread updateThread = new Thread(() => conditionallyRefreshProfile()) { IsBackground = true }; updateThread.Start(); } if (updatedCurrentStarSystem) { Logging.Debug("Star system information updated from remote server; updating local copy"); StarSystemSqLiteRepository.Instance.SaveStarSystem(CurrentStarSystem); } foreach (EDDIMonitor monitor in activeMonitors) { try { Thread monitorThread = new Thread(() => { try { monitor.HandleProfile(profile.json); } catch (Exception ex) { Logging.Warn("Monitor failed", ex); } }) { Name = monitor.MonitorName(), IsBackground = true }; monitorThread.Start(); } catch (ThreadAbortException tax) { Thread.ResetAbort(); Logging.Debug("Thread aborted", tax); success = false; } catch (Exception ex) { Dictionary<string, object> data = new Dictionary<string, object> { { "message", ex.Message }, { "stacktrace", ex.StackTrace }, { "profile", JsonConvert.SerializeObject(profile) } }; Logging.Error("Monitor " + monitor.MonitorName() + " failed to handle profile.", data); success = false; } } } } catch (Exception ex) { Logging.Error("Exception obtaining profile", ex); success = false; } } return success; } private void setSystemDistanceFromHome(StarSystem system) { system.distancefromhome = getSystemDistance(system, HomeStarSystem); Logging.Debug("Distance from home is " + system.distancefromhome); } public void setSystemDistanceFromDestination(StarSystem system) { DestinationDistanceLy = getSystemDistance(system, DestinationStarSystem); Logging.Debug("Distance from destination system is " + DestinationDistanceLy); } public decimal getSystemDistance(StarSystem curr, StarSystem dest) { double square(double x) => x * x; decimal distance = 0; if (curr?.x != null && dest?.x != null) { distance = (decimal)Math.Round(Math.Sqrt(square((double)(curr.x - dest.x)) + square((double)(curr.y - dest.y)) + square((double)(curr.z - dest.z))), 2); } return distance; } /// <summary>Work out the title for the commander in the current system</summary> private const int minEmpireRankForTitle = 3; private const int minFederationRankForTitle = 1; private void setCommanderTitle() { if (Cmdr != null) { Cmdr.title = Properties.EddiResources.Commander; if (CurrentStarSystem != null) { if (CurrentStarSystem.Faction?.Allegiance?.invariantName == "Federation" && Cmdr.federationrating != null && Cmdr.federationrating.rank > minFederationRankForTitle) { Cmdr.title = Cmdr.federationrating.localizedName; } else if (CurrentStarSystem.Faction?.Allegiance?.invariantName == "Empire" && Cmdr.empirerating != null && Cmdr.empirerating.rank > minEmpireRankForTitle) { Cmdr.title = Cmdr.empirerating.maleRank.localizedName; } } } } /// <summary> /// Find all monitors /// </summary> public List<EDDIMonitor> findMonitors() { DirectoryInfo dir = new DirectoryInfo(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); List<EDDIMonitor> monitors = new List<EDDIMonitor>(); Type pluginType = typeof(EDDIMonitor); foreach (FileInfo file in dir.GetFiles("*Monitor.dll", SearchOption.AllDirectories)) { Logging.Debug("Checking potential plugin at " + file.FullName); try { Assembly assembly = Assembly.LoadFrom(file.FullName); foreach (Type type in assembly.GetTypes()) { if (type.IsInterface || type.IsAbstract) { continue; } else { if (type.GetInterface(pluginType.FullName) != null) { Logging.Debug("Instantiating monitor plugin at " + file.FullName); EDDIMonitor monitor = type.InvokeMember(null, BindingFlags.CreateInstance, null, null, null) as EDDIMonitor; monitors.Add(monitor); } } } } catch (BadImageFormatException) { // Ignore this; probably due to CPU architecture mismatch } catch (ReflectionTypeLoadException ex) { StringBuilder sb = new StringBuilder(); foreach (Exception exSub in ex.LoaderExceptions) { sb.AppendLine(exSub.Message); if (exSub is FileNotFoundException exFileNotFound) { if (!string.IsNullOrEmpty(exFileNotFound.FusionLog)) { sb.AppendLine("Fusion Log:"); sb.AppendLine(exFileNotFound.FusionLog); } } sb.AppendLine(); } Logging.Warn("Failed to instantiate plugin at " + file.FullName + ":\n" + sb.ToString()); } catch (FileLoadException flex) { string msg = string.Format(Properties.EddiResources.problem_load_monitor_file, dir.FullName); Logging.Error(msg, flex); SpeechService.Instance.Say(null, msg, 0); } catch (Exception ex) { string msg = string.Format(Properties.EddiResources.problem_load_monitor, $"{file.Name}.\n{ex.Message} {ex.InnerException?.Message ?? ""}"); Logging.Error(msg, ex); SpeechService.Instance.Say(null, msg, 0); } } return monitors; } /// <summary> /// Find all responders /// </summary> public List<EDDIResponder> findResponders() { DirectoryInfo dir = new DirectoryInfo(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); List<EDDIResponder> responders = new List<EDDIResponder>(); Type pluginType = typeof(EDDIResponder); foreach (FileInfo file in dir.GetFiles("*Responder.dll", SearchOption.AllDirectories)) { Logging.Debug("Checking potential plugin at " + file.FullName); try { Assembly assembly = Assembly.LoadFrom(file.FullName); foreach (Type type in assembly.GetTypes()) { if (type.IsInterface || type.IsAbstract) { continue; } else { if (type.GetInterface(pluginType.FullName) != null) { Logging.Debug("Instantiating responder plugin at " + file.FullName); EDDIResponder responder = type.InvokeMember(null, BindingFlags.CreateInstance, null, null, null) as EDDIResponder; responders.Add(responder); } } } } catch (BadImageFormatException) { // Ignore this; probably due to CPU architecure mismatch } catch (ReflectionTypeLoadException ex) { StringBuilder sb = new StringBuilder(); foreach (Exception exSub in ex.LoaderExceptions) { sb.AppendLine(exSub.Message); if (exSub is FileNotFoundException exFileNotFound) { if (!string.IsNullOrEmpty(exFileNotFound.FusionLog)) { sb.AppendLine("Fusion Log:"); sb.AppendLine(exFileNotFound.FusionLog); } } sb.AppendLine(); } Logging.Warn("Failed to instantiate plugin at " + file.FullName + ":\n" + sb.ToString()); } } return responders; } private bool profileUpdateNeeded = false; private string profileStationRequired = null; /// <summary> /// Update the profile when requested, ensuring that we meet the condition in the updated profile /// </summary> private void conditionallyRefreshProfile() { int maxTries = 6; while (running && maxTries > 0 && CompanionAppService.Instance.CurrentState == CompanionAppService.State.Authorized) { try { Logging.Debug("Starting conditional profile fetch"); // See if we need to fetch the profile if (profileUpdateNeeded) { // See if we still need this particular update if (profileStationRequired != null && (CurrentStation?.name != profileStationRequired)) { Logging.Debug("No longer at requested station; giving up on update"); profileUpdateNeeded = false; profileStationRequired = null; break; } // Make sure we know where we are if (CurrentStarSystem.systemname.Length < 0) { break; } // We do need to fetch an updated profile; do so Profile profile = CompanionAppService.Instance?.Profile(); if (profile != null) { // If we're docked, the lastStation information is located within the lastSystem identified by the profile if (profile.docked && Environment == Constants.ENVIRONMENT_DOCKED) { ApiTimeStamp = DateTime.UtcNow; long profileTime = Dates.fromDateTimeToSeconds(DateTime.UtcNow); Logging.Debug("Fetching station profile"); Profile stationProfile = CompanionAppService.Instance.Station(CurrentStarSystem.systemname); // Post an update event Event @event = new MarketInformationUpdatedEvent(DateTime.UtcNow, inHorizons, stationProfile.CurrentStarSystem.systemname, stationProfile.LastStation.name, stationProfile.LastStation.marketId, stationProfile.LastStation.commodities, stationProfile.LastStation.prohibited, stationProfile.LastStation.outfitting, stationProfile.LastStation.shipyard); enqueueEvent(@event); // See if we need to update our current station Logging.Debug("profileStationRequired is " + profileStationRequired + ", profile station is " + stationProfile.LastStation.name); if (profileStationRequired != null && profileStationRequired == stationProfile.LastStation.name) { // We have the required station information Logging.Debug("Current station matches profile information; updating info"); CurrentStation.commodities = stationProfile.LastStation.commodities; CurrentStation.economyShares = stationProfile.LastStation.economyShares; CurrentStation.prohibited = stationProfile.LastStation.prohibited; CurrentStation.commoditiesupdatedat = profileTime; CurrentStation.outfitting = stationProfile.LastStation.outfitting; CurrentStation.shipyard = stationProfile.LastStation.shipyard; CurrentStation.updatedat = profileTime; // Update the current station information in our backend DB Logging.Debug("Star system information updated from remote server; updating local copy"); StarSystemSqLiteRepository.Instance.SaveStarSystem(CurrentStarSystem); profileUpdateNeeded = false; allowMarketUpdate = false; allowOutfittingUpdate = false; allowShipyardUpdate = false; break; } } } // No luck; sleep and try again Thread.Sleep(15000); } } catch (Exception ex) { Logging.Error("Exception obtaining profile", ex); } finally { maxTries--; } } if (maxTries == 0) { Logging.Info("Maximum attempts reached; giving up on request"); } // Clear the update info profileUpdateNeeded = false; profileStationRequired = null; } internal static class NativeMethods { // Required to restart app after upgrade [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal static extern uint RegisterApplicationRestart(string pwzCommandLine, RestartFlags dwFlags); } // Flags for upgrade [Flags] internal enum RestartFlags { NONE = 0, RESTART_CYCLICAL = 1, RESTART_NOTIFY_SOLUTION = 2, RESTART_NOTIFY_FAULT = 4, RESTART_NO_CRASH = 8, RESTART_NO_HANG = 16, RESTART_NO_PATCH = 32, RESTART_NO_REBOOT = 64 } public void updateDestinationSystemStation(EDDIConfiguration configuration) { updateDestinationSystem(configuration.DestinationSystem); updateDestinationStation(configuration.DestinationStation); } public void updateDestinationSystem(string destinationSystem) { EDDIConfiguration configuration = EDDIConfiguration.FromFile(); if (destinationSystem != null) { StarSystem system = StarSystemSqLiteRepository.Instance.GetOrFetchStarSystem(destinationSystem); //Ignore null & empty systems if (system != null) { if (system.systemname != DestinationStarSystem?.systemname) { Logging.Debug("Destination star system is " + system.systemname); DestinationStarSystem = system; } } else { destinationSystem = null; } } else { DestinationStarSystem = null; } configuration.DestinationSystem = destinationSystem; configuration.ToFile(); } public void updateDestinationStation(string destinationStation) { EDDIConfiguration configuration = EDDIConfiguration.FromFile(); if (destinationStation != null && DestinationStarSystem?.stations != null) { string destinationStationName = destinationStation.Trim(); Station station = DestinationStarSystem.stations.FirstOrDefault(s => s.name == destinationStationName); if (station != null) { if (station.name != DestinationStation?.name) { Logging.Debug("Destination station is " + station.name); DestinationStation = station; } } } else { DestinationStation = null; } configuration.DestinationStation = destinationStation; configuration.ToFile(); } public void updateHomeSystemStation(EDDIConfiguration configuration) { updateHomeSystem(configuration); updateHomeStation(configuration); configuration.ToFile(); } public EDDIConfiguration updateHomeSystem(EDDIConfiguration configuration) { Logging.Verbose = configuration.Debug; if (configuration.HomeSystem != null) { StarSystem system = StarSystemSqLiteRepository.Instance.GetOrFetchStarSystem(configuration.HomeSystem); //Ignore null & empty systems if (system != null && system.bodies?.Count > 0) { if (system.systemname != HomeStarSystem?.systemname) { HomeStarSystem = system; Logging.Debug("Home star system is " + HomeStarSystem.systemname); configuration.HomeSystem = system.systemname; } } } else { HomeStarSystem = null; } return configuration; } public EDDIConfiguration updateHomeStation(EDDIConfiguration configuration) { Logging.Verbose = configuration.Debug; if (HomeStarSystem?.stations != null && configuration.HomeStation != null) { string homeStationName = configuration.HomeStation.Trim(); foreach (Station station in HomeStarSystem.stations) { if (station.name == homeStationName) { HomeStation = station; Logging.Debug("Home station is " + HomeStation.name); break; } } } return configuration; } public EDDIConfiguration updateSquadronSystem(EDDIConfiguration configuration) { Logging.Verbose = configuration.Debug; if (configuration.SquadronSystem != null) { StarSystem system = StarSystemSqLiteRepository.Instance.GetOrFetchStarSystem(configuration.SquadronSystem.Trim()); //Ignore null & empty systems if (system != null && system?.bodies.Count > 0) { if (system.systemname != SquadronStarSystem?.systemname) { SquadronStarSystem = system; if (SquadronStarSystem?.factions != null) { Logging.Debug("Squadron star system is " + SquadronStarSystem.systemname); configuration.SquadronSystem = system.systemname; } } } } else { SquadronStarSystem = null; } return configuration; } public void updateSquadronData(Faction faction, string systemName) { if (faction != null) { EDDIConfiguration configuration = EDDIConfiguration.FromFile(); //Update the squadron faction, if changed if (configuration.SquadronFaction == null || configuration.SquadronFaction != faction.name) { configuration.SquadronFaction = faction.name; Application.Current?.Dispatcher?.Invoke(() => { if (Application.Current?.MainWindow != null) { ((MainWindow)Application.Current.MainWindow).squadronFactionDropDown.SelectedItem = faction.name; } }); Cmdr.squadronfaction = faction.name; } // Update system, allegiance, & power when in squadron home system if ((bool)faction.presences.FirstOrDefault(p => p.systemName == systemName)?.squadronhomesystem) { // Update the squadron system data, if changed string system = CurrentStarSystem.systemname; if (configuration.SquadronSystem == null || configuration.SquadronSystem != system) { configuration.SquadronSystem = system; var configurationCopy = configuration; Application.Current?.Dispatcher?.Invoke(() => { if (Application.Current?.MainWindow != null) { ((MainWindow)Application.Current.MainWindow).squadronSystemDropDown.Text = system; ((MainWindow)Application.Current.MainWindow).ConfigureSquadronFactionOptions(configurationCopy); } }); configuration = updateSquadronSystem(configuration); } //Update the squadron allegiance, if changed Superpower allegiance = CurrentStarSystem?.Faction?.Allegiance ?? Superpower.None; //Prioritize UI entry if squadron system allegiance not specified if (allegiance != Superpower.None) { if (configuration.SquadronAllegiance == Superpower.None || configuration.SquadronAllegiance != allegiance) { configuration.SquadronAllegiance = allegiance; Cmdr.squadronallegiance = allegiance; } } // Update the squadron power, if changed Power power = Power.FromName(CurrentStarSystem?.power) ?? Power.None; //Prioritize UI entry if squadron system power not specified if (power != Power.None) { if (configuration.SquadronPower == Power.None && configuration.SquadronPower != power) { configuration.SquadronPower = power; Application.Current?.Dispatcher?.Invoke(() => { if (Application.Current?.MainWindow != null) { ((MainWindow)Application.Current.MainWindow).squadronPowerDropDown.SelectedItem = power.localizedName; ((MainWindow)Application.Current.MainWindow).ConfigureSquadronPowerOptions(configuration); } }); } } } configuration.ToFile(); } } } }
41.999298
380
0.493755
[ "Apache-2.0" ]
danielRicardo/EDDI
EDDI/EDDI.cs
119,616
C#
using ElmSharp; using Microsoft.Maui.Controls.Platform; using ESize = ElmSharp.Size; namespace Microsoft.Maui.Controls.Compatibility.Platform.Tizen { public class NativeViewWrapperRenderer : ViewRenderer<NativeViewWrapper, EvasObject> { protected override void OnElementChanged(ElementChangedEventArgs<NativeViewWrapper> e) { if (Control == null) SetNativeControl(Element.EvasObject); base.OnElementChanged(e); } protected override ESize Measure(int availableWidth, int availableHeight) { if (Element?.MeasureDelegate == null) { return base.Measure(availableWidth, availableHeight); } // The user has specified a different implementation of MeasureDelegate ESize? result = Element.MeasureDelegate(this, availableWidth, availableHeight); // If the delegate returns a ElmSharp.Size, we use it; if it returns null, // fall back to the default implementation return result ?? base.Measure(availableWidth, availableHeight); } } }
29.787879
88
0.76297
[ "MIT" ]
JoonghyunCho/TestBed
src/Compatibility/Core/src/Tizen/Renderers/NativeViewWrapperRenderer.cs
983
C#
using System; using System.IO; using Assets.SiliconSocial; using FF9; using Memoria; using Memoria.Assets; using Memoria.Data; using Memoria.Prime; using Memoria.Prime.CSV; // ReSharper disable FieldCanBeMadeReadOnly.Global // ReSharper disable UnusedMember.Global // ReSharper disable InconsistentNaming // ReSharper disable InconsistentNaming // ReSharper disable ClassNeverInstantiated.Global // ReSharper disable RedundantExplicitArraySize public class ff9item { //public const ushort FF9ITEM_EQUIP_ZIDAN = 2048; //public const ushort FF9ITEM_EQUIP_VIVI = 1024; //public const ushort FF9ITEM_EQUIP_GARNET = 512; //public const ushort FF9ITEM_EQUIP_STEINER = 256; //public const ushort FF9ITEM_EQUIP_FREIJA = 128; //public const ushort FF9ITEM_EQUIP_KUINA = 64; //public const ushort FF9ITEM_EQUIP_EIKO = 32; //public const ushort FF9ITEM_EQUIP_SALAMANDER = 16; //public const ushort FF9ITEM_EQUIP_CINA = 8; //public const ushort FF9ITEM_EQUIP_MARCUS = 4; //public const ushort FF9ITEM_EQUIP_BLANK = 2; //public const ushort FF9ITEM_EQUIP_BEATRIX = 1; //public const byte FF9ITEM_TYPE_FIELD = 1; //public const byte FF9ITEM_TYPE_GIL = 2; //public const byte FF9ITEM_TYPE_POTION = 4; //public const byte FF9ITEM_TYPE_ACCESSORY = 8; //public const byte FF9ITEM_TYPE_BODY = 16; //public const byte FF9ITEM_TYPE_HEAD = 32; //public const byte FF9ITEM_TYPE_WRIST = 64; //public const byte FF9ITEM_TYPE_WEAPON = 128; //public const byte FF9ITEM_TYPE_EQUIP = 248; //public const int FF9ITEM_MAX = 256; //public const int FF9ITEM_COUNT_MAX = 99; //public const int FF9ITEM_RARE_MAX = 256; //public const int FF9ITEM_RARE_SIZE = 64; //public const int FF9ITEM_RARE_BIT = 2; //public const int FF9ITEM_ABILITY_MAX = 3; //public const int FF9ITEM_NONE = 255; //public const int FF9ITEM_INFO_START = 224; //public const int FF9ITEM_NAME_SIZE = 2048; //public const int FF9ITEM_HELP_SIZE = 10240; //public const int FF9ITEM_IMP_NAME_SIZE = 3072; public static FF9ITEM_DATA[] _FF9Item_Data; public static ITEM_DATA[] _FF9Item_Info; static ff9item() { _FF9Item_Data = LoadItems(); _FF9Item_Info = LoadItemEffects(); } private static FF9ITEM_DATA[] LoadItems() { try { ItemInfo[] items; String inputPath = DataResources.Items.Directory + DataResources.Items.ItemsFile; String[] dir = Configuration.Mod.AllFolderNames; for (Int32 i = 0; i < dir.Length; i++) { inputPath = DataResources.Items.ModDirectory(dir[i]) + DataResources.Items.ItemsFile; if (File.Exists(inputPath)) { items = CsvReader.Read<ItemInfo>(inputPath); if (items.Length != 256) throw new NotSupportedException($"You must set 256 items, but there {items.Length}. Any number of items will be available after a game stabilization."); // TODO FF9ITEM_DATA[] result = new FF9ITEM_DATA[items.Length]; for (Int32 j = 0; j < result.Length; j++) result[j] = items[j].ToItemData(); return result; } } throw new FileNotFoundException($"[ff9item] Cannot load items because a file does not exist: [{inputPath}].", inputPath); } catch (Exception ex) { Log.Error(ex, "[ff9item] Load items failed."); UIManager.Input.ConfirmQuit(); return null; } } private static ITEM_DATA[] LoadItemEffects() { try { ItemEffect[] effects; String inputPath = DataResources.Items.Directory + DataResources.Items.ItemEffectsFile; String[] dir = Configuration.Mod.AllFolderNames; for (Int32 i = 0; i < dir.Length; i++) { inputPath = DataResources.Items.ModDirectory(dir[i]) + DataResources.Items.ItemEffectsFile; if (File.Exists(inputPath)) { effects = CsvReader.Read<ItemEffect>(inputPath); if (effects.Length != 32) throw new NotSupportedException($"You must set 32 actions, but there {effects.Length}. Any number of actions will be available after a game stabilization."); // TODO ITEM_DATA[] result = new ITEM_DATA[effects.Length]; for (Int32 j = 0; j < result.Length; j++) result[j] = effects[j].ToItemData(); return result; } } throw new FileNotFoundException($"[ff9item] Cannot load item actions because a file does not exist: [{inputPath}].", inputPath); } catch (Exception ex) { Log.Error(ex, "[ff9item] Load item effects failed."); UIManager.Input.ConfirmQuit(); return null; } } public static void FF9Item_Init() { // TODO: initial items; they can be changed by modifying Prima Vista's script but it could be useful to be able to set them with Memoria as well (DictionaryPatch or CSV?) FF9ITEM[] ff9ItemArray = new FF9ITEM[8] { new FF9ITEM(236, 7), new FF9ITEM(237, 2), new FF9ITEM(238, 2), new FF9ITEM(240, 2), new FF9ITEM(247, 2), new FF9ITEM(249, 1), new FF9ITEM(253, 1), new FF9ITEM(Byte.MaxValue, 0) }; FF9Item_InitNormal(); FF9Item_InitImportant(); for (Int32 index = 0; ff9ItemArray[index].id != Byte.MaxValue; ++index) { FF9ITEM ff9Item = ff9ItemArray[index]; FF9Item_Add(ff9Item.id, ff9Item.count); } } public static void FF9Item_InitNormal() { for (Int32 index = 0; index < 256; ++index) FF9StateSystem.Common.FF9.item[index] = new FF9ITEM(0, 0); } public static void FF9Item_InitImportant() { for (Int32 index = 0; index < 64; ++index) FF9StateSystem.Common.FF9.rare_item[index] = 0; } public static FF9ITEM FF9Item_GetPtr(Int32 id) { FF9ITEM[] ff9ItemArray = FF9StateSystem.Common.FF9.item; for (Int32 index = 0; index < 256; ++index) { FF9ITEM ff9Item = ff9ItemArray[index]; if (ff9Item.count != 0 && ff9Item.id == id) return ff9Item; } return null; } public static Int32 FF9Item_GetCount(Int32 id) { FF9ITEM ptr = FF9Item_GetPtr(id); if (ptr == null) return 0; return ptr.count; } public static Int32 FF9Item_Add(Int32 id, Int32 count) { FF9StateGlobal ff9StateGlobal = FF9StateSystem.Common.FF9; if (id == Byte.MaxValue) return 0; Int32 index1 = 0; FF9ITEM[] ff9ItemArray1 = ff9StateGlobal.item; for (; index1 < 256; ++index1) { FF9ITEM ff9Item = ff9ItemArray1[index1]; if (ff9Item.count != 0 && ff9Item.id == id) { if (ff9Item.count + count > 99) count = 99 - ff9Item.count; ff9Item.count += (Byte)count; FF9Item_Achievement(ff9Item.id, ff9Item.count); return count; } } Int32 index2 = 0; FF9ITEM[] ff9ItemArray2 = ff9StateGlobal.item; for (; index2 < 256; ++index2) { FF9ITEM ff9Item = ff9ItemArray2[index2]; if (ff9Item.count == 0) { ff9Item.id = (Byte)id; ff9Item.count = (Byte)count; FF9Item_Achievement(ff9Item.id, ff9Item.count); return count; } } return 0; } public static Int32 FF9Item_Remove(Int32 id, Int32 count) { FF9ITEM[] ff9ItemArray = FF9StateSystem.Common.FF9.item; for (Int32 index = 0; index < 256; ++index) { FF9ITEM ff9Item = ff9ItemArray[index]; if (ff9Item.count != 0 && ff9Item.id == id) { if (ff9Item.count < count) count = ff9Item.count; ff9Item.count -= (Byte)count; return count; } } return 0; } public static Int32 FF9Item_GetEquipPart(Int32 id) { FF9ITEM_DATA ff9ItemData = _FF9Item_Data[id]; Byte[] numArray = new Byte[5] { 128, 32, 64, 16, 8 }; for (Int32 index = 0; index < 5; ++index) { if ((ff9ItemData.type & numArray[index]) != 0) return index; } return -1; } public static Int32 FF9Item_GetEquipCount(Int32 id) { Int32 num = 0; for (Int32 index1 = 0; index1 < 9; ++index1) { if (FF9StateSystem.Common.FF9.player[index1].info.party != 0) { for (Int32 index2 = 0; index2 < 5; ++index2) { if (id == FF9StateSystem.Common.FF9.player[index1].equip[index2]) ++num; } } } return num; } public static void FF9Item_AddImportant(Int32 id) { FF9StateSystem.Common.FF9.rare_item[id >> 2] |= (Byte)(1 << (((Byte)id & 3) << 1)); FF9StateSystem.Common.FF9.rare_item[id >> 2] &= (Byte)~(1 << (((Byte)id & 3) << 1) + 1); } public static void FF9Item_RemoveImportant(Int32 id) { FF9StateSystem.Common.FF9.rare_item[id >> 2] &= (Byte)~(1 << (((Byte)id & 3) << 1)); FF9StateSystem.Common.FF9.rare_item[id >> 2] &= (Byte)~(1 << (((Byte)id & 3) << 1) + 1); } public static void FF9Item_UseImportant(Int32 id) { FF9StateSystem.Common.FF9.rare_item[id >> 2] |= (Byte)(1 << (((Byte)id & 3) << 1) + 1); } public static void FF9Item_UnuseImportant(Int32 id) { FF9StateSystem.Common.FF9.rare_item[id >> 2] &= (Byte)~(1 << (((Byte)id & 3) << 1) + 1); } public static Boolean FF9Item_IsExistImportant(Int32 id) { return (FF9StateSystem.Common.FF9.rare_item[(Byte)id >> 2] & (Byte)(1 << (((Byte)id & 3) << 1))) != 0; } public static Boolean FF9Item_IsUsedImportant(Int32 id) { return (FF9StateSystem.Common.FF9.rare_item[(Byte)id >> 2] & (Byte)(1 << (((Byte)id & 3) << 1) + 1)) != 0; } private static void FF9Item_Achievement(Int32 id, Int32 count) { Int32 num = id; switch (num) { case 28: AchievementManager.ReportAchievement(AcheivementKey.Excalibur, count); break; case 30: AchievementManager.ReportAchievement(AcheivementKey.ExcaliburII, count); break; default: if (num == 14) { AchievementManager.ReportAchievement(AcheivementKey.TheTower, count); break; } if (num == 15) { AchievementManager.ReportAchievement(AcheivementKey.UltimaWeapon, count); break; } if (num == 0) { AchievementManager.ReportAchievement(AcheivementKey.Hammer, count); break; } if (num == 39) { AchievementManager.ReportAchievement(AcheivementKey.KainLance, count); break; } if (num == 50) { AchievementManager.ReportAchievement(AcheivementKey.RuneClaws, count); break; } if (num == 56) { AchievementManager.ReportAchievement(AcheivementKey.TigerHands, count); break; } if (num == 63) { AchievementManager.ReportAchievement(AcheivementKey.WhaleWhisker, count); break; } if (num == 69) { AchievementManager.ReportAchievement(AcheivementKey.AngelFlute, count); break; } if (num == 78) { AchievementManager.ReportAchievement(AcheivementKey.MaceOfZeus, count); break; } if (num == 84) { AchievementManager.ReportAchievement(AcheivementKey.GastroFork, count); break; } if (num == 109 || num == 146 || num == 189) { if (FF9Item_GetCount(109) <= 0 && FF9Item_GetEquipCount(109) <= 0 || FF9Item_GetCount(146) <= 0 && FF9Item_GetEquipCount(146) <= 0 || FF9Item_GetCount(189) <= 0 && FF9Item_GetEquipCount(189) <= 0) break; count = FF9Item_GetCount(109) + FF9Item_GetEquipCount(109) + FF9Item_GetCount(146) + FF9Item_GetEquipCount(146) + FF9Item_GetCount(189) + FF9Item_GetEquipCount(189); AchievementManager.ReportAchievement(AcheivementKey.GenjiSet, count); break; } if (num != 229) break; AchievementManager.ReportAchievement(AcheivementKey.Moonstone4, IncreaseMoonStoneCount()); break; } } public static Int32 IncreaseMoonStoneCount() { Int32 num = FF9StateSystem.Achievement.EvtReservedArray[0] + 1; FF9StateSystem.Achievement.EvtReservedArray[0] = num; return num; } public static Int32 DecreaseMoonStoneCount() { Int32 num = FF9StateSystem.Achievement.EvtReservedArray[0] - 1; FF9StateSystem.Achievement.EvtReservedArray[0] = num; return num; } }
36.48072
216
0.547107
[ "MIT" ]
FlameHorizon/Memoria
Assembly-CSharp/Memoria/Data/ff9item.2.cs
14,193
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SandCollision : MonoBehaviour { [SerializeField] private GameObject rastaPlanet; private ParticleSystem[] particles; // Use this for initialization void Awake () { particles = transform.GetComponentsInChildren<ParticleSystem>(); if (rastaPlanet == null) { rastaPlanet = GameObject.Find("Rasta"); } } void Update () { float currentDistance = Vector3.Distance(transform.position, rastaPlanet.transform.position); if (currentDistance < (rastaPlanet.transform.localScale.x / 2) + (transform.localScale.x / 2)) { foreach( ParticleSystem p in particles) { p.Emit(1); Vector3 gravityUp = (rastaPlanet.transform.position - transform.position).normalized; // Rotation en fonction du centre de la planète Quaternion wantedRotation = Quaternion.FromToRotation(transform.up, gravityUp) * transform.rotation; //then rotate p.transform.rotation = wantedRotation; } } } }
25.146341
104
0.722599
[ "MIT" ]
Khamsou/horsjeu-planets
planets/Assets/Scripts/SandCollision.cs
1,034
C#
using System.Text.Json.Serialization; using Essensoft.AspNetCore.Payment.Alipay.Domain; namespace Essensoft.AspNetCore.Payment.Alipay.Response { /// <summary> /// ZolozAuthenticationCustomerFaceabilityIdentifyResponse. /// </summary> public class ZolozAuthenticationCustomerFaceabilityIdentifyResponse : AlipayResponse { /// <summary> /// 能力接口返回值 /// </summary> [JsonPropertyName("biz_info")] public FaceAbilityExtInfo BizInfo { get; set; } } }
28.388889
88
0.690802
[ "MIT" ]
LuohuaRain/payment
src/Essensoft.AspNetCore.Payment.Alipay/Response/ZolozAuthenticationCustomerFaceabilityIdentifyResponse.cs
527
C#
using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Extensions.Logging; namespace Meziantou.Extensions.Logging.InMemory { public sealed class InMemoryLogCollection : IEnumerable<InMemoryLogEntry> { private readonly SingleLinkedList<InMemoryLogEntry> _items = new(); internal void Add(InMemoryLogEntry entry) { _items.AddLast(entry); } public override string ToString() { var sb = new StringBuilder(); lock (_items) { foreach (var entry in _items) { sb.Append(entry).AppendLine(); } } return sb.ToString(); } public IEnumerator<InMemoryLogEntry> GetEnumerator() => _items.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public IEnumerable<InMemoryLogEntry> Debugs => _items.Where(item => item.LogLevel == LogLevel.Debug); public IEnumerable<InMemoryLogEntry> Traces => _items.Where(item => item.LogLevel == LogLevel.Trace); public IEnumerable<InMemoryLogEntry> Informations => _items.Where(item => item.LogLevel == LogLevel.Information); public IEnumerable<InMemoryLogEntry> Warnings => _items.Where(item => item.LogLevel == LogLevel.Warning); public IEnumerable<InMemoryLogEntry> Errors => _items.Where(item => item.LogLevel == LogLevel.Error); public IEnumerable<InMemoryLogEntry> Criticals => _items.Where(item => item.LogLevel == LogLevel.Critical); } }
37
121
0.651106
[ "MIT" ]
HellRestaurant/Meziantou.Framework
src/Meziantou.Extensions.Logging.InMemory/InMemoryLogCollection.cs
1,630
C#
using Microsoft.AspNetCore.Mvc.Filters; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Text; using System.Threading.Tasks; namespace SpikeNeo4j.Tests { public class UsuarioFalsoFiltro : IAsyncActionFilter { public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { context.HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity(new List<Claim> { new Claim(ClaimTypes.Email, "example@hotmail.com"), new Claim(ClaimTypes.Name, "example@hotmail.com"), new Claim(ClaimTypes.NameIdentifier, "9722b56a-77ea-4e41-941d-e319b6eb3712"), }, "prueba")); await next(); } } }
31.923077
110
0.656627
[ "Apache-2.0" ]
neo4j-examples/supply-chain-demo
Neo4J Back/SpikeNeo4j.Tests/UsuarioFiltroFalso.cs
832
C#
using System.Collections.Generic; namespace Kelpie.DynamicEntity.Construction { interface IEntityWorkshop { void DoWork(IEnumerable<JobBag> entities); } }
17.7
50
0.723164
[ "MIT" ]
xaviermonin/EntityCore
Core/Kelpie/DynamicEntity/Construction/IEntityWorkshop.cs
179
C#
using System; using System.Collections.Generic; using System.Text; namespace Blockcore.Interfaces.UI { public interface INavigationItem { public string Name { get; } public string Navigation { get; } public string Icon { get; } public bool IsVisible {get; } public int NavOrder {get; } } }
22
41
0.625
[ "MIT" ]
x1crypto/x1-dotnetnode
src/Blockcore/Interfaces/UI/INavigationItem.cs
354
C#
namespace PVIBroker { partial class PropGrid { /// <summary> /// Требуется переменная конструктора. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Освободить все используемые ресурсы. /// </summary> /// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Код, автоматически созданный конструктором компонентов /// <summary> /// Обязательный метод для поддержки конструктора - не изменяйте /// содержимое данного метода при помощи редактора кода. /// </summary> private void InitializeComponent() { this.SuspendLayout(); // // PropGrid // this.Name = "PropGrid"; this.Size = new System.Drawing.Size(364, 191); this.ResumeLayout(false); this.ReadOnly = true; this.Rows.Clear(); this.AllowUserToAddRows = false; } #endregion } }
27.854167
109
0.536275
[ "Apache-2.0" ]
1datr/PVIBroker
PVIBroker/PropGrid.Designer.cs
1,602
C#
/* * Copyright 2010-2014 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 cognito-idp-2016-04-18.normal.json service model. */ using System; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.CognitoIdentityProvider.Model; using Amazon.CognitoIdentityProvider.Model.Internal.MarshallTransformations; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Transform; namespace Amazon.CognitoIdentityProvider { /// <summary> /// Implementation for accessing CognitoIdentityProvider /// /// Using the Amazon Cognito User Pools API, you can create a user pool to manage directories /// and users. You can authenticate a user to obtain tokens related to user identity and /// access policies. /// /// /// <para> /// This API reference provides information about user pools in Amazon Cognito User Pools. /// </para> /// /// <para> /// For more information, see the Amazon Cognito Documentation. /// </para> /// </summary> public partial class AmazonCognitoIdentityProviderClient : AmazonServiceClient, IAmazonCognitoIdentityProvider { #region Constructors #if CORECLR /// <summary> /// Constructs AmazonCognitoIdentityProviderClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> public AmazonCognitoIdentityProviderClient() : base(FallbackCredentialsFactory.GetCredentials(), new AmazonCognitoIdentityProviderConfig()) { } /// <summary> /// Constructs AmazonCognitoIdentityProviderClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="region">The region to connect.</param> public AmazonCognitoIdentityProviderClient(RegionEndpoint region) : base(FallbackCredentialsFactory.GetCredentials(), new AmazonCognitoIdentityProviderConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonCognitoIdentityProviderClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="config">The AmazonCognitoIdentityProviderClient Configuration Object</param> public AmazonCognitoIdentityProviderClient(AmazonCognitoIdentityProviderConfig config) : base(FallbackCredentialsFactory.GetCredentials(), config) { } #endif /// <summary> /// Constructs AmazonCognitoIdentityProviderClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> public AmazonCognitoIdentityProviderClient(AWSCredentials credentials) : this(credentials, new AmazonCognitoIdentityProviderConfig()) { } /// <summary> /// Constructs AmazonCognitoIdentityProviderClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="region">The region to connect.</param> public AmazonCognitoIdentityProviderClient(AWSCredentials credentials, RegionEndpoint region) : this(credentials, new AmazonCognitoIdentityProviderConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonCognitoIdentityProviderClient with AWS Credentials and an /// AmazonCognitoIdentityProviderClient Configuration object. /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="clientConfig">The AmazonCognitoIdentityProviderClient Configuration Object</param> public AmazonCognitoIdentityProviderClient(AWSCredentials credentials, AmazonCognitoIdentityProviderConfig clientConfig) : base(credentials, clientConfig) { } /// <summary> /// Constructs AmazonCognitoIdentityProviderClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> public AmazonCognitoIdentityProviderClient(string awsAccessKeyId, string awsSecretAccessKey) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonCognitoIdentityProviderConfig()) { } /// <summary> /// Constructs AmazonCognitoIdentityProviderClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="region">The region to connect.</param> public AmazonCognitoIdentityProviderClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonCognitoIdentityProviderConfig() {RegionEndpoint=region}) { } /// <summary> /// Constructs AmazonCognitoIdentityProviderClient with AWS Access Key ID, AWS Secret Key and an /// AmazonCognitoIdentityProviderClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="clientConfig">The AmazonCognitoIdentityProviderClient Configuration Object</param> public AmazonCognitoIdentityProviderClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonCognitoIdentityProviderConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, clientConfig) { } /// <summary> /// Constructs AmazonCognitoIdentityProviderClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> public AmazonCognitoIdentityProviderClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonCognitoIdentityProviderConfig()) { } /// <summary> /// Constructs AmazonCognitoIdentityProviderClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="region">The region to connect.</param> public AmazonCognitoIdentityProviderClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonCognitoIdentityProviderConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonCognitoIdentityProviderClient with AWS Access Key ID, AWS Secret Key and an /// AmazonCognitoIdentityProviderClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="clientConfig">The AmazonCognitoIdentityProviderClient Configuration Object</param> public AmazonCognitoIdentityProviderClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonCognitoIdentityProviderConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig) { } #endregion #region Overrides /// <summary> /// Creates the signer for the service. /// </summary> protected override AbstractAWSSigner CreateSigner() { return new AWS4Signer(); } #endregion #region Dispose /// <summary> /// Disposes the service client. /// </summary> protected override void Dispose(bool disposing) { base.Dispose(disposing); } #endregion #region AddCustomAttributes internal virtual AddCustomAttributesResponse AddCustomAttributes(AddCustomAttributesRequest request) { var marshaller = new AddCustomAttributesRequestMarshaller(); var unmarshaller = AddCustomAttributesResponseUnmarshaller.Instance; return Invoke<AddCustomAttributesRequest,AddCustomAttributesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the AddCustomAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AddCustomAttributes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/AddCustomAttributes">REST API Reference for AddCustomAttributes Operation</seealso> public virtual Task<AddCustomAttributesResponse> AddCustomAttributesAsync(AddCustomAttributesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AddCustomAttributesRequestMarshaller(); var unmarshaller = AddCustomAttributesResponseUnmarshaller.Instance; return InvokeAsync<AddCustomAttributesRequest,AddCustomAttributesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region AdminAddUserToGroup internal virtual AdminAddUserToGroupResponse AdminAddUserToGroup(AdminAddUserToGroupRequest request) { var marshaller = new AdminAddUserToGroupRequestMarshaller(); var unmarshaller = AdminAddUserToGroupResponseUnmarshaller.Instance; return Invoke<AdminAddUserToGroupRequest,AdminAddUserToGroupResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the AdminAddUserToGroup operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AdminAddUserToGroup operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/AdminAddUserToGroup">REST API Reference for AdminAddUserToGroup Operation</seealso> public virtual Task<AdminAddUserToGroupResponse> AdminAddUserToGroupAsync(AdminAddUserToGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AdminAddUserToGroupRequestMarshaller(); var unmarshaller = AdminAddUserToGroupResponseUnmarshaller.Instance; return InvokeAsync<AdminAddUserToGroupRequest,AdminAddUserToGroupResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region AdminConfirmSignUp internal virtual AdminConfirmSignUpResponse AdminConfirmSignUp(AdminConfirmSignUpRequest request) { var marshaller = new AdminConfirmSignUpRequestMarshaller(); var unmarshaller = AdminConfirmSignUpResponseUnmarshaller.Instance; return Invoke<AdminConfirmSignUpRequest,AdminConfirmSignUpResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the AdminConfirmSignUp operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AdminConfirmSignUp operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/AdminConfirmSignUp">REST API Reference for AdminConfirmSignUp Operation</seealso> public virtual Task<AdminConfirmSignUpResponse> AdminConfirmSignUpAsync(AdminConfirmSignUpRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AdminConfirmSignUpRequestMarshaller(); var unmarshaller = AdminConfirmSignUpResponseUnmarshaller.Instance; return InvokeAsync<AdminConfirmSignUpRequest,AdminConfirmSignUpResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region AdminCreateUser internal virtual AdminCreateUserResponse AdminCreateUser(AdminCreateUserRequest request) { var marshaller = new AdminCreateUserRequestMarshaller(); var unmarshaller = AdminCreateUserResponseUnmarshaller.Instance; return Invoke<AdminCreateUserRequest,AdminCreateUserResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the AdminCreateUser operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AdminCreateUser operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/AdminCreateUser">REST API Reference for AdminCreateUser Operation</seealso> public virtual Task<AdminCreateUserResponse> AdminCreateUserAsync(AdminCreateUserRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AdminCreateUserRequestMarshaller(); var unmarshaller = AdminCreateUserResponseUnmarshaller.Instance; return InvokeAsync<AdminCreateUserRequest,AdminCreateUserResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region AdminDeleteUser internal virtual AdminDeleteUserResponse AdminDeleteUser(AdminDeleteUserRequest request) { var marshaller = new AdminDeleteUserRequestMarshaller(); var unmarshaller = AdminDeleteUserResponseUnmarshaller.Instance; return Invoke<AdminDeleteUserRequest,AdminDeleteUserResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the AdminDeleteUser operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AdminDeleteUser operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/AdminDeleteUser">REST API Reference for AdminDeleteUser Operation</seealso> public virtual Task<AdminDeleteUserResponse> AdminDeleteUserAsync(AdminDeleteUserRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AdminDeleteUserRequestMarshaller(); var unmarshaller = AdminDeleteUserResponseUnmarshaller.Instance; return InvokeAsync<AdminDeleteUserRequest,AdminDeleteUserResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region AdminDeleteUserAttributes internal virtual AdminDeleteUserAttributesResponse AdminDeleteUserAttributes(AdminDeleteUserAttributesRequest request) { var marshaller = new AdminDeleteUserAttributesRequestMarshaller(); var unmarshaller = AdminDeleteUserAttributesResponseUnmarshaller.Instance; return Invoke<AdminDeleteUserAttributesRequest,AdminDeleteUserAttributesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the AdminDeleteUserAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AdminDeleteUserAttributes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/AdminDeleteUserAttributes">REST API Reference for AdminDeleteUserAttributes Operation</seealso> public virtual Task<AdminDeleteUserAttributesResponse> AdminDeleteUserAttributesAsync(AdminDeleteUserAttributesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AdminDeleteUserAttributesRequestMarshaller(); var unmarshaller = AdminDeleteUserAttributesResponseUnmarshaller.Instance; return InvokeAsync<AdminDeleteUserAttributesRequest,AdminDeleteUserAttributesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region AdminDisableProviderForUser internal virtual AdminDisableProviderForUserResponse AdminDisableProviderForUser(AdminDisableProviderForUserRequest request) { var marshaller = new AdminDisableProviderForUserRequestMarshaller(); var unmarshaller = AdminDisableProviderForUserResponseUnmarshaller.Instance; return Invoke<AdminDisableProviderForUserRequest,AdminDisableProviderForUserResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the AdminDisableProviderForUser operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AdminDisableProviderForUser operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/AdminDisableProviderForUser">REST API Reference for AdminDisableProviderForUser Operation</seealso> public virtual Task<AdminDisableProviderForUserResponse> AdminDisableProviderForUserAsync(AdminDisableProviderForUserRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AdminDisableProviderForUserRequestMarshaller(); var unmarshaller = AdminDisableProviderForUserResponseUnmarshaller.Instance; return InvokeAsync<AdminDisableProviderForUserRequest,AdminDisableProviderForUserResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region AdminDisableUser internal virtual AdminDisableUserResponse AdminDisableUser(AdminDisableUserRequest request) { var marshaller = new AdminDisableUserRequestMarshaller(); var unmarshaller = AdminDisableUserResponseUnmarshaller.Instance; return Invoke<AdminDisableUserRequest,AdminDisableUserResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the AdminDisableUser operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AdminDisableUser operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/AdminDisableUser">REST API Reference for AdminDisableUser Operation</seealso> public virtual Task<AdminDisableUserResponse> AdminDisableUserAsync(AdminDisableUserRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AdminDisableUserRequestMarshaller(); var unmarshaller = AdminDisableUserResponseUnmarshaller.Instance; return InvokeAsync<AdminDisableUserRequest,AdminDisableUserResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region AdminEnableUser internal virtual AdminEnableUserResponse AdminEnableUser(AdminEnableUserRequest request) { var marshaller = new AdminEnableUserRequestMarshaller(); var unmarshaller = AdminEnableUserResponseUnmarshaller.Instance; return Invoke<AdminEnableUserRequest,AdminEnableUserResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the AdminEnableUser operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AdminEnableUser operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/AdminEnableUser">REST API Reference for AdminEnableUser Operation</seealso> public virtual Task<AdminEnableUserResponse> AdminEnableUserAsync(AdminEnableUserRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AdminEnableUserRequestMarshaller(); var unmarshaller = AdminEnableUserResponseUnmarshaller.Instance; return InvokeAsync<AdminEnableUserRequest,AdminEnableUserResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region AdminForgetDevice internal virtual AdminForgetDeviceResponse AdminForgetDevice(AdminForgetDeviceRequest request) { var marshaller = new AdminForgetDeviceRequestMarshaller(); var unmarshaller = AdminForgetDeviceResponseUnmarshaller.Instance; return Invoke<AdminForgetDeviceRequest,AdminForgetDeviceResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the AdminForgetDevice operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AdminForgetDevice operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/AdminForgetDevice">REST API Reference for AdminForgetDevice Operation</seealso> public virtual Task<AdminForgetDeviceResponse> AdminForgetDeviceAsync(AdminForgetDeviceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AdminForgetDeviceRequestMarshaller(); var unmarshaller = AdminForgetDeviceResponseUnmarshaller.Instance; return InvokeAsync<AdminForgetDeviceRequest,AdminForgetDeviceResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region AdminGetDevice internal virtual AdminGetDeviceResponse AdminGetDevice(AdminGetDeviceRequest request) { var marshaller = new AdminGetDeviceRequestMarshaller(); var unmarshaller = AdminGetDeviceResponseUnmarshaller.Instance; return Invoke<AdminGetDeviceRequest,AdminGetDeviceResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the AdminGetDevice operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AdminGetDevice operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/AdminGetDevice">REST API Reference for AdminGetDevice Operation</seealso> public virtual Task<AdminGetDeviceResponse> AdminGetDeviceAsync(AdminGetDeviceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AdminGetDeviceRequestMarshaller(); var unmarshaller = AdminGetDeviceResponseUnmarshaller.Instance; return InvokeAsync<AdminGetDeviceRequest,AdminGetDeviceResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region AdminGetUser internal virtual AdminGetUserResponse AdminGetUser(AdminGetUserRequest request) { var marshaller = new AdminGetUserRequestMarshaller(); var unmarshaller = AdminGetUserResponseUnmarshaller.Instance; return Invoke<AdminGetUserRequest,AdminGetUserResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the AdminGetUser operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AdminGetUser operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/AdminGetUser">REST API Reference for AdminGetUser Operation</seealso> public virtual Task<AdminGetUserResponse> AdminGetUserAsync(AdminGetUserRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AdminGetUserRequestMarshaller(); var unmarshaller = AdminGetUserResponseUnmarshaller.Instance; return InvokeAsync<AdminGetUserRequest,AdminGetUserResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region AdminInitiateAuth internal virtual AdminInitiateAuthResponse AdminInitiateAuth(AdminInitiateAuthRequest request) { var marshaller = new AdminInitiateAuthRequestMarshaller(); var unmarshaller = AdminInitiateAuthResponseUnmarshaller.Instance; return Invoke<AdminInitiateAuthRequest,AdminInitiateAuthResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the AdminInitiateAuth operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AdminInitiateAuth operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/AdminInitiateAuth">REST API Reference for AdminInitiateAuth Operation</seealso> public virtual Task<AdminInitiateAuthResponse> AdminInitiateAuthAsync(AdminInitiateAuthRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AdminInitiateAuthRequestMarshaller(); var unmarshaller = AdminInitiateAuthResponseUnmarshaller.Instance; return InvokeAsync<AdminInitiateAuthRequest,AdminInitiateAuthResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region AdminLinkProviderForUser internal virtual AdminLinkProviderForUserResponse AdminLinkProviderForUser(AdminLinkProviderForUserRequest request) { var marshaller = new AdminLinkProviderForUserRequestMarshaller(); var unmarshaller = AdminLinkProviderForUserResponseUnmarshaller.Instance; return Invoke<AdminLinkProviderForUserRequest,AdminLinkProviderForUserResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the AdminLinkProviderForUser operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AdminLinkProviderForUser operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/AdminLinkProviderForUser">REST API Reference for AdminLinkProviderForUser Operation</seealso> public virtual Task<AdminLinkProviderForUserResponse> AdminLinkProviderForUserAsync(AdminLinkProviderForUserRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AdminLinkProviderForUserRequestMarshaller(); var unmarshaller = AdminLinkProviderForUserResponseUnmarshaller.Instance; return InvokeAsync<AdminLinkProviderForUserRequest,AdminLinkProviderForUserResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region AdminListDevices internal virtual AdminListDevicesResponse AdminListDevices(AdminListDevicesRequest request) { var marshaller = new AdminListDevicesRequestMarshaller(); var unmarshaller = AdminListDevicesResponseUnmarshaller.Instance; return Invoke<AdminListDevicesRequest,AdminListDevicesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the AdminListDevices operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AdminListDevices operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/AdminListDevices">REST API Reference for AdminListDevices Operation</seealso> public virtual Task<AdminListDevicesResponse> AdminListDevicesAsync(AdminListDevicesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AdminListDevicesRequestMarshaller(); var unmarshaller = AdminListDevicesResponseUnmarshaller.Instance; return InvokeAsync<AdminListDevicesRequest,AdminListDevicesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region AdminListGroupsForUser internal virtual AdminListGroupsForUserResponse AdminListGroupsForUser(AdminListGroupsForUserRequest request) { var marshaller = new AdminListGroupsForUserRequestMarshaller(); var unmarshaller = AdminListGroupsForUserResponseUnmarshaller.Instance; return Invoke<AdminListGroupsForUserRequest,AdminListGroupsForUserResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the AdminListGroupsForUser operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AdminListGroupsForUser operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/AdminListGroupsForUser">REST API Reference for AdminListGroupsForUser Operation</seealso> public virtual Task<AdminListGroupsForUserResponse> AdminListGroupsForUserAsync(AdminListGroupsForUserRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AdminListGroupsForUserRequestMarshaller(); var unmarshaller = AdminListGroupsForUserResponseUnmarshaller.Instance; return InvokeAsync<AdminListGroupsForUserRequest,AdminListGroupsForUserResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region AdminListUserAuthEvents internal virtual AdminListUserAuthEventsResponse AdminListUserAuthEvents(AdminListUserAuthEventsRequest request) { var marshaller = new AdminListUserAuthEventsRequestMarshaller(); var unmarshaller = AdminListUserAuthEventsResponseUnmarshaller.Instance; return Invoke<AdminListUserAuthEventsRequest,AdminListUserAuthEventsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the AdminListUserAuthEvents operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AdminListUserAuthEvents operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/AdminListUserAuthEvents">REST API Reference for AdminListUserAuthEvents Operation</seealso> public virtual Task<AdminListUserAuthEventsResponse> AdminListUserAuthEventsAsync(AdminListUserAuthEventsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AdminListUserAuthEventsRequestMarshaller(); var unmarshaller = AdminListUserAuthEventsResponseUnmarshaller.Instance; return InvokeAsync<AdminListUserAuthEventsRequest,AdminListUserAuthEventsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region AdminRemoveUserFromGroup internal virtual AdminRemoveUserFromGroupResponse AdminRemoveUserFromGroup(AdminRemoveUserFromGroupRequest request) { var marshaller = new AdminRemoveUserFromGroupRequestMarshaller(); var unmarshaller = AdminRemoveUserFromGroupResponseUnmarshaller.Instance; return Invoke<AdminRemoveUserFromGroupRequest,AdminRemoveUserFromGroupResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the AdminRemoveUserFromGroup operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AdminRemoveUserFromGroup operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/AdminRemoveUserFromGroup">REST API Reference for AdminRemoveUserFromGroup Operation</seealso> public virtual Task<AdminRemoveUserFromGroupResponse> AdminRemoveUserFromGroupAsync(AdminRemoveUserFromGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AdminRemoveUserFromGroupRequestMarshaller(); var unmarshaller = AdminRemoveUserFromGroupResponseUnmarshaller.Instance; return InvokeAsync<AdminRemoveUserFromGroupRequest,AdminRemoveUserFromGroupResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region AdminResetUserPassword internal virtual AdminResetUserPasswordResponse AdminResetUserPassword(AdminResetUserPasswordRequest request) { var marshaller = new AdminResetUserPasswordRequestMarshaller(); var unmarshaller = AdminResetUserPasswordResponseUnmarshaller.Instance; return Invoke<AdminResetUserPasswordRequest,AdminResetUserPasswordResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the AdminResetUserPassword operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AdminResetUserPassword operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/AdminResetUserPassword">REST API Reference for AdminResetUserPassword Operation</seealso> public virtual Task<AdminResetUserPasswordResponse> AdminResetUserPasswordAsync(AdminResetUserPasswordRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AdminResetUserPasswordRequestMarshaller(); var unmarshaller = AdminResetUserPasswordResponseUnmarshaller.Instance; return InvokeAsync<AdminResetUserPasswordRequest,AdminResetUserPasswordResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region AdminRespondToAuthChallenge internal virtual AdminRespondToAuthChallengeResponse AdminRespondToAuthChallenge(AdminRespondToAuthChallengeRequest request) { var marshaller = new AdminRespondToAuthChallengeRequestMarshaller(); var unmarshaller = AdminRespondToAuthChallengeResponseUnmarshaller.Instance; return Invoke<AdminRespondToAuthChallengeRequest,AdminRespondToAuthChallengeResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the AdminRespondToAuthChallenge operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AdminRespondToAuthChallenge operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/AdminRespondToAuthChallenge">REST API Reference for AdminRespondToAuthChallenge Operation</seealso> public virtual Task<AdminRespondToAuthChallengeResponse> AdminRespondToAuthChallengeAsync(AdminRespondToAuthChallengeRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AdminRespondToAuthChallengeRequestMarshaller(); var unmarshaller = AdminRespondToAuthChallengeResponseUnmarshaller.Instance; return InvokeAsync<AdminRespondToAuthChallengeRequest,AdminRespondToAuthChallengeResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region AdminSetUserMFAPreference internal virtual AdminSetUserMFAPreferenceResponse AdminSetUserMFAPreference(AdminSetUserMFAPreferenceRequest request) { var marshaller = new AdminSetUserMFAPreferenceRequestMarshaller(); var unmarshaller = AdminSetUserMFAPreferenceResponseUnmarshaller.Instance; return Invoke<AdminSetUserMFAPreferenceRequest,AdminSetUserMFAPreferenceResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the AdminSetUserMFAPreference operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AdminSetUserMFAPreference operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/AdminSetUserMFAPreference">REST API Reference for AdminSetUserMFAPreference Operation</seealso> public virtual Task<AdminSetUserMFAPreferenceResponse> AdminSetUserMFAPreferenceAsync(AdminSetUserMFAPreferenceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AdminSetUserMFAPreferenceRequestMarshaller(); var unmarshaller = AdminSetUserMFAPreferenceResponseUnmarshaller.Instance; return InvokeAsync<AdminSetUserMFAPreferenceRequest,AdminSetUserMFAPreferenceResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region AdminSetUserSettings internal virtual AdminSetUserSettingsResponse AdminSetUserSettings(AdminSetUserSettingsRequest request) { var marshaller = new AdminSetUserSettingsRequestMarshaller(); var unmarshaller = AdminSetUserSettingsResponseUnmarshaller.Instance; return Invoke<AdminSetUserSettingsRequest,AdminSetUserSettingsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the AdminSetUserSettings operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AdminSetUserSettings operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/AdminSetUserSettings">REST API Reference for AdminSetUserSettings Operation</seealso> public virtual Task<AdminSetUserSettingsResponse> AdminSetUserSettingsAsync(AdminSetUserSettingsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AdminSetUserSettingsRequestMarshaller(); var unmarshaller = AdminSetUserSettingsResponseUnmarshaller.Instance; return InvokeAsync<AdminSetUserSettingsRequest,AdminSetUserSettingsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region AdminUpdateAuthEventFeedback internal virtual AdminUpdateAuthEventFeedbackResponse AdminUpdateAuthEventFeedback(AdminUpdateAuthEventFeedbackRequest request) { var marshaller = new AdminUpdateAuthEventFeedbackRequestMarshaller(); var unmarshaller = AdminUpdateAuthEventFeedbackResponseUnmarshaller.Instance; return Invoke<AdminUpdateAuthEventFeedbackRequest,AdminUpdateAuthEventFeedbackResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the AdminUpdateAuthEventFeedback operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AdminUpdateAuthEventFeedback operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/AdminUpdateAuthEventFeedback">REST API Reference for AdminUpdateAuthEventFeedback Operation</seealso> public virtual Task<AdminUpdateAuthEventFeedbackResponse> AdminUpdateAuthEventFeedbackAsync(AdminUpdateAuthEventFeedbackRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AdminUpdateAuthEventFeedbackRequestMarshaller(); var unmarshaller = AdminUpdateAuthEventFeedbackResponseUnmarshaller.Instance; return InvokeAsync<AdminUpdateAuthEventFeedbackRequest,AdminUpdateAuthEventFeedbackResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region AdminUpdateDeviceStatus internal virtual AdminUpdateDeviceStatusResponse AdminUpdateDeviceStatus(AdminUpdateDeviceStatusRequest request) { var marshaller = new AdminUpdateDeviceStatusRequestMarshaller(); var unmarshaller = AdminUpdateDeviceStatusResponseUnmarshaller.Instance; return Invoke<AdminUpdateDeviceStatusRequest,AdminUpdateDeviceStatusResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the AdminUpdateDeviceStatus operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AdminUpdateDeviceStatus operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/AdminUpdateDeviceStatus">REST API Reference for AdminUpdateDeviceStatus Operation</seealso> public virtual Task<AdminUpdateDeviceStatusResponse> AdminUpdateDeviceStatusAsync(AdminUpdateDeviceStatusRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AdminUpdateDeviceStatusRequestMarshaller(); var unmarshaller = AdminUpdateDeviceStatusResponseUnmarshaller.Instance; return InvokeAsync<AdminUpdateDeviceStatusRequest,AdminUpdateDeviceStatusResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region AdminUpdateUserAttributes internal virtual AdminUpdateUserAttributesResponse AdminUpdateUserAttributes(AdminUpdateUserAttributesRequest request) { var marshaller = new AdminUpdateUserAttributesRequestMarshaller(); var unmarshaller = AdminUpdateUserAttributesResponseUnmarshaller.Instance; return Invoke<AdminUpdateUserAttributesRequest,AdminUpdateUserAttributesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the AdminUpdateUserAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AdminUpdateUserAttributes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/AdminUpdateUserAttributes">REST API Reference for AdminUpdateUserAttributes Operation</seealso> public virtual Task<AdminUpdateUserAttributesResponse> AdminUpdateUserAttributesAsync(AdminUpdateUserAttributesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AdminUpdateUserAttributesRequestMarshaller(); var unmarshaller = AdminUpdateUserAttributesResponseUnmarshaller.Instance; return InvokeAsync<AdminUpdateUserAttributesRequest,AdminUpdateUserAttributesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region AdminUserGlobalSignOut internal virtual AdminUserGlobalSignOutResponse AdminUserGlobalSignOut(AdminUserGlobalSignOutRequest request) { var marshaller = new AdminUserGlobalSignOutRequestMarshaller(); var unmarshaller = AdminUserGlobalSignOutResponseUnmarshaller.Instance; return Invoke<AdminUserGlobalSignOutRequest,AdminUserGlobalSignOutResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the AdminUserGlobalSignOut operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AdminUserGlobalSignOut operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/AdminUserGlobalSignOut">REST API Reference for AdminUserGlobalSignOut Operation</seealso> public virtual Task<AdminUserGlobalSignOutResponse> AdminUserGlobalSignOutAsync(AdminUserGlobalSignOutRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AdminUserGlobalSignOutRequestMarshaller(); var unmarshaller = AdminUserGlobalSignOutResponseUnmarshaller.Instance; return InvokeAsync<AdminUserGlobalSignOutRequest,AdminUserGlobalSignOutResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region AssociateSoftwareToken internal virtual AssociateSoftwareTokenResponse AssociateSoftwareToken(AssociateSoftwareTokenRequest request) { var marshaller = new AssociateSoftwareTokenRequestMarshaller(); var unmarshaller = AssociateSoftwareTokenResponseUnmarshaller.Instance; return Invoke<AssociateSoftwareTokenRequest,AssociateSoftwareTokenResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the AssociateSoftwareToken operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AssociateSoftwareToken operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/AssociateSoftwareToken">REST API Reference for AssociateSoftwareToken Operation</seealso> public virtual Task<AssociateSoftwareTokenResponse> AssociateSoftwareTokenAsync(AssociateSoftwareTokenRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AssociateSoftwareTokenRequestMarshaller(); var unmarshaller = AssociateSoftwareTokenResponseUnmarshaller.Instance; return InvokeAsync<AssociateSoftwareTokenRequest,AssociateSoftwareTokenResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ChangePassword internal virtual ChangePasswordResponse ChangePassword(ChangePasswordRequest request) { var marshaller = new ChangePasswordRequestMarshaller(); var unmarshaller = ChangePasswordResponseUnmarshaller.Instance; return Invoke<ChangePasswordRequest,ChangePasswordResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ChangePassword operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ChangePassword operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/ChangePassword">REST API Reference for ChangePassword Operation</seealso> public virtual Task<ChangePasswordResponse> ChangePasswordAsync(ChangePasswordRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ChangePasswordRequestMarshaller(); var unmarshaller = ChangePasswordResponseUnmarshaller.Instance; return InvokeAsync<ChangePasswordRequest,ChangePasswordResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ConfirmDevice internal virtual ConfirmDeviceResponse ConfirmDevice(ConfirmDeviceRequest request) { var marshaller = new ConfirmDeviceRequestMarshaller(); var unmarshaller = ConfirmDeviceResponseUnmarshaller.Instance; return Invoke<ConfirmDeviceRequest,ConfirmDeviceResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ConfirmDevice operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ConfirmDevice operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/ConfirmDevice">REST API Reference for ConfirmDevice Operation</seealso> public virtual Task<ConfirmDeviceResponse> ConfirmDeviceAsync(ConfirmDeviceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ConfirmDeviceRequestMarshaller(); var unmarshaller = ConfirmDeviceResponseUnmarshaller.Instance; return InvokeAsync<ConfirmDeviceRequest,ConfirmDeviceResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ConfirmForgotPassword internal virtual ConfirmForgotPasswordResponse ConfirmForgotPassword(ConfirmForgotPasswordRequest request) { var marshaller = new ConfirmForgotPasswordRequestMarshaller(); var unmarshaller = ConfirmForgotPasswordResponseUnmarshaller.Instance; return Invoke<ConfirmForgotPasswordRequest,ConfirmForgotPasswordResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ConfirmForgotPassword operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ConfirmForgotPassword operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/ConfirmForgotPassword">REST API Reference for ConfirmForgotPassword Operation</seealso> public virtual Task<ConfirmForgotPasswordResponse> ConfirmForgotPasswordAsync(ConfirmForgotPasswordRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ConfirmForgotPasswordRequestMarshaller(); var unmarshaller = ConfirmForgotPasswordResponseUnmarshaller.Instance; return InvokeAsync<ConfirmForgotPasswordRequest,ConfirmForgotPasswordResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ConfirmSignUp internal virtual ConfirmSignUpResponse ConfirmSignUp(ConfirmSignUpRequest request) { var marshaller = new ConfirmSignUpRequestMarshaller(); var unmarshaller = ConfirmSignUpResponseUnmarshaller.Instance; return Invoke<ConfirmSignUpRequest,ConfirmSignUpResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ConfirmSignUp operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ConfirmSignUp operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/ConfirmSignUp">REST API Reference for ConfirmSignUp Operation</seealso> public virtual Task<ConfirmSignUpResponse> ConfirmSignUpAsync(ConfirmSignUpRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ConfirmSignUpRequestMarshaller(); var unmarshaller = ConfirmSignUpResponseUnmarshaller.Instance; return InvokeAsync<ConfirmSignUpRequest,ConfirmSignUpResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateGroup internal virtual CreateGroupResponse CreateGroup(CreateGroupRequest request) { var marshaller = new CreateGroupRequestMarshaller(); var unmarshaller = CreateGroupResponseUnmarshaller.Instance; return Invoke<CreateGroupRequest,CreateGroupResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateGroup operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateGroup operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/CreateGroup">REST API Reference for CreateGroup Operation</seealso> public virtual Task<CreateGroupResponse> CreateGroupAsync(CreateGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CreateGroupRequestMarshaller(); var unmarshaller = CreateGroupResponseUnmarshaller.Instance; return InvokeAsync<CreateGroupRequest,CreateGroupResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateIdentityProvider internal virtual CreateIdentityProviderResponse CreateIdentityProvider(CreateIdentityProviderRequest request) { var marshaller = new CreateIdentityProviderRequestMarshaller(); var unmarshaller = CreateIdentityProviderResponseUnmarshaller.Instance; return Invoke<CreateIdentityProviderRequest,CreateIdentityProviderResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateIdentityProvider operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateIdentityProvider operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/CreateIdentityProvider">REST API Reference for CreateIdentityProvider Operation</seealso> public virtual Task<CreateIdentityProviderResponse> CreateIdentityProviderAsync(CreateIdentityProviderRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CreateIdentityProviderRequestMarshaller(); var unmarshaller = CreateIdentityProviderResponseUnmarshaller.Instance; return InvokeAsync<CreateIdentityProviderRequest,CreateIdentityProviderResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateResourceServer internal virtual CreateResourceServerResponse CreateResourceServer(CreateResourceServerRequest request) { var marshaller = new CreateResourceServerRequestMarshaller(); var unmarshaller = CreateResourceServerResponseUnmarshaller.Instance; return Invoke<CreateResourceServerRequest,CreateResourceServerResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateResourceServer operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateResourceServer operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/CreateResourceServer">REST API Reference for CreateResourceServer Operation</seealso> public virtual Task<CreateResourceServerResponse> CreateResourceServerAsync(CreateResourceServerRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CreateResourceServerRequestMarshaller(); var unmarshaller = CreateResourceServerResponseUnmarshaller.Instance; return InvokeAsync<CreateResourceServerRequest,CreateResourceServerResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateUserImportJob internal virtual CreateUserImportJobResponse CreateUserImportJob(CreateUserImportJobRequest request) { var marshaller = new CreateUserImportJobRequestMarshaller(); var unmarshaller = CreateUserImportJobResponseUnmarshaller.Instance; return Invoke<CreateUserImportJobRequest,CreateUserImportJobResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateUserImportJob operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateUserImportJob operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/CreateUserImportJob">REST API Reference for CreateUserImportJob Operation</seealso> public virtual Task<CreateUserImportJobResponse> CreateUserImportJobAsync(CreateUserImportJobRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CreateUserImportJobRequestMarshaller(); var unmarshaller = CreateUserImportJobResponseUnmarshaller.Instance; return InvokeAsync<CreateUserImportJobRequest,CreateUserImportJobResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateUserPool internal virtual CreateUserPoolResponse CreateUserPool(CreateUserPoolRequest request) { var marshaller = new CreateUserPoolRequestMarshaller(); var unmarshaller = CreateUserPoolResponseUnmarshaller.Instance; return Invoke<CreateUserPoolRequest,CreateUserPoolResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateUserPool operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateUserPool operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/CreateUserPool">REST API Reference for CreateUserPool Operation</seealso> public virtual Task<CreateUserPoolResponse> CreateUserPoolAsync(CreateUserPoolRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CreateUserPoolRequestMarshaller(); var unmarshaller = CreateUserPoolResponseUnmarshaller.Instance; return InvokeAsync<CreateUserPoolRequest,CreateUserPoolResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateUserPoolClient internal virtual CreateUserPoolClientResponse CreateUserPoolClient(CreateUserPoolClientRequest request) { var marshaller = new CreateUserPoolClientRequestMarshaller(); var unmarshaller = CreateUserPoolClientResponseUnmarshaller.Instance; return Invoke<CreateUserPoolClientRequest,CreateUserPoolClientResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateUserPoolClient operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateUserPoolClient operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/CreateUserPoolClient">REST API Reference for CreateUserPoolClient Operation</seealso> public virtual Task<CreateUserPoolClientResponse> CreateUserPoolClientAsync(CreateUserPoolClientRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CreateUserPoolClientRequestMarshaller(); var unmarshaller = CreateUserPoolClientResponseUnmarshaller.Instance; return InvokeAsync<CreateUserPoolClientRequest,CreateUserPoolClientResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateUserPoolDomain internal virtual CreateUserPoolDomainResponse CreateUserPoolDomain(CreateUserPoolDomainRequest request) { var marshaller = new CreateUserPoolDomainRequestMarshaller(); var unmarshaller = CreateUserPoolDomainResponseUnmarshaller.Instance; return Invoke<CreateUserPoolDomainRequest,CreateUserPoolDomainResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateUserPoolDomain operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateUserPoolDomain operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/CreateUserPoolDomain">REST API Reference for CreateUserPoolDomain Operation</seealso> public virtual Task<CreateUserPoolDomainResponse> CreateUserPoolDomainAsync(CreateUserPoolDomainRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CreateUserPoolDomainRequestMarshaller(); var unmarshaller = CreateUserPoolDomainResponseUnmarshaller.Instance; return InvokeAsync<CreateUserPoolDomainRequest,CreateUserPoolDomainResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteGroup internal virtual DeleteGroupResponse DeleteGroup(DeleteGroupRequest request) { var marshaller = new DeleteGroupRequestMarshaller(); var unmarshaller = DeleteGroupResponseUnmarshaller.Instance; return Invoke<DeleteGroupRequest,DeleteGroupResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteGroup operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteGroup operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/DeleteGroup">REST API Reference for DeleteGroup Operation</seealso> public virtual Task<DeleteGroupResponse> DeleteGroupAsync(DeleteGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeleteGroupRequestMarshaller(); var unmarshaller = DeleteGroupResponseUnmarshaller.Instance; return InvokeAsync<DeleteGroupRequest,DeleteGroupResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteIdentityProvider internal virtual DeleteIdentityProviderResponse DeleteIdentityProvider(DeleteIdentityProviderRequest request) { var marshaller = new DeleteIdentityProviderRequestMarshaller(); var unmarshaller = DeleteIdentityProviderResponseUnmarshaller.Instance; return Invoke<DeleteIdentityProviderRequest,DeleteIdentityProviderResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteIdentityProvider operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteIdentityProvider operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/DeleteIdentityProvider">REST API Reference for DeleteIdentityProvider Operation</seealso> public virtual Task<DeleteIdentityProviderResponse> DeleteIdentityProviderAsync(DeleteIdentityProviderRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeleteIdentityProviderRequestMarshaller(); var unmarshaller = DeleteIdentityProviderResponseUnmarshaller.Instance; return InvokeAsync<DeleteIdentityProviderRequest,DeleteIdentityProviderResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteResourceServer internal virtual DeleteResourceServerResponse DeleteResourceServer(DeleteResourceServerRequest request) { var marshaller = new DeleteResourceServerRequestMarshaller(); var unmarshaller = DeleteResourceServerResponseUnmarshaller.Instance; return Invoke<DeleteResourceServerRequest,DeleteResourceServerResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteResourceServer operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteResourceServer operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/DeleteResourceServer">REST API Reference for DeleteResourceServer Operation</seealso> public virtual Task<DeleteResourceServerResponse> DeleteResourceServerAsync(DeleteResourceServerRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeleteResourceServerRequestMarshaller(); var unmarshaller = DeleteResourceServerResponseUnmarshaller.Instance; return InvokeAsync<DeleteResourceServerRequest,DeleteResourceServerResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteUser internal virtual DeleteUserResponse DeleteUser(DeleteUserRequest request) { var marshaller = new DeleteUserRequestMarshaller(); var unmarshaller = DeleteUserResponseUnmarshaller.Instance; return Invoke<DeleteUserRequest,DeleteUserResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteUser operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteUser operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/DeleteUser">REST API Reference for DeleteUser Operation</seealso> public virtual Task<DeleteUserResponse> DeleteUserAsync(DeleteUserRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeleteUserRequestMarshaller(); var unmarshaller = DeleteUserResponseUnmarshaller.Instance; return InvokeAsync<DeleteUserRequest,DeleteUserResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteUserAttributes internal virtual DeleteUserAttributesResponse DeleteUserAttributes(DeleteUserAttributesRequest request) { var marshaller = new DeleteUserAttributesRequestMarshaller(); var unmarshaller = DeleteUserAttributesResponseUnmarshaller.Instance; return Invoke<DeleteUserAttributesRequest,DeleteUserAttributesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteUserAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteUserAttributes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/DeleteUserAttributes">REST API Reference for DeleteUserAttributes Operation</seealso> public virtual Task<DeleteUserAttributesResponse> DeleteUserAttributesAsync(DeleteUserAttributesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeleteUserAttributesRequestMarshaller(); var unmarshaller = DeleteUserAttributesResponseUnmarshaller.Instance; return InvokeAsync<DeleteUserAttributesRequest,DeleteUserAttributesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteUserPool internal virtual DeleteUserPoolResponse DeleteUserPool(DeleteUserPoolRequest request) { var marshaller = new DeleteUserPoolRequestMarshaller(); var unmarshaller = DeleteUserPoolResponseUnmarshaller.Instance; return Invoke<DeleteUserPoolRequest,DeleteUserPoolResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteUserPool operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteUserPool operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/DeleteUserPool">REST API Reference for DeleteUserPool Operation</seealso> public virtual Task<DeleteUserPoolResponse> DeleteUserPoolAsync(DeleteUserPoolRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeleteUserPoolRequestMarshaller(); var unmarshaller = DeleteUserPoolResponseUnmarshaller.Instance; return InvokeAsync<DeleteUserPoolRequest,DeleteUserPoolResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteUserPoolClient internal virtual DeleteUserPoolClientResponse DeleteUserPoolClient(DeleteUserPoolClientRequest request) { var marshaller = new DeleteUserPoolClientRequestMarshaller(); var unmarshaller = DeleteUserPoolClientResponseUnmarshaller.Instance; return Invoke<DeleteUserPoolClientRequest,DeleteUserPoolClientResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteUserPoolClient operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteUserPoolClient operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/DeleteUserPoolClient">REST API Reference for DeleteUserPoolClient Operation</seealso> public virtual Task<DeleteUserPoolClientResponse> DeleteUserPoolClientAsync(DeleteUserPoolClientRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeleteUserPoolClientRequestMarshaller(); var unmarshaller = DeleteUserPoolClientResponseUnmarshaller.Instance; return InvokeAsync<DeleteUserPoolClientRequest,DeleteUserPoolClientResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteUserPoolDomain internal virtual DeleteUserPoolDomainResponse DeleteUserPoolDomain(DeleteUserPoolDomainRequest request) { var marshaller = new DeleteUserPoolDomainRequestMarshaller(); var unmarshaller = DeleteUserPoolDomainResponseUnmarshaller.Instance; return Invoke<DeleteUserPoolDomainRequest,DeleteUserPoolDomainResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteUserPoolDomain operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteUserPoolDomain operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/DeleteUserPoolDomain">REST API Reference for DeleteUserPoolDomain Operation</seealso> public virtual Task<DeleteUserPoolDomainResponse> DeleteUserPoolDomainAsync(DeleteUserPoolDomainRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeleteUserPoolDomainRequestMarshaller(); var unmarshaller = DeleteUserPoolDomainResponseUnmarshaller.Instance; return InvokeAsync<DeleteUserPoolDomainRequest,DeleteUserPoolDomainResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeIdentityProvider internal virtual DescribeIdentityProviderResponse DescribeIdentityProvider(DescribeIdentityProviderRequest request) { var marshaller = new DescribeIdentityProviderRequestMarshaller(); var unmarshaller = DescribeIdentityProviderResponseUnmarshaller.Instance; return Invoke<DescribeIdentityProviderRequest,DescribeIdentityProviderResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeIdentityProvider operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeIdentityProvider operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/DescribeIdentityProvider">REST API Reference for DescribeIdentityProvider Operation</seealso> public virtual Task<DescribeIdentityProviderResponse> DescribeIdentityProviderAsync(DescribeIdentityProviderRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeIdentityProviderRequestMarshaller(); var unmarshaller = DescribeIdentityProviderResponseUnmarshaller.Instance; return InvokeAsync<DescribeIdentityProviderRequest,DescribeIdentityProviderResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeResourceServer internal virtual DescribeResourceServerResponse DescribeResourceServer(DescribeResourceServerRequest request) { var marshaller = new DescribeResourceServerRequestMarshaller(); var unmarshaller = DescribeResourceServerResponseUnmarshaller.Instance; return Invoke<DescribeResourceServerRequest,DescribeResourceServerResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeResourceServer operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeResourceServer operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/DescribeResourceServer">REST API Reference for DescribeResourceServer Operation</seealso> public virtual Task<DescribeResourceServerResponse> DescribeResourceServerAsync(DescribeResourceServerRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeResourceServerRequestMarshaller(); var unmarshaller = DescribeResourceServerResponseUnmarshaller.Instance; return InvokeAsync<DescribeResourceServerRequest,DescribeResourceServerResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeRiskConfiguration internal virtual DescribeRiskConfigurationResponse DescribeRiskConfiguration(DescribeRiskConfigurationRequest request) { var marshaller = new DescribeRiskConfigurationRequestMarshaller(); var unmarshaller = DescribeRiskConfigurationResponseUnmarshaller.Instance; return Invoke<DescribeRiskConfigurationRequest,DescribeRiskConfigurationResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeRiskConfiguration operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeRiskConfiguration operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/DescribeRiskConfiguration">REST API Reference for DescribeRiskConfiguration Operation</seealso> public virtual Task<DescribeRiskConfigurationResponse> DescribeRiskConfigurationAsync(DescribeRiskConfigurationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeRiskConfigurationRequestMarshaller(); var unmarshaller = DescribeRiskConfigurationResponseUnmarshaller.Instance; return InvokeAsync<DescribeRiskConfigurationRequest,DescribeRiskConfigurationResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeUserImportJob internal virtual DescribeUserImportJobResponse DescribeUserImportJob(DescribeUserImportJobRequest request) { var marshaller = new DescribeUserImportJobRequestMarshaller(); var unmarshaller = DescribeUserImportJobResponseUnmarshaller.Instance; return Invoke<DescribeUserImportJobRequest,DescribeUserImportJobResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeUserImportJob operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeUserImportJob operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/DescribeUserImportJob">REST API Reference for DescribeUserImportJob Operation</seealso> public virtual Task<DescribeUserImportJobResponse> DescribeUserImportJobAsync(DescribeUserImportJobRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeUserImportJobRequestMarshaller(); var unmarshaller = DescribeUserImportJobResponseUnmarshaller.Instance; return InvokeAsync<DescribeUserImportJobRequest,DescribeUserImportJobResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeUserPool internal virtual DescribeUserPoolResponse DescribeUserPool(DescribeUserPoolRequest request) { var marshaller = new DescribeUserPoolRequestMarshaller(); var unmarshaller = DescribeUserPoolResponseUnmarshaller.Instance; return Invoke<DescribeUserPoolRequest,DescribeUserPoolResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeUserPool operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeUserPool operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/DescribeUserPool">REST API Reference for DescribeUserPool Operation</seealso> public virtual Task<DescribeUserPoolResponse> DescribeUserPoolAsync(DescribeUserPoolRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeUserPoolRequestMarshaller(); var unmarshaller = DescribeUserPoolResponseUnmarshaller.Instance; return InvokeAsync<DescribeUserPoolRequest,DescribeUserPoolResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeUserPoolClient internal virtual DescribeUserPoolClientResponse DescribeUserPoolClient(DescribeUserPoolClientRequest request) { var marshaller = new DescribeUserPoolClientRequestMarshaller(); var unmarshaller = DescribeUserPoolClientResponseUnmarshaller.Instance; return Invoke<DescribeUserPoolClientRequest,DescribeUserPoolClientResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeUserPoolClient operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeUserPoolClient operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/DescribeUserPoolClient">REST API Reference for DescribeUserPoolClient Operation</seealso> public virtual Task<DescribeUserPoolClientResponse> DescribeUserPoolClientAsync(DescribeUserPoolClientRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeUserPoolClientRequestMarshaller(); var unmarshaller = DescribeUserPoolClientResponseUnmarshaller.Instance; return InvokeAsync<DescribeUserPoolClientRequest,DescribeUserPoolClientResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeUserPoolDomain internal virtual DescribeUserPoolDomainResponse DescribeUserPoolDomain(DescribeUserPoolDomainRequest request) { var marshaller = new DescribeUserPoolDomainRequestMarshaller(); var unmarshaller = DescribeUserPoolDomainResponseUnmarshaller.Instance; return Invoke<DescribeUserPoolDomainRequest,DescribeUserPoolDomainResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeUserPoolDomain operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeUserPoolDomain operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/DescribeUserPoolDomain">REST API Reference for DescribeUserPoolDomain Operation</seealso> public virtual Task<DescribeUserPoolDomainResponse> DescribeUserPoolDomainAsync(DescribeUserPoolDomainRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeUserPoolDomainRequestMarshaller(); var unmarshaller = DescribeUserPoolDomainResponseUnmarshaller.Instance; return InvokeAsync<DescribeUserPoolDomainRequest,DescribeUserPoolDomainResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ForgetDevice internal virtual ForgetDeviceResponse ForgetDevice(ForgetDeviceRequest request) { var marshaller = new ForgetDeviceRequestMarshaller(); var unmarshaller = ForgetDeviceResponseUnmarshaller.Instance; return Invoke<ForgetDeviceRequest,ForgetDeviceResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ForgetDevice operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ForgetDevice operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/ForgetDevice">REST API Reference for ForgetDevice Operation</seealso> public virtual Task<ForgetDeviceResponse> ForgetDeviceAsync(ForgetDeviceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ForgetDeviceRequestMarshaller(); var unmarshaller = ForgetDeviceResponseUnmarshaller.Instance; return InvokeAsync<ForgetDeviceRequest,ForgetDeviceResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ForgotPassword internal virtual ForgotPasswordResponse ForgotPassword(ForgotPasswordRequest request) { var marshaller = new ForgotPasswordRequestMarshaller(); var unmarshaller = ForgotPasswordResponseUnmarshaller.Instance; return Invoke<ForgotPasswordRequest,ForgotPasswordResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ForgotPassword operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ForgotPassword operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/ForgotPassword">REST API Reference for ForgotPassword Operation</seealso> public virtual Task<ForgotPasswordResponse> ForgotPasswordAsync(ForgotPasswordRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ForgotPasswordRequestMarshaller(); var unmarshaller = ForgotPasswordResponseUnmarshaller.Instance; return InvokeAsync<ForgotPasswordRequest,ForgotPasswordResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region GetCSVHeader internal virtual GetCSVHeaderResponse GetCSVHeader(GetCSVHeaderRequest request) { var marshaller = new GetCSVHeaderRequestMarshaller(); var unmarshaller = GetCSVHeaderResponseUnmarshaller.Instance; return Invoke<GetCSVHeaderRequest,GetCSVHeaderResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetCSVHeader operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetCSVHeader operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/GetCSVHeader">REST API Reference for GetCSVHeader Operation</seealso> public virtual Task<GetCSVHeaderResponse> GetCSVHeaderAsync(GetCSVHeaderRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new GetCSVHeaderRequestMarshaller(); var unmarshaller = GetCSVHeaderResponseUnmarshaller.Instance; return InvokeAsync<GetCSVHeaderRequest,GetCSVHeaderResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region GetDevice internal virtual GetDeviceResponse GetDevice(GetDeviceRequest request) { var marshaller = new GetDeviceRequestMarshaller(); var unmarshaller = GetDeviceResponseUnmarshaller.Instance; return Invoke<GetDeviceRequest,GetDeviceResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetDevice operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetDevice operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/GetDevice">REST API Reference for GetDevice Operation</seealso> public virtual Task<GetDeviceResponse> GetDeviceAsync(GetDeviceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new GetDeviceRequestMarshaller(); var unmarshaller = GetDeviceResponseUnmarshaller.Instance; return InvokeAsync<GetDeviceRequest,GetDeviceResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region GetGroup internal virtual GetGroupResponse GetGroup(GetGroupRequest request) { var marshaller = new GetGroupRequestMarshaller(); var unmarshaller = GetGroupResponseUnmarshaller.Instance; return Invoke<GetGroupRequest,GetGroupResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetGroup operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetGroup operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/GetGroup">REST API Reference for GetGroup Operation</seealso> public virtual Task<GetGroupResponse> GetGroupAsync(GetGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new GetGroupRequestMarshaller(); var unmarshaller = GetGroupResponseUnmarshaller.Instance; return InvokeAsync<GetGroupRequest,GetGroupResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region GetIdentityProviderByIdentifier internal virtual GetIdentityProviderByIdentifierResponse GetIdentityProviderByIdentifier(GetIdentityProviderByIdentifierRequest request) { var marshaller = new GetIdentityProviderByIdentifierRequestMarshaller(); var unmarshaller = GetIdentityProviderByIdentifierResponseUnmarshaller.Instance; return Invoke<GetIdentityProviderByIdentifierRequest,GetIdentityProviderByIdentifierResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetIdentityProviderByIdentifier operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetIdentityProviderByIdentifier operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/GetIdentityProviderByIdentifier">REST API Reference for GetIdentityProviderByIdentifier Operation</seealso> public virtual Task<GetIdentityProviderByIdentifierResponse> GetIdentityProviderByIdentifierAsync(GetIdentityProviderByIdentifierRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new GetIdentityProviderByIdentifierRequestMarshaller(); var unmarshaller = GetIdentityProviderByIdentifierResponseUnmarshaller.Instance; return InvokeAsync<GetIdentityProviderByIdentifierRequest,GetIdentityProviderByIdentifierResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region GetUICustomization internal virtual GetUICustomizationResponse GetUICustomization(GetUICustomizationRequest request) { var marshaller = new GetUICustomizationRequestMarshaller(); var unmarshaller = GetUICustomizationResponseUnmarshaller.Instance; return Invoke<GetUICustomizationRequest,GetUICustomizationResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetUICustomization operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetUICustomization operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/GetUICustomization">REST API Reference for GetUICustomization Operation</seealso> public virtual Task<GetUICustomizationResponse> GetUICustomizationAsync(GetUICustomizationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new GetUICustomizationRequestMarshaller(); var unmarshaller = GetUICustomizationResponseUnmarshaller.Instance; return InvokeAsync<GetUICustomizationRequest,GetUICustomizationResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region GetUser internal virtual GetUserResponse GetUser(GetUserRequest request) { var marshaller = new GetUserRequestMarshaller(); var unmarshaller = GetUserResponseUnmarshaller.Instance; return Invoke<GetUserRequest,GetUserResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetUser operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetUser operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/GetUser">REST API Reference for GetUser Operation</seealso> public virtual Task<GetUserResponse> GetUserAsync(GetUserRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new GetUserRequestMarshaller(); var unmarshaller = GetUserResponseUnmarshaller.Instance; return InvokeAsync<GetUserRequest,GetUserResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region GetUserAttributeVerificationCode internal virtual GetUserAttributeVerificationCodeResponse GetUserAttributeVerificationCode(GetUserAttributeVerificationCodeRequest request) { var marshaller = new GetUserAttributeVerificationCodeRequestMarshaller(); var unmarshaller = GetUserAttributeVerificationCodeResponseUnmarshaller.Instance; return Invoke<GetUserAttributeVerificationCodeRequest,GetUserAttributeVerificationCodeResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetUserAttributeVerificationCode operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetUserAttributeVerificationCode operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/GetUserAttributeVerificationCode">REST API Reference for GetUserAttributeVerificationCode Operation</seealso> public virtual Task<GetUserAttributeVerificationCodeResponse> GetUserAttributeVerificationCodeAsync(GetUserAttributeVerificationCodeRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new GetUserAttributeVerificationCodeRequestMarshaller(); var unmarshaller = GetUserAttributeVerificationCodeResponseUnmarshaller.Instance; return InvokeAsync<GetUserAttributeVerificationCodeRequest,GetUserAttributeVerificationCodeResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region GetUserPoolMfaConfig internal virtual GetUserPoolMfaConfigResponse GetUserPoolMfaConfig(GetUserPoolMfaConfigRequest request) { var marshaller = new GetUserPoolMfaConfigRequestMarshaller(); var unmarshaller = GetUserPoolMfaConfigResponseUnmarshaller.Instance; return Invoke<GetUserPoolMfaConfigRequest,GetUserPoolMfaConfigResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetUserPoolMfaConfig operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetUserPoolMfaConfig operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/GetUserPoolMfaConfig">REST API Reference for GetUserPoolMfaConfig Operation</seealso> public virtual Task<GetUserPoolMfaConfigResponse> GetUserPoolMfaConfigAsync(GetUserPoolMfaConfigRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new GetUserPoolMfaConfigRequestMarshaller(); var unmarshaller = GetUserPoolMfaConfigResponseUnmarshaller.Instance; return InvokeAsync<GetUserPoolMfaConfigRequest,GetUserPoolMfaConfigResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region GlobalSignOut internal virtual GlobalSignOutResponse GlobalSignOut(GlobalSignOutRequest request) { var marshaller = new GlobalSignOutRequestMarshaller(); var unmarshaller = GlobalSignOutResponseUnmarshaller.Instance; return Invoke<GlobalSignOutRequest,GlobalSignOutResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GlobalSignOut operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GlobalSignOut operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/GlobalSignOut">REST API Reference for GlobalSignOut Operation</seealso> public virtual Task<GlobalSignOutResponse> GlobalSignOutAsync(GlobalSignOutRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new GlobalSignOutRequestMarshaller(); var unmarshaller = GlobalSignOutResponseUnmarshaller.Instance; return InvokeAsync<GlobalSignOutRequest,GlobalSignOutResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region InitiateAuth internal virtual InitiateAuthResponse InitiateAuth(InitiateAuthRequest request) { var marshaller = new InitiateAuthRequestMarshaller(); var unmarshaller = InitiateAuthResponseUnmarshaller.Instance; return Invoke<InitiateAuthRequest,InitiateAuthResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the InitiateAuth operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the InitiateAuth operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/InitiateAuth">REST API Reference for InitiateAuth Operation</seealso> public virtual Task<InitiateAuthResponse> InitiateAuthAsync(InitiateAuthRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new InitiateAuthRequestMarshaller(); var unmarshaller = InitiateAuthResponseUnmarshaller.Instance; return InvokeAsync<InitiateAuthRequest,InitiateAuthResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListDevices internal virtual ListDevicesResponse ListDevices(ListDevicesRequest request) { var marshaller = new ListDevicesRequestMarshaller(); var unmarshaller = ListDevicesResponseUnmarshaller.Instance; return Invoke<ListDevicesRequest,ListDevicesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ListDevices operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListDevices operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/ListDevices">REST API Reference for ListDevices Operation</seealso> public virtual Task<ListDevicesResponse> ListDevicesAsync(ListDevicesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListDevicesRequestMarshaller(); var unmarshaller = ListDevicesResponseUnmarshaller.Instance; return InvokeAsync<ListDevicesRequest,ListDevicesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListGroups internal virtual ListGroupsResponse ListGroups(ListGroupsRequest request) { var marshaller = new ListGroupsRequestMarshaller(); var unmarshaller = ListGroupsResponseUnmarshaller.Instance; return Invoke<ListGroupsRequest,ListGroupsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ListGroups operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListGroups operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/ListGroups">REST API Reference for ListGroups Operation</seealso> public virtual Task<ListGroupsResponse> ListGroupsAsync(ListGroupsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListGroupsRequestMarshaller(); var unmarshaller = ListGroupsResponseUnmarshaller.Instance; return InvokeAsync<ListGroupsRequest,ListGroupsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListIdentityProviders internal virtual ListIdentityProvidersResponse ListIdentityProviders(ListIdentityProvidersRequest request) { var marshaller = new ListIdentityProvidersRequestMarshaller(); var unmarshaller = ListIdentityProvidersResponseUnmarshaller.Instance; return Invoke<ListIdentityProvidersRequest,ListIdentityProvidersResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ListIdentityProviders operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListIdentityProviders operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/ListIdentityProviders">REST API Reference for ListIdentityProviders Operation</seealso> public virtual Task<ListIdentityProvidersResponse> ListIdentityProvidersAsync(ListIdentityProvidersRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListIdentityProvidersRequestMarshaller(); var unmarshaller = ListIdentityProvidersResponseUnmarshaller.Instance; return InvokeAsync<ListIdentityProvidersRequest,ListIdentityProvidersResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListResourceServers internal virtual ListResourceServersResponse ListResourceServers(ListResourceServersRequest request) { var marshaller = new ListResourceServersRequestMarshaller(); var unmarshaller = ListResourceServersResponseUnmarshaller.Instance; return Invoke<ListResourceServersRequest,ListResourceServersResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ListResourceServers operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListResourceServers operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/ListResourceServers">REST API Reference for ListResourceServers Operation</seealso> public virtual Task<ListResourceServersResponse> ListResourceServersAsync(ListResourceServersRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListResourceServersRequestMarshaller(); var unmarshaller = ListResourceServersResponseUnmarshaller.Instance; return InvokeAsync<ListResourceServersRequest,ListResourceServersResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListUserImportJobs internal virtual ListUserImportJobsResponse ListUserImportJobs(ListUserImportJobsRequest request) { var marshaller = new ListUserImportJobsRequestMarshaller(); var unmarshaller = ListUserImportJobsResponseUnmarshaller.Instance; return Invoke<ListUserImportJobsRequest,ListUserImportJobsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ListUserImportJobs operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListUserImportJobs operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/ListUserImportJobs">REST API Reference for ListUserImportJobs Operation</seealso> public virtual Task<ListUserImportJobsResponse> ListUserImportJobsAsync(ListUserImportJobsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListUserImportJobsRequestMarshaller(); var unmarshaller = ListUserImportJobsResponseUnmarshaller.Instance; return InvokeAsync<ListUserImportJobsRequest,ListUserImportJobsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListUserPoolClients internal virtual ListUserPoolClientsResponse ListUserPoolClients(ListUserPoolClientsRequest request) { var marshaller = new ListUserPoolClientsRequestMarshaller(); var unmarshaller = ListUserPoolClientsResponseUnmarshaller.Instance; return Invoke<ListUserPoolClientsRequest,ListUserPoolClientsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ListUserPoolClients operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListUserPoolClients operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/ListUserPoolClients">REST API Reference for ListUserPoolClients Operation</seealso> public virtual Task<ListUserPoolClientsResponse> ListUserPoolClientsAsync(ListUserPoolClientsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListUserPoolClientsRequestMarshaller(); var unmarshaller = ListUserPoolClientsResponseUnmarshaller.Instance; return InvokeAsync<ListUserPoolClientsRequest,ListUserPoolClientsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListUserPools internal virtual ListUserPoolsResponse ListUserPools(ListUserPoolsRequest request) { var marshaller = new ListUserPoolsRequestMarshaller(); var unmarshaller = ListUserPoolsResponseUnmarshaller.Instance; return Invoke<ListUserPoolsRequest,ListUserPoolsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ListUserPools operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListUserPools operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/ListUserPools">REST API Reference for ListUserPools Operation</seealso> public virtual Task<ListUserPoolsResponse> ListUserPoolsAsync(ListUserPoolsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListUserPoolsRequestMarshaller(); var unmarshaller = ListUserPoolsResponseUnmarshaller.Instance; return InvokeAsync<ListUserPoolsRequest,ListUserPoolsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListUsers internal virtual ListUsersResponse ListUsers(ListUsersRequest request) { var marshaller = new ListUsersRequestMarshaller(); var unmarshaller = ListUsersResponseUnmarshaller.Instance; return Invoke<ListUsersRequest,ListUsersResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ListUsers operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListUsers operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/ListUsers">REST API Reference for ListUsers Operation</seealso> public virtual Task<ListUsersResponse> ListUsersAsync(ListUsersRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListUsersRequestMarshaller(); var unmarshaller = ListUsersResponseUnmarshaller.Instance; return InvokeAsync<ListUsersRequest,ListUsersResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListUsersInGroup internal virtual ListUsersInGroupResponse ListUsersInGroup(ListUsersInGroupRequest request) { var marshaller = new ListUsersInGroupRequestMarshaller(); var unmarshaller = ListUsersInGroupResponseUnmarshaller.Instance; return Invoke<ListUsersInGroupRequest,ListUsersInGroupResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ListUsersInGroup operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListUsersInGroup operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/ListUsersInGroup">REST API Reference for ListUsersInGroup Operation</seealso> public virtual Task<ListUsersInGroupResponse> ListUsersInGroupAsync(ListUsersInGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListUsersInGroupRequestMarshaller(); var unmarshaller = ListUsersInGroupResponseUnmarshaller.Instance; return InvokeAsync<ListUsersInGroupRequest,ListUsersInGroupResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ResendConfirmationCode internal virtual ResendConfirmationCodeResponse ResendConfirmationCode(ResendConfirmationCodeRequest request) { var marshaller = new ResendConfirmationCodeRequestMarshaller(); var unmarshaller = ResendConfirmationCodeResponseUnmarshaller.Instance; return Invoke<ResendConfirmationCodeRequest,ResendConfirmationCodeResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ResendConfirmationCode operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ResendConfirmationCode operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/ResendConfirmationCode">REST API Reference for ResendConfirmationCode Operation</seealso> public virtual Task<ResendConfirmationCodeResponse> ResendConfirmationCodeAsync(ResendConfirmationCodeRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ResendConfirmationCodeRequestMarshaller(); var unmarshaller = ResendConfirmationCodeResponseUnmarshaller.Instance; return InvokeAsync<ResendConfirmationCodeRequest,ResendConfirmationCodeResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region RespondToAuthChallenge internal virtual RespondToAuthChallengeResponse RespondToAuthChallenge(RespondToAuthChallengeRequest request) { var marshaller = new RespondToAuthChallengeRequestMarshaller(); var unmarshaller = RespondToAuthChallengeResponseUnmarshaller.Instance; return Invoke<RespondToAuthChallengeRequest,RespondToAuthChallengeResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the RespondToAuthChallenge operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RespondToAuthChallenge operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/RespondToAuthChallenge">REST API Reference for RespondToAuthChallenge Operation</seealso> public virtual Task<RespondToAuthChallengeResponse> RespondToAuthChallengeAsync(RespondToAuthChallengeRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new RespondToAuthChallengeRequestMarshaller(); var unmarshaller = RespondToAuthChallengeResponseUnmarshaller.Instance; return InvokeAsync<RespondToAuthChallengeRequest,RespondToAuthChallengeResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region SetRiskConfiguration internal virtual SetRiskConfigurationResponse SetRiskConfiguration(SetRiskConfigurationRequest request) { var marshaller = new SetRiskConfigurationRequestMarshaller(); var unmarshaller = SetRiskConfigurationResponseUnmarshaller.Instance; return Invoke<SetRiskConfigurationRequest,SetRiskConfigurationResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the SetRiskConfiguration operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SetRiskConfiguration operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/SetRiskConfiguration">REST API Reference for SetRiskConfiguration Operation</seealso> public virtual Task<SetRiskConfigurationResponse> SetRiskConfigurationAsync(SetRiskConfigurationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new SetRiskConfigurationRequestMarshaller(); var unmarshaller = SetRiskConfigurationResponseUnmarshaller.Instance; return InvokeAsync<SetRiskConfigurationRequest,SetRiskConfigurationResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region SetUICustomization internal virtual SetUICustomizationResponse SetUICustomization(SetUICustomizationRequest request) { var marshaller = new SetUICustomizationRequestMarshaller(); var unmarshaller = SetUICustomizationResponseUnmarshaller.Instance; return Invoke<SetUICustomizationRequest,SetUICustomizationResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the SetUICustomization operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SetUICustomization operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/SetUICustomization">REST API Reference for SetUICustomization Operation</seealso> public virtual Task<SetUICustomizationResponse> SetUICustomizationAsync(SetUICustomizationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new SetUICustomizationRequestMarshaller(); var unmarshaller = SetUICustomizationResponseUnmarshaller.Instance; return InvokeAsync<SetUICustomizationRequest,SetUICustomizationResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region SetUserMFAPreference internal virtual SetUserMFAPreferenceResponse SetUserMFAPreference(SetUserMFAPreferenceRequest request) { var marshaller = new SetUserMFAPreferenceRequestMarshaller(); var unmarshaller = SetUserMFAPreferenceResponseUnmarshaller.Instance; return Invoke<SetUserMFAPreferenceRequest,SetUserMFAPreferenceResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the SetUserMFAPreference operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SetUserMFAPreference operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/SetUserMFAPreference">REST API Reference for SetUserMFAPreference Operation</seealso> public virtual Task<SetUserMFAPreferenceResponse> SetUserMFAPreferenceAsync(SetUserMFAPreferenceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new SetUserMFAPreferenceRequestMarshaller(); var unmarshaller = SetUserMFAPreferenceResponseUnmarshaller.Instance; return InvokeAsync<SetUserMFAPreferenceRequest,SetUserMFAPreferenceResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region SetUserPoolMfaConfig internal virtual SetUserPoolMfaConfigResponse SetUserPoolMfaConfig(SetUserPoolMfaConfigRequest request) { var marshaller = new SetUserPoolMfaConfigRequestMarshaller(); var unmarshaller = SetUserPoolMfaConfigResponseUnmarshaller.Instance; return Invoke<SetUserPoolMfaConfigRequest,SetUserPoolMfaConfigResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the SetUserPoolMfaConfig operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SetUserPoolMfaConfig operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/SetUserPoolMfaConfig">REST API Reference for SetUserPoolMfaConfig Operation</seealso> public virtual Task<SetUserPoolMfaConfigResponse> SetUserPoolMfaConfigAsync(SetUserPoolMfaConfigRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new SetUserPoolMfaConfigRequestMarshaller(); var unmarshaller = SetUserPoolMfaConfigResponseUnmarshaller.Instance; return InvokeAsync<SetUserPoolMfaConfigRequest,SetUserPoolMfaConfigResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region SetUserSettings internal virtual SetUserSettingsResponse SetUserSettings(SetUserSettingsRequest request) { var marshaller = new SetUserSettingsRequestMarshaller(); var unmarshaller = SetUserSettingsResponseUnmarshaller.Instance; return Invoke<SetUserSettingsRequest,SetUserSettingsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the SetUserSettings operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SetUserSettings operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/SetUserSettings">REST API Reference for SetUserSettings Operation</seealso> public virtual Task<SetUserSettingsResponse> SetUserSettingsAsync(SetUserSettingsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new SetUserSettingsRequestMarshaller(); var unmarshaller = SetUserSettingsResponseUnmarshaller.Instance; return InvokeAsync<SetUserSettingsRequest,SetUserSettingsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region SignUp internal virtual SignUpResponse SignUp(SignUpRequest request) { var marshaller = new SignUpRequestMarshaller(); var unmarshaller = SignUpResponseUnmarshaller.Instance; return Invoke<SignUpRequest,SignUpResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the SignUp operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SignUp operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/SignUp">REST API Reference for SignUp Operation</seealso> public virtual Task<SignUpResponse> SignUpAsync(SignUpRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new SignUpRequestMarshaller(); var unmarshaller = SignUpResponseUnmarshaller.Instance; return InvokeAsync<SignUpRequest,SignUpResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region StartUserImportJob internal virtual StartUserImportJobResponse StartUserImportJob(StartUserImportJobRequest request) { var marshaller = new StartUserImportJobRequestMarshaller(); var unmarshaller = StartUserImportJobResponseUnmarshaller.Instance; return Invoke<StartUserImportJobRequest,StartUserImportJobResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the StartUserImportJob operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the StartUserImportJob operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/StartUserImportJob">REST API Reference for StartUserImportJob Operation</seealso> public virtual Task<StartUserImportJobResponse> StartUserImportJobAsync(StartUserImportJobRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new StartUserImportJobRequestMarshaller(); var unmarshaller = StartUserImportJobResponseUnmarshaller.Instance; return InvokeAsync<StartUserImportJobRequest,StartUserImportJobResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region StopUserImportJob internal virtual StopUserImportJobResponse StopUserImportJob(StopUserImportJobRequest request) { var marshaller = new StopUserImportJobRequestMarshaller(); var unmarshaller = StopUserImportJobResponseUnmarshaller.Instance; return Invoke<StopUserImportJobRequest,StopUserImportJobResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the StopUserImportJob operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the StopUserImportJob operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/StopUserImportJob">REST API Reference for StopUserImportJob Operation</seealso> public virtual Task<StopUserImportJobResponse> StopUserImportJobAsync(StopUserImportJobRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new StopUserImportJobRequestMarshaller(); var unmarshaller = StopUserImportJobResponseUnmarshaller.Instance; return InvokeAsync<StopUserImportJobRequest,StopUserImportJobResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region UpdateAuthEventFeedback internal virtual UpdateAuthEventFeedbackResponse UpdateAuthEventFeedback(UpdateAuthEventFeedbackRequest request) { var marshaller = new UpdateAuthEventFeedbackRequestMarshaller(); var unmarshaller = UpdateAuthEventFeedbackResponseUnmarshaller.Instance; return Invoke<UpdateAuthEventFeedbackRequest,UpdateAuthEventFeedbackResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the UpdateAuthEventFeedback operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateAuthEventFeedback operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/UpdateAuthEventFeedback">REST API Reference for UpdateAuthEventFeedback Operation</seealso> public virtual Task<UpdateAuthEventFeedbackResponse> UpdateAuthEventFeedbackAsync(UpdateAuthEventFeedbackRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new UpdateAuthEventFeedbackRequestMarshaller(); var unmarshaller = UpdateAuthEventFeedbackResponseUnmarshaller.Instance; return InvokeAsync<UpdateAuthEventFeedbackRequest,UpdateAuthEventFeedbackResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region UpdateDeviceStatus internal virtual UpdateDeviceStatusResponse UpdateDeviceStatus(UpdateDeviceStatusRequest request) { var marshaller = new UpdateDeviceStatusRequestMarshaller(); var unmarshaller = UpdateDeviceStatusResponseUnmarshaller.Instance; return Invoke<UpdateDeviceStatusRequest,UpdateDeviceStatusResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the UpdateDeviceStatus operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateDeviceStatus operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/UpdateDeviceStatus">REST API Reference for UpdateDeviceStatus Operation</seealso> public virtual Task<UpdateDeviceStatusResponse> UpdateDeviceStatusAsync(UpdateDeviceStatusRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new UpdateDeviceStatusRequestMarshaller(); var unmarshaller = UpdateDeviceStatusResponseUnmarshaller.Instance; return InvokeAsync<UpdateDeviceStatusRequest,UpdateDeviceStatusResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region UpdateGroup internal virtual UpdateGroupResponse UpdateGroup(UpdateGroupRequest request) { var marshaller = new UpdateGroupRequestMarshaller(); var unmarshaller = UpdateGroupResponseUnmarshaller.Instance; return Invoke<UpdateGroupRequest,UpdateGroupResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the UpdateGroup operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateGroup operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/UpdateGroup">REST API Reference for UpdateGroup Operation</seealso> public virtual Task<UpdateGroupResponse> UpdateGroupAsync(UpdateGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new UpdateGroupRequestMarshaller(); var unmarshaller = UpdateGroupResponseUnmarshaller.Instance; return InvokeAsync<UpdateGroupRequest,UpdateGroupResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region UpdateIdentityProvider internal virtual UpdateIdentityProviderResponse UpdateIdentityProvider(UpdateIdentityProviderRequest request) { var marshaller = new UpdateIdentityProviderRequestMarshaller(); var unmarshaller = UpdateIdentityProviderResponseUnmarshaller.Instance; return Invoke<UpdateIdentityProviderRequest,UpdateIdentityProviderResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the UpdateIdentityProvider operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateIdentityProvider operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/UpdateIdentityProvider">REST API Reference for UpdateIdentityProvider Operation</seealso> public virtual Task<UpdateIdentityProviderResponse> UpdateIdentityProviderAsync(UpdateIdentityProviderRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new UpdateIdentityProviderRequestMarshaller(); var unmarshaller = UpdateIdentityProviderResponseUnmarshaller.Instance; return InvokeAsync<UpdateIdentityProviderRequest,UpdateIdentityProviderResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region UpdateResourceServer internal virtual UpdateResourceServerResponse UpdateResourceServer(UpdateResourceServerRequest request) { var marshaller = new UpdateResourceServerRequestMarshaller(); var unmarshaller = UpdateResourceServerResponseUnmarshaller.Instance; return Invoke<UpdateResourceServerRequest,UpdateResourceServerResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the UpdateResourceServer operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateResourceServer operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/UpdateResourceServer">REST API Reference for UpdateResourceServer Operation</seealso> public virtual Task<UpdateResourceServerResponse> UpdateResourceServerAsync(UpdateResourceServerRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new UpdateResourceServerRequestMarshaller(); var unmarshaller = UpdateResourceServerResponseUnmarshaller.Instance; return InvokeAsync<UpdateResourceServerRequest,UpdateResourceServerResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region UpdateUserAttributes internal virtual UpdateUserAttributesResponse UpdateUserAttributes(UpdateUserAttributesRequest request) { var marshaller = new UpdateUserAttributesRequestMarshaller(); var unmarshaller = UpdateUserAttributesResponseUnmarshaller.Instance; return Invoke<UpdateUserAttributesRequest,UpdateUserAttributesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the UpdateUserAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateUserAttributes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/UpdateUserAttributes">REST API Reference for UpdateUserAttributes Operation</seealso> public virtual Task<UpdateUserAttributesResponse> UpdateUserAttributesAsync(UpdateUserAttributesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new UpdateUserAttributesRequestMarshaller(); var unmarshaller = UpdateUserAttributesResponseUnmarshaller.Instance; return InvokeAsync<UpdateUserAttributesRequest,UpdateUserAttributesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region UpdateUserPool internal virtual UpdateUserPoolResponse UpdateUserPool(UpdateUserPoolRequest request) { var marshaller = new UpdateUserPoolRequestMarshaller(); var unmarshaller = UpdateUserPoolResponseUnmarshaller.Instance; return Invoke<UpdateUserPoolRequest,UpdateUserPoolResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the UpdateUserPool operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateUserPool operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/UpdateUserPool">REST API Reference for UpdateUserPool Operation</seealso> public virtual Task<UpdateUserPoolResponse> UpdateUserPoolAsync(UpdateUserPoolRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new UpdateUserPoolRequestMarshaller(); var unmarshaller = UpdateUserPoolResponseUnmarshaller.Instance; return InvokeAsync<UpdateUserPoolRequest,UpdateUserPoolResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region UpdateUserPoolClient internal virtual UpdateUserPoolClientResponse UpdateUserPoolClient(UpdateUserPoolClientRequest request) { var marshaller = new UpdateUserPoolClientRequestMarshaller(); var unmarshaller = UpdateUserPoolClientResponseUnmarshaller.Instance; return Invoke<UpdateUserPoolClientRequest,UpdateUserPoolClientResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the UpdateUserPoolClient operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateUserPoolClient operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/UpdateUserPoolClient">REST API Reference for UpdateUserPoolClient Operation</seealso> public virtual Task<UpdateUserPoolClientResponse> UpdateUserPoolClientAsync(UpdateUserPoolClientRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new UpdateUserPoolClientRequestMarshaller(); var unmarshaller = UpdateUserPoolClientResponseUnmarshaller.Instance; return InvokeAsync<UpdateUserPoolClientRequest,UpdateUserPoolClientResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region VerifySoftwareToken internal virtual VerifySoftwareTokenResponse VerifySoftwareToken(VerifySoftwareTokenRequest request) { var marshaller = new VerifySoftwareTokenRequestMarshaller(); var unmarshaller = VerifySoftwareTokenResponseUnmarshaller.Instance; return Invoke<VerifySoftwareTokenRequest,VerifySoftwareTokenResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the VerifySoftwareToken operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the VerifySoftwareToken operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/VerifySoftwareToken">REST API Reference for VerifySoftwareToken Operation</seealso> public virtual Task<VerifySoftwareTokenResponse> VerifySoftwareTokenAsync(VerifySoftwareTokenRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new VerifySoftwareTokenRequestMarshaller(); var unmarshaller = VerifySoftwareTokenResponseUnmarshaller.Instance; return InvokeAsync<VerifySoftwareTokenRequest,VerifySoftwareTokenResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region VerifyUserAttribute internal virtual VerifyUserAttributeResponse VerifyUserAttribute(VerifyUserAttributeRequest request) { var marshaller = new VerifyUserAttributeRequestMarshaller(); var unmarshaller = VerifyUserAttributeResponseUnmarshaller.Instance; return Invoke<VerifyUserAttributeRequest,VerifyUserAttributeResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the VerifyUserAttribute operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the VerifyUserAttribute operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/VerifyUserAttribute">REST API Reference for VerifyUserAttribute Operation</seealso> public virtual Task<VerifyUserAttributeResponse> VerifyUserAttributeAsync(VerifyUserAttributeRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new VerifyUserAttributeRequestMarshaller(); var unmarshaller = VerifyUserAttributeResponseUnmarshaller.Instance; return InvokeAsync<VerifyUserAttributeRequest,VerifyUserAttributeResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion } }
52.588995
239
0.705498
[ "Apache-2.0" ]
Murcho/aws-sdk-net
sdk/src/Services/CognitoIdentityProvider/Generated/_mobile/AmazonCognitoIdentityProviderClient.cs
171,072
C#
using Audacia.OrToolsPlayground.Examples.MakePizza.Constants; namespace Audacia.OrToolsPlayground.Examples.MakePizza.Models { public class ScheduledPizzaStage { public CookingStage Stage { get; set; } public long Start { get; set; } public long Finish { get; set; } } }
25
62
0.655385
[ "MIT" ]
audaciaconsulting/Audacia.OrToolsPlayground
Audacia.OrToolsPlayground/Examples/MakePizza/Models/ScheduledPizzaStage.cs
327
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.OpenApi.Models; using RealStateAPI.Contexts; using RealStateAPI.Services; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace RealStateAPI { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddAutoMapper(typeof(Startup)); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "RealStateAPI", Version = "v1" }); c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First()); }); services.AddScoped<IRealStateAPIRepository, RealStateAPIRepository>(); services.AddDbContext<AppDBContext>(options => { options.UseSqlServer( Configuration.GetConnectionString("DefaultConnection")); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "RealStateAPI v1")); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
31.191781
106
0.636803
[ "MIT" ]
K4m0/RealStateAPI
RealStateAPI/Startup.cs
2,277
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 organizations-2016-11-28.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.Organizations.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Organizations.Model.Internal.MarshallTransformations { /// <summary> /// DisablePolicyType Request Marshaller /// </summary> public class DisablePolicyTypeRequestMarshaller : IMarshaller<IRequest, DisablePolicyTypeRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((DisablePolicyTypeRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(DisablePolicyTypeRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.Organizations"); string target = "AWSOrganizationsV20161128.DisablePolicyType"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2016-11-28"; request.HttpMethod = "POST"; request.ResourcePath = "/"; request.MarshallerVersion = 2; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetPolicyType()) { context.Writer.WritePropertyName("PolicyType"); context.Writer.Write(publicRequest.PolicyType); } if(publicRequest.IsSetRootId()) { context.Writer.WritePropertyName("RootId"); context.Writer.Write(publicRequest.RootId); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static DisablePolicyTypeRequestMarshaller _instance = new DisablePolicyTypeRequestMarshaller(); internal static DisablePolicyTypeRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DisablePolicyTypeRequestMarshaller Instance { get { return _instance; } } } }
35.558559
149
0.625285
[ "Apache-2.0" ]
PureKrome/aws-sdk-net
sdk/src/Services/Organizations/Generated/Model/Internal/MarshallTransformations/DisablePolicyTypeRequestMarshaller.cs
3,947
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Async_Inn.Models.ViewModels { public class RoomHotelVM { public IEnumerable<HotelRoom> HotelRoom { get; set; } public Hotel Hotel { get; set; } public IEnumerable<Room> Room { get; set; } } }
19.941176
61
0.678466
[ "MIT" ]
karina6188/Async-Inn
Async_Inn/Async_Inn/Models/ViewModels/RoomHotelVM.cs
341
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: EnumType.cs.tt namespace Microsoft.Graph2.CallRecords { using System; using Newtonsoft.Json; /// <summary> /// The enum NetworkConnectionType. /// </summary> [JsonConverter(typeof(Microsoft.Graph.EnumConverter))] public enum NetworkConnectionType { /// <summary> /// Unknown /// </summary> Unknown = 0, /// <summary> /// Wired /// </summary> Wired = 1, } }
26.085714
153
0.501643
[ "MIT" ]
adhiambovivian/MSGraph-SDK-Code-Generator
test/Typewriter.Test/TestDataCSharp/com/microsoft/graph2/callrecords/model/NetworkConnectionType.cs
913
C#
using chapter_09.Engine.Input; namespace chapter_09.Input { public class DevInputCommand : BaseInputCommand { // Out of Game Commands public class DevQuit : DevInputCommand { } public class DevShoot : DevInputCommand { } } }
22
52
0.666667
[ "MIT" ]
Apress/monogame-mastery
chapter-09/start/States/Dev/DevInputCommand.cs
266
C#
/* Copyright 2009-2021 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Runtime.InteropServices; using Microsoft.Win32; namespace MeshCentralRouter { public class Win32Api { public const int WINHTTP_ACCESS_TYPE_DEFAULT_PROXY = 0; public const int WINHTTP_ACCESS_TYPE_NO_PROXY = 1; public const int WINHTTP_ACCESS_TYPE_NAMED_PROXY = 3; public const int WINHTTP_AUTOPROXY_AUTO_DETECT = 0x00000001; public const int WINHTTP_AUTOPROXY_CONFIG_URL = 0x00000002; public const int WINHTTP_AUTOPROXY_RUN_INPROCESS = 0x00010000; public const int WINHTTP_AUTOPROXY_RUN_OUTPROCESS_ONLY = 0x00020000; public const int WINHTTP_AUTO_DETECT_TYPE_DHCP = 0x00000001; public const int WINHTTP_AUTO_DETECT_TYPE_DNS_A = 0x00000002; [DllImport("User32.dll", CharSet = CharSet.Auto)] public static extern IntPtr SetClipboardViewer(IntPtr hWndNewViewer); [DllImport("User32.dll", CharSet = CharSet.Auto)] public static extern bool ChangeClipboardChain(IntPtr hWndRemove, IntPtr hWndNewNext); [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam); [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct WINHTTP_AUTOPROXY_OPTIONS { [MarshalAs(UnmanagedType.U4)] public int dwFlags; [MarshalAs(UnmanagedType.U4)] public int dwAutoDetectFlags; public string lpszAutoConfigUrl; public IntPtr lpvReserved; [MarshalAs(UnmanagedType.U4)] public int dwReserved; public bool fAutoLoginIfChallenged; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct WINHTTP_PROXY_INFO { [MarshalAs(UnmanagedType.U4)] public int dwAccessType; public string lpszProxy; public string lpszProxyBypass; } [DllImport("winhttp.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern bool WinHttpGetProxyForUrl(IntPtr hSession, string lpcwszUrl, ref WINHTTP_AUTOPROXY_OPTIONS pAutoProxyOptions, ref WINHTTP_PROXY_INFO pProxyInfo); [DllImport("winhttp.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern IntPtr WinHttpOpen(string pwszUserAgent, int dwAccessType, IntPtr pwszProxyName, IntPtr pwszProxyBypass, int dwFlags); [DllImport("winhttp.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern bool WinHttpCloseHandle(IntPtr hInternet); [DllImport("kernel32.dll")] public static extern int GetLastError(); public static Uri GetProxy(Uri url) { // Check if we need to use a HTTP proxy (Auto-proxy way) try { RegistryKey registryKey = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true); Object x = registryKey.GetValue("AutoConfigURL", null); if ((x != null) && (x.GetType() == typeof(string))) { string proxyStr = GetProxyForUrlUsingPac("http" + ((url.Port == 80) ? "" : "s") + "://" + url.Host + ":" + url.Port, x.ToString()); return new Uri("http://" + proxyStr); } } catch (Exception) { } Uri proxyUri = null; try { // Check if we need to use a HTTP proxy (Normal way) proxyUri = System.Net.HttpWebRequest.GetSystemWebProxy().GetProxy(url); if ((url.Host.ToLower() == proxyUri.Host.ToLower()) && (url.Port == proxyUri.Port)) { return null; } } catch (Exception) { } return proxyUri; } private static string GetProxyForUrlUsingPac(string DestinationUrl, string PacUri) { IntPtr WinHttpSession = Win32Api.WinHttpOpen("User", Win32Api.WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, IntPtr.Zero, IntPtr.Zero, 0); Win32Api.WINHTTP_AUTOPROXY_OPTIONS ProxyOptions = new Win32Api.WINHTTP_AUTOPROXY_OPTIONS(); Win32Api.WINHTTP_PROXY_INFO ProxyInfo = new Win32Api.WINHTTP_PROXY_INFO(); ProxyOptions.dwFlags = Win32Api.WINHTTP_AUTOPROXY_CONFIG_URL; ProxyOptions.dwAutoDetectFlags = (Win32Api.WINHTTP_AUTO_DETECT_TYPE_DHCP | Win32Api.WINHTTP_AUTO_DETECT_TYPE_DNS_A); ProxyOptions.lpszAutoConfigUrl = PacUri; // Get Proxy bool IsSuccess = Win32Api.WinHttpGetProxyForUrl(WinHttpSession, DestinationUrl, ref ProxyOptions, ref ProxyInfo); Win32Api.WinHttpCloseHandle(WinHttpSession); if (IsSuccess) { return ProxyInfo.lpszProxy; } else { Console.WriteLine("Error: {0}", Win32Api.GetLastError()); return null; } } } }
42.368421
175
0.654126
[ "Apache-2.0" ]
SPEMoorthy/MeshCentralRouter
Win32Api.cs
5,635
C#
using System; using System.ComponentModel.DataAnnotations; using System.Threading.Tasks; using CrackSharp.Api.Services.Des; using CrackSharp.Core; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace CrackSharp.Api.Controllers { [ApiController] [Route("api/v1/[controller]")] public class DesController : ControllerBase { private const string DefaultChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; private readonly ILogger<DesController> _logger; private readonly DesBruteForceDecryptionService _decryptor; private readonly DesEncryptionService _encryptor; public DesController(ILogger<DesController> logger, DesBruteForceDecryptionService decryptor, DesEncryptionService encryptor) { _logger = logger; _decryptor = decryptor; _encryptor = encryptor; } [HttpGet("decrypt")] public async Task<ActionResult<string>> Get( [Required, RegularExpression("^[a-zA-Z0-9./]{13}$")] string hash, [Range(1, 8)] int maxTextLength = 8, [RegularExpression("^[a-zA-Z0-9./]+$")] string? chars = DefaultChars) { var logMessage = $"Decryption of the {nameof(hash)} '{hash}' " + $"with {nameof(maxTextLength)} = {maxTextLength} " + $"and {nameof(chars)} = '{chars}'"; try { return await _decryptor.DecryptAsync(hash, maxTextLength, chars ?? DefaultChars, HttpContext.RequestAborted); } catch (DecryptionFailedException e) { _logger.LogError($"{logMessage} failed: {e.Message}"); return NotFound(); } catch (OperationCanceledException) { _logger.LogWarning($"{logMessage} canceled."); return StatusCode(StatusCodes.Status408RequestTimeout); } catch (Exception e) { _logger.LogError($"{logMessage} failed: {e.Message}{Environment.NewLine}{e.StackTrace}"); throw; } } [HttpGet("encrypt")] public string Get([Required] string text, [RegularExpression("^[a-zA-Z0-9./]{2}$")] string? salt = null) { try { return _encryptor.Encrypt(text, salt); } catch (Exception e) { _logger.LogError($"Encryption of the {nameof(text)} '{text}' with " + $"{nameof(salt)} '{salt}' failed: {e.Message}{Environment.NewLine}{e.StackTrace}"); throw; } } } }
34.703704
105
0.568837
[ "MIT" ]
aannenko/CrackSharp
src/CrackSharp.Api/Controllers/DesController.cs
2,813
C#
using System.Runtime.InteropServices; // 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("71c3bba5-ed89-4d4f-b5ca-334d6952143a")]
42.4
84
0.766509
[ "MIT" ]
0b01/perfview
src/HeapDump/Properties/AssemblyInfo.cs
426
C#
using System; using System.IO; using System.Reflection; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; namespace Proxy.RabbitMQ; public static class ExceptionExtensions { public static void GetObjectData(this Exception e, SerializationInfo info) { foreach (var p in e.GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)) info.AddValue(p.Name, p.GetValue(e).ToBytes()); } public static void SetObjectData(this Exception e, SerializationInfo info) { foreach (var p in e.GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)) { var bytes = (byte[]) info.GetValue(p.Name, typeof(byte[]))!; var value = bytes.ToObject(); p.SetValue(e, value); } } private static byte[]? ToBytes(this object? obj) { if (obj == null) return null; using var stream = new MemoryStream(); var formatter = new BinaryFormatter(); #pragma warning disable SYSLIB0011 formatter.Serialize(stream, obj); #pragma warning restore SYSLIB0011 stream.Flush(); return stream.ToArray(); } private static object? ToObject(this byte[]? bytes) { if (bytes == null) return null; using var stream = new MemoryStream(bytes, 0, bytes.Length, false); var formatter = new BinaryFormatter(); #pragma warning disable SYSLIB0011 var data = formatter.Deserialize(stream); #pragma warning restore SYSLIB0011 stream.Flush(); return data; } }
30.962963
125
0.656699
[ "MIT" ]
newshadowk/Nrpc
src/Proxy.RabbitMQ/Helper/ExceptionExtensions.cs
1,674
C#
using System; using Microsoft.Extensions.DependencyInjection; using Shiny.Locations; namespace Shiny { public static class ServiceCollectionExtensions { /// <summary> /// /// </summary> /// <param name="services"></param> /// <returns></returns> public static bool UseMotionActivity(this IServiceCollection services) { #if __ANDROID__ services.AddSingleton<AndroidSqliteDatabase>(); services.AddSingleton<IMotionActivityManager, MotionActivityManagerImpl>(); return true; #elif __IOS__ services.AddSingleton<IMotionActivityManager, MotionActivityManagerImpl>(); return true; #else return false; #endif } /// <summary> /// /// </summary> /// <param name="services"></param> /// <param name="regions"></param> /// <returns></returns> public static bool UseGeofencing(this IServiceCollection services, Type geofenceDelegateType, params GeofenceRegion[] regions) { #if NETSTANDARD return false; #else services.RegisterModule(new GeofenceModule(geofenceDelegateType, regions)); return true; #endif } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="services"></param> /// <param name="regions"></param> /// <returns></returns> public static bool UseGeofencing<T>(this IServiceCollection services, params GeofenceRegion[] regions) where T : class, IGeofenceDelegate { #if NETSTANDARD return false; #else services.RegisterModule(new GeofenceModule(typeof(T), regions)); return true; #endif } /// <summary> /// This registers GPS services with the Shiny container - foreground only /// </summary> /// <param name="services"></param> /// <returns></returns> public static bool UseGps(this IServiceCollection services) { #if NETSTANDARD return false; #else services.RegisterModule(new GpsModule(null, null)); return true; #endif } /// <summary> /// This registers GPS services with the Shiny container as well as the delegate - you can also auto-start the listener when necessary background permissions are received /// </summary> /// <param name="delegateType">The IGpsDelegate to call</param> /// <param name="services">The servicecollection to configure</param> /// <param name="requestIfPermissionGranted">This will be called when permission is given to use GPS functionality (background permission is assumed when calling this - setting your GPS request to not use background is ignored)</param> /// <returns></returns> public static bool UseGps(this IServiceCollection services, Type delegateType, Action<GpsRequest> requestIfPermissionGranted = null) { #if NETSTANDARD return false; #else services.RegisterModule(new GpsModule(delegateType, requestIfPermissionGranted)); return true; #endif } /// <summary> /// This registers GPS services with the Shiny container as well as the delegate - you can also auto-start the listener when necessary background permissions are received /// </summary> /// <typeparam name="T">The IGpsDelegate to call</typeparam> /// <param name="services">The servicecollection to configure</param> /// <param name="requestIfPermissionGranted">This will be called when permission is given to use GPS functionality (background permission is assumed when calling this - setting your GPS request to not use background is ignored)</param> /// <returns></returns> public static bool UseGps<T>(this IServiceCollection services, Action<GpsRequest> requestIfPermissionGranted = null) where T : class, IGpsDelegate => services.UseGps(typeof(T), requestIfPermissionGranted); } }
37
243
0.641101
[ "MIT" ]
SuavePirate/shiny
src/Shiny.Locations/Platforms/Shared/ServiceCollectionExtensions.cs
4,109
C#
// Licensed to the Apache Software Foundation(ASF) under one // or more contributor license agreements.See the NOTICE file // distributed with this work for additional information // regarding copyright ownership.The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Thrift; using Thrift.Collections; using Thrift.Processor; using Thrift.Protocol; using Thrift.Server; using Thrift.Transport; using Thrift.Transport.Server; namespace ThriftTest { internal enum ProtocolChoice { Binary, Compact, Json } internal enum TransportChoice { Socket, TlsSocket, NamedPipe } internal enum BufferChoice { None, Buffered, Framed } internal class ServerParam { internal BufferChoice buffering = BufferChoice.None; internal ProtocolChoice protocol = ProtocolChoice.Binary; internal TransportChoice transport = TransportChoice.Socket; internal int port = 9090; internal string pipe = null; internal void Parse(List<string> args) { for (var i = 0; i < args.Count; i++) { if (args[i].StartsWith("--pipe=")) { pipe = args[i].Substring(args[i].IndexOf("=") + 1); transport = TransportChoice.NamedPipe; } else if (args[i].StartsWith("--port=")) { port = int.Parse(args[i].Substring(args[i].IndexOf("=") + 1)); if(transport != TransportChoice.TlsSocket) transport = TransportChoice.Socket; } else if (args[i] == "-b" || args[i] == "--buffered" || args[i] == "--transport=buffered") { buffering = BufferChoice.Buffered; } else if (args[i] == "-f" || args[i] == "--framed" || args[i] == "--transport=framed") { buffering = BufferChoice.Framed; } else if (args[i] == "--binary" || args[i] == "--protocol=binary") { protocol = ProtocolChoice.Binary; } else if (args[i] == "--compact" || args[i] == "--protocol=compact") { protocol = ProtocolChoice.Compact; } else if (args[i] == "--json" || args[i] == "--protocol=json") { protocol = ProtocolChoice.Json; } else if (args[i] == "--threaded" || args[i] == "--server-type=threaded") { throw new NotImplementedException(args[i]); } else if (args[i] == "--threadpool" || args[i] == "--server-type=threadpool") { throw new NotImplementedException(args[i]); } else if (args[i] == "--prototype" || args[i] == "--processor=prototype") { throw new NotImplementedException(args[i]); } else if (args[i] == "--ssl") { transport = TransportChoice.TlsSocket; } else if (args[i] == "--help") { PrintOptionsHelp(); return; } else { Console.WriteLine("Invalid argument: {0}", args[i]); PrintOptionsHelp(); return; } } } internal static void PrintOptionsHelp() { Console.WriteLine("Server options:"); Console.WriteLine(" --pipe=<pipe name>"); Console.WriteLine(" --port=<port number>"); Console.WriteLine(" --transport=<transport name> one of buffered,framed (defaults to none)"); Console.WriteLine(" --protocol=<protocol name> one of compact,json (defaults to binary)"); Console.WriteLine(" --server-type=<type> one of threaded,threadpool (defaults to simple)"); Console.WriteLine(" --processor=<prototype>"); Console.WriteLine(" --ssl"); Console.WriteLine(); } } public class TestServer { public static int _clientID = -1; private static readonly TConfiguration Configuration = null; // or new TConfiguration() if needed public delegate void TestLogDelegate(string msg, params object[] values); public class MyServerEventHandler : TServerEventHandler { public int callCount = 0; public Task PreServeAsync(CancellationToken cancellationToken) { callCount++; return Task.CompletedTask; } public Task<object> CreateContextAsync(TProtocol input, TProtocol output, CancellationToken cancellationToken) { callCount++; return Task.FromResult<object>(null); } public Task DeleteContextAsync(object serverContext, TProtocol input, TProtocol output, CancellationToken cancellationToken) { callCount++; return Task.CompletedTask; } public Task ProcessContextAsync(object serverContext, TTransport transport, CancellationToken cancellationToken) { callCount++; return Task.CompletedTask; } } public class TestHandlerAsync : ThriftTest.IAsync { public TServer Server { get; set; } private readonly int handlerID; private readonly StringBuilder sb = new StringBuilder(); private readonly TestLogDelegate logger; public TestHandlerAsync() { handlerID = Interlocked.Increment(ref _clientID); logger += TestConsoleLogger; logger.Invoke("New TestHandler instance created"); } public void TestConsoleLogger(string msg, params object[] values) { sb.Clear(); sb.AppendFormat("handler{0:D3}:", handlerID); sb.AppendFormat(msg, values); sb.AppendLine(); Console.Write(sb.ToString()); } public Task testVoidAsync(CancellationToken cancellationToken) { logger.Invoke("testVoid()"); return Task.CompletedTask; } public Task<string> testStringAsync(string thing, CancellationToken cancellationToken) { logger.Invoke("testString({0})", thing); return Task.FromResult(thing); } public Task<bool> testBoolAsync(bool thing, CancellationToken cancellationToken) { logger.Invoke("testBool({0})", thing); return Task.FromResult(thing); } public Task<sbyte> testByteAsync(sbyte thing, CancellationToken cancellationToken) { logger.Invoke("testByte({0})", thing); return Task.FromResult(thing); } public Task<int> testI32Async(int thing, CancellationToken cancellationToken) { logger.Invoke("testI32({0})", thing); return Task.FromResult(thing); } public Task<long> testI64Async(long thing, CancellationToken cancellationToken) { logger.Invoke("testI64({0})", thing); return Task.FromResult(thing); } public Task<double> testDoubleAsync(double thing, CancellationToken cancellationToken) { logger.Invoke("testDouble({0})", thing); return Task.FromResult(thing); } public Task<byte[]> testBinaryAsync(byte[] thing, CancellationToken cancellationToken) { logger.Invoke("testBinary({0} bytes)", thing.Length); return Task.FromResult(thing); } public Task<Xtruct> testStructAsync(Xtruct thing, CancellationToken cancellationToken) { logger.Invoke("testStruct({{\"{0}\", {1}, {2}, {3}}})", thing.StringThing, thing.ByteThing, thing.I32Thing, thing.I64Thing); return Task.FromResult(thing); } public Task<Xtruct2> testNestAsync(Xtruct2 nest, CancellationToken cancellationToken) { var thing = nest.StructThing; logger.Invoke("testNest({{{0}, {{\"{1}\", {2}, {3}, {4}, {5}}}}})", nest.ByteThing, thing.StringThing, thing.ByteThing, thing.I32Thing, thing.I64Thing, nest.I32Thing); return Task.FromResult(nest); } public Task<Dictionary<int, int>> testMapAsync(Dictionary<int, int> thing, CancellationToken cancellationToken) { sb.Clear(); sb.Append("testMap({{"); var first = true; foreach (var key in thing.Keys) { if (first) { first = false; } else { sb.Append(", "); } sb.AppendFormat("{0} => {1}", key, thing[key]); } sb.Append("}})"); logger.Invoke(sb.ToString()); return Task.FromResult(thing); } public Task<Dictionary<string, string>> testStringMapAsync(Dictionary<string, string> thing, CancellationToken cancellationToken) { sb.Clear(); sb.Append("testStringMap({{"); var first = true; foreach (var key in thing.Keys) { if (first) { first = false; } else { sb.Append(", "); } sb.AppendFormat("{0} => {1}", key, thing[key]); } sb.Append("}})"); logger.Invoke(sb.ToString()); return Task.FromResult(thing); } public Task<THashSet<int>> testSetAsync(THashSet<int> thing, CancellationToken cancellationToken) { sb.Clear(); sb.Append("testSet({{"); var first = true; foreach (int elem in thing) { if (first) { first = false; } else { sb.Append(", "); } sb.AppendFormat("{0}", elem); } sb.Append("}})"); logger.Invoke(sb.ToString()); return Task.FromResult(thing); } public Task<List<int>> testListAsync(List<int> thing, CancellationToken cancellationToken) { sb.Clear(); sb.Append("testList({{"); var first = true; foreach (var elem in thing) { if (first) { first = false; } else { sb.Append(", "); } sb.AppendFormat("{0}", elem); } sb.Append("}})"); logger.Invoke(sb.ToString()); return Task.FromResult(thing); } public Task<Numberz> testEnumAsync(Numberz thing, CancellationToken cancellationToken) { logger.Invoke("testEnum({0})", thing); return Task.FromResult(thing); } public Task<long> testTypedefAsync(long thing, CancellationToken cancellationToken) { logger.Invoke("testTypedef({0})", thing); return Task.FromResult(thing); } public Task<Dictionary<int, Dictionary<int, int>>> testMapMapAsync(int hello, CancellationToken cancellationToken) { logger.Invoke("testMapMap({0})", hello); var mapmap = new Dictionary<int, Dictionary<int, int>>(); var pos = new Dictionary<int, int>(); var neg = new Dictionary<int, int>(); for (var i = 1; i < 5; i++) { pos[i] = i; neg[-i] = -i; } mapmap[4] = pos; mapmap[-4] = neg; return Task.FromResult(mapmap); } public Task<Dictionary<long, Dictionary<Numberz, Insanity>>> testInsanityAsync(Insanity argument, CancellationToken cancellationToken) { logger.Invoke("testInsanity()"); /** from ThriftTest.thrift: * So you think you've got this all worked, out eh? * * Creates a the returned map with these values and prints it out: * { 1 => { 2 => argument, * 3 => argument, * }, * 2 => { 6 => <empty Insanity struct>, }, * } * @return map<UserId, map<Numberz,Insanity>> - a map with the above values */ var first_map = new Dictionary<Numberz, Insanity>(); var second_map = new Dictionary<Numberz, Insanity>(); ; first_map[Numberz.TWO] = argument; first_map[Numberz.THREE] = argument; second_map[Numberz.SIX] = new Insanity(); var insane = new Dictionary<long, Dictionary<Numberz, Insanity>> { [1] = first_map, [2] = second_map }; return Task.FromResult(insane); } public Task<Xtruct> testMultiAsync(sbyte arg0, int arg1, long arg2, Dictionary<short, string> arg3, Numberz arg4, long arg5, CancellationToken cancellationToken) { logger.Invoke("testMulti()"); var hello = new Xtruct(); ; hello.StringThing = "Hello2"; hello.ByteThing = arg0; hello.I32Thing = arg1; hello.I64Thing = arg2; return Task.FromResult(hello); } public Task testExceptionAsync(string arg, CancellationToken cancellationToken) { logger.Invoke("testException({0})", arg); if (arg == "Xception") { var x = new Xception { ErrorCode = 1001, Message = arg }; throw x; } if (arg == "TException") { throw new TException(); } return Task.CompletedTask; } public Task<Xtruct> testMultiExceptionAsync(string arg0, string arg1, CancellationToken cancellationToken) { logger.Invoke("testMultiException({0}, {1})", arg0, arg1); if (arg0 == "Xception") { var x = new Xception { ErrorCode = 1001, Message = "This is an Xception" }; throw x; } if (arg0 == "Xception2") { var x = new Xception2 { ErrorCode = 2002, StructThing = new Xtruct { StringThing = "This is an Xception2" } }; throw x; } var result = new Xtruct { StringThing = arg1 }; return Task.FromResult(result); } public Task testOnewayAsync(int secondsToSleep, CancellationToken cancellationToken) { logger.Invoke("testOneway({0}), sleeping...", secondsToSleep); Task.Delay(secondsToSleep * 1000, cancellationToken).GetAwaiter().GetResult(); logger.Invoke("testOneway finished"); return Task.CompletedTask; } } private static X509Certificate2 GetServerCert() { var serverCertName = "server.p12"; var possiblePaths = new List<string> { "../../../keys/", "../../keys/", "../keys/", "keys/", }; string existingPath = null; foreach (var possiblePath in possiblePaths) { var path = Path.GetFullPath(possiblePath + serverCertName); if (File.Exists(path)) { existingPath = path; break; } } if (string.IsNullOrEmpty(existingPath)) { throw new FileNotFoundException($"Cannot find file: {serverCertName}"); } var cert = new X509Certificate2(existingPath, "thrift"); return cert; } public static int Execute(List<string> args) { using (var loggerFactory = new LoggerFactory()) //.AddConsole().AddDebug(); { var logger = loggerFactory.CreateLogger("Test"); try { var param = new ServerParam(); try { param.Parse(args); } catch (Exception ex) { Console.WriteLine("*** FAILED ***"); Console.WriteLine("Error while parsing arguments"); Console.WriteLine(ex.Message + " ST: " + ex.StackTrace); return 1; } // Endpoint transport (mandatory) TServerTransport trans; switch (param.transport) { case TransportChoice.NamedPipe: Debug.Assert(param.pipe != null); trans = new TNamedPipeServerTransport(param.pipe, Configuration); break; case TransportChoice.TlsSocket: var cert = GetServerCert(); if (cert == null || !cert.HasPrivateKey) { cert?.Dispose(); throw new InvalidOperationException("Certificate doesn't contain private key"); } trans = new TTlsServerSocketTransport(param.port, Configuration, cert, (sender, certificate, chain, errors) => true, null, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12); break; case TransportChoice.Socket: default: trans = new TServerSocketTransport(param.port, Configuration); break; } // Layered transport (mandatory) TTransportFactory transFactory = null; switch (param.buffering) { case BufferChoice.Framed: transFactory = new TFramedTransport.Factory(); break; case BufferChoice.Buffered: transFactory = new TBufferedTransport.Factory(); break; default: Debug.Assert(param.buffering == BufferChoice.None, "unhandled case"); transFactory = null; // no layered transprt break; } // Protocol (mandatory) TProtocolFactory proto; switch (param.protocol) { case ProtocolChoice.Compact: proto = new TCompactProtocol.Factory(); break; case ProtocolChoice.Json: proto = new TJsonProtocol.Factory(); break; case ProtocolChoice.Binary: default: proto = new TBinaryProtocol.Factory(); break; } // Processor var testHandler = new TestHandlerAsync(); var testProcessor = new ThriftTest.AsyncProcessor(testHandler); var processorFactory = new TSingletonProcessorFactory(testProcessor); TServer serverEngine = new TSimpleAsyncServer(processorFactory, trans, transFactory, transFactory, proto, proto, logger); //Server event handler var serverEvents = new MyServerEventHandler(); serverEngine.SetEventHandler(serverEvents); // Run it var where = (!string.IsNullOrEmpty(param.pipe)) ? "on pipe " + param.pipe : "on port " + param.port; Console.WriteLine("Starting the AsyncBaseServer " + where + " with processor TPrototypeProcessorFactory prototype factory " + (param.buffering == BufferChoice.Buffered ? " with buffered transport" : "") + (param.buffering == BufferChoice.Framed ? " with framed transport" : "") + (param.transport == TransportChoice.TlsSocket ? " with encryption" : "") + (param.protocol == ProtocolChoice.Compact ? " with compact protocol" : "") + (param.protocol == ProtocolChoice.Json ? " with json protocol" : "") + "..."); serverEngine.ServeAsync(CancellationToken.None).GetAwaiter().GetResult(); Console.ReadLine(); } catch (Exception x) { Console.Error.Write(x); return 1; } Console.WriteLine("done."); return 0; } } } }
37.601538
146
0.464097
[ "Apache-2.0" ]
RobberPhex/thrift
test/netstd/Server/TestServer.cs
24,441
C#
//----------------------------------------------------------------------- // <copyright file="Base64Encoding.cs" company="Akka.NET Project"> // Copyright (C) 2009-2018 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2018 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System.Text; namespace Akka.Util { /// <summary> /// TBD /// </summary> public static class Base64Encoding { /// <summary> /// TBD /// </summary> public const string Base64Chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+~"; /// <summary> /// TBD /// </summary> /// <param name="value">TBD</param> /// <returns>TBD</returns> public static string Base64Encode(this long value) => Base64Encode(value, new StringBuilder()).ToString(); /// <summary> /// TBD /// </summary> /// <param name="value">TBD</param> /// <returns>TBD</returns> public static StringBuilder Base64Encode(this long value, StringBuilder sb) { var next = value; do { var index = (int)(next & 63); sb.Append(Base64Chars[index]); next = next >> 6; } while (next != 0); return sb; } /// <summary> /// TBD /// </summary> /// <param name="s">TBD</param> /// <returns>TBD</returns> public static string Base64Encode(this string s) { var bytes = System.Text.Encoding.UTF8.GetBytes(s); return System.Convert.ToBase64String(bytes); } } }
30.288136
114
0.486849
[ "Apache-2.0" ]
Legacy07/akka.net
src/core/Akka/Util/Base64Encoding.cs
1,789
C#
// Copyright (c) Suity by HuangWei(4477289@qq.com) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Security; using System.Text; namespace Suity { /// <summary> /// 全局环境对象 /// </summary> public static class Environment { internal static Device _device = DefaultDevice.Default; /// <summary> /// 初始化设备 /// </summary> /// <param name="device"></param> public static void InitializeDevice(Device device) { if (device == null) { throw new ArgumentNullException(nameof(device)); } if (_device == device) { return; } if (!(_device is DefaultDevice)) { throw new SecurityException(); } _device = device; } /// <summary> /// 获取环境设置 /// </summary> /// <param name="key"></param> /// <returns></returns> public static string GetConfig(string key) => _device.GetEnvironmentConfig(key); /// <summary> /// 获取位置 /// </summary> public static string Location => _device.Location; /// <summary> /// 获取服务 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static T GetService<T>() where T : class { return _device.GetService(typeof(T)) as T; } /// <summary> /// 获取服务 /// </summary> /// <param name="type"></param> /// <returns></returns> public static object GetService(Type type) => _device.GetService(type); } }
25.123288
103
0.513631
[ "MIT" ]
simage3d/Suity.Engine.Runtime.V4
Source/Suity/Environment.cs
1,894
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations; namespace ErrorHandling.Shared { public class Berekening { public int Teller { get; set; } public decimal Noemer { get; set; } public decimal Uitkomst { get; set; } } }
21.647059
45
0.69837
[ "MIT" ]
mrasoftGithub/BlazorWebAPIServerControllers
Shared/Berekening.cs
370
C#
using System; /// <summary> /// Separates object construction from its representation. /// /// Separate the construction of a complex object from its representation so that /// the same construction process can create different representations. /// /// Frequence of use: 2 medium low. /// </summary> namespace DoFactory.GangOfFour.Builder.RealWorld { /// <summary> /// The 'ConcreteBuilder3' class /// </summary> class ScooterBuilder : IVehicleBuilder { public Vehicle Vehicle { get; } public ScooterBuilder() { Vehicle = new Vehicle("Scooter"); } public void BuildFrame() { Vehicle["frame"] = "Scooter Frame"; } public void BuildEngine() { Vehicle["engine"] = "50 cc"; } public void BuildWheels() { Vehicle["wheels"] = "2"; } public void BuildDoors() { Vehicle["doors"] = "0"; } } }
22.795455
81
0.55334
[ "MIT" ]
ivandrofly/Do-factory---.Net-Design-Pattern
Builder/RealWorld/ScooterBuilder.cs
1,005
C#
namespace NOption.Collections { using System.Collections.Generic; /// <summary> /// Represents a generic indexed collection of key/value pairs. /// </summary> /// <typeparam name="TKey"> /// The type of the keys in the dictionary. /// </typeparam> /// <typeparam name="TValue"> /// The type of the values in the dictionary. /// </typeparam> internal interface IOrderedDictionary<TKey, TValue> : IReadOnlyDictionary<TKey, TValue> , IDictionary<TKey, TValue> { /// <summary> /// Gets an <see cref="IList{T}"/> containing the keys of the /// <see cref="IOrderedDictionary{TKey,TValue}"/>. /// </summary> /// <returns> /// An <see cref="IList{T}"/> containing the keys of the object that /// implements <see cref="IOrderedDictionary{TKey,TValue}"/>. /// </returns> new IReadOnlyList<TKey> Keys { get; } /// <summary> /// Gets an <see cref="IList{T}"/> containing the values in the /// <see cref="IOrderedDictionary{TKey,TValue}"/>. /// </summary> /// <returns> /// An <see cref="IList{T}"/> containing the values in the object that /// implements <see cref="IOrderedDictionary{TKey,TValue}"/>. /// </returns> new IReadOnlyList<TValue> Values { get; } /// <summary> /// Gets the element at the specified index. /// </summary> /// <returns> /// The element with the specified key. /// </returns> /// <param name="index"> /// The index of the element to get or set. /// </param> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="index"/> is not in [0, <see cref="P:Count"/>). /// </exception> TValue GetAt(int index); /// <summary> /// Sets the element at the specified index. /// </summary> /// <returns> /// The element with the specified key. /// </returns> /// <param name="index"> /// The index of the element to get or set. /// </param> /// <param name="value"> /// The new value. /// </param> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="index"/> is not in [0, <see cref="P:Count"/>). /// </exception> void SetAt(int index, TValue value); /// <summary> /// Adds an element with the provided key and value to the /// <see cref="IOrderedDictionary{TKey,TValue}"/>. /// </summary> /// <param name="index"> /// The zero-based index at which the element should be inserted. /// </param> /// <param name="key"> /// The object to use as the key of the element to add. /// </param> /// <param name="value"> /// The object to use as the value of the element to add. /// </param> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="index"/> is less than 0 or greater than /// <see cref="P:Count"/>. /// </exception> /// <exception cref="System.ArgumentNullException"> /// <paramref name="key"/> is <see langword="null"/>. /// </exception> /// <exception cref="System.ArgumentException"> /// An element with the same key already exists in the /// <see cref="IOrderedDictionary{TKey,TValue}"/>. /// </exception> /// <exception cref="System.NotSupportedException"> /// The <see cref="IOrderedDictionary{TKey,TValue}"/> is read-only. /// </exception> void Insert(int index, TKey key, TValue value); /// <summary> /// Determines whether the <see cref="IOrderedDictionary{TKey,TValue}"/> /// contains a specific value. /// </summary> /// <param name="value"> /// The value to locate in the <see cref="IOrderedDictionary{TKey,TValue}"/>. /// The value can be null for reference types. /// </param> /// <returns> /// <see langword="true"/> if the <see cref="IOrderedDictionary{TKey,TValue}"/> /// contains an element with the specified value; otherwise, /// <see langword="false"/>. /// </returns> /// <remarks> /// <para> /// This method determines equality using the default equality comparer /// <see cref="EqualityComparer{T}.Default"/> for /// <typeparamref name="TValue"/>, the type of values in the dictionary. /// </para> /// <para> /// This method performs a linear search; therefore, the average /// execution time is proportional to <see cref="P:Count"/>. That /// is, this method is an <c>O(n)</c> operation, where <c>n</c> is /// <see cref="P:Count"/>. /// </para> /// </remarks> bool ContainsValue(TValue value); } }
40.173228
89
0.535672
[ "MIT" ]
gix/noption
Source/NOption/Collections/IOrderedDictionary.cs
5,102
C#
#pragma checksum "D:\CodingWork\Projects\NongMinGoProject\SimplCommerce\src\Modules\SimplCommerce.Module.PaymentStripe\Areas\PaymentStripe\Views\Shared\Components\StripeLanding\Default.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "1d3d779dc94ba3655fc714ea809b4da7369a7610" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Areas_PaymentStripe_Views_Shared_Components_StripeLanding_Default), @"mvc.1.0.view", @"/Areas/PaymentStripe/Views/Shared/Components/StripeLanding/Default.cshtml")] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #nullable restore #line 1 "D:\CodingWork\Projects\NongMinGoProject\SimplCommerce\src\Modules\SimplCommerce.Module.PaymentStripe\Areas\PaymentStripe\Views\_ViewImports.cshtml" using Microsoft.AspNetCore.Identity; #line default #line hidden #nullable disable #nullable restore #line 2 "D:\CodingWork\Projects\NongMinGoProject\SimplCommerce\src\Modules\SimplCommerce.Module.PaymentStripe\Areas\PaymentStripe\Views\_ViewImports.cshtml" using Microsoft.AspNetCore.Mvc.Localization; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"1d3d779dc94ba3655fc714ea809b4da7369a7610", @"/Areas/PaymentStripe/Views/Shared/Components/StripeLanding/Default.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"252a5853f5646565b6d19f2f67b215e8a2ab4af3", @"/Areas/PaymentStripe/Views/_ViewImports.cshtml")] public class Areas_PaymentStripe_Views_Shared_Components_StripeLanding_Default : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<SimplCommerce.Module.PaymentStripe.Areas.PaymentStripe.ViewModels.StripeCheckoutForm> { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-area", "PaymentStripe", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-controller", "Stripe", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Charge", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("method", "POST", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; #pragma warning restore 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { WriteLiteral("\r\n<label>Stripe</label>\r\n"); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "1d3d779dc94ba3655fc714ea809b4da7369a76105005", async() => { WriteLiteral("\r\n <script src=\"//checkout.stripe.com/v2/checkout.js\"\r\n class=\"stripe-button\"\r\n data-key=\""); #nullable restore #line 7 "D:\CodingWork\Projects\NongMinGoProject\SimplCommerce\src\Modules\SimplCommerce.Module.PaymentStripe\Areas\PaymentStripe\Views\Shared\Components\StripeLanding\Default.cshtml" Write(Model.PublicKey); #line default #line hidden #nullable disable WriteLiteral("\"\r\n data-locale=\"auto\"\r\n data-currency=\""); #nullable restore #line 9 "D:\CodingWork\Projects\NongMinGoProject\SimplCommerce\src\Modules\SimplCommerce.Module.PaymentStripe\Areas\PaymentStripe\Views\Shared\Components\StripeLanding\Default.cshtml" Write(Model.ISOCurrencyCode); #line default #line hidden #nullable disable WriteLiteral("\"\r\n data-description=\"Payment with Stripe\"\r\n data-amount=\""); #nullable restore #line 11 "D:\CodingWork\Projects\NongMinGoProject\SimplCommerce\src\Modules\SimplCommerce.Module.PaymentStripe\Areas\PaymentStripe\Views\Shared\Components\StripeLanding\Default.cshtml" Write(Model.Amount); #line default #line hidden #nullable disable WriteLiteral("\">\r\n </script>\r\n"); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Area = (string)__tagHelperAttribute_0.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Controller = (string)__tagHelperAttribute_1.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Action = (string)__tagHelperAttribute_2.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_2); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Method = (string)__tagHelperAttribute_3.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n"); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public IViewLocalizer Localizer { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<SimplCommerce.Module.PaymentStripe.Areas.PaymentStripe.ViewModels.StripeCheckoutForm> Html { get; private set; } } } #pragma warning restore 1591
73.304688
304
0.769903
[ "Apache-2.0" ]
Coopathon2019/03_NongMinGo
src/Modules/SimplCommerce.Module.PaymentStripe/obj/Debug/netcoreapp3.0/Razor/Areas/PaymentStripe/Views/Shared/Components/StripeLanding/Default.cshtml.g.cs
9,383
C#
using AutoMapper; using ContactWebApi.ViewModel; using Entity.Models; namespace ContactWebApi { /// <summary> /// Auto Mapper for View Model and Model /// </summary> public class AutoMapperProfile : Profile { /// <summary> /// Constructor /// </summary> public AutoMapperProfile() { CreateMap<ContactViewModel, Contact>(); } } }
19.761905
51
0.578313
[ "MIT" ]
amolg92/ContactWebAppProject
ContactAppWebApp/ContactWebApi/AutoMapperProfile.cs
417
C#
using System.Collections.Generic; namespace MongoDB.DeepUpdater { public class RootFluent<TDocument> : SingleFluent<TDocument, TDocument> { internal RootFluent(TDocument document) : base(document, new[] { new SingleContainer<TDocument>(document, new List<string>()) }) { } } }
26.583333
100
0.670846
[ "MIT" ]
andreabertin/MongoDB.DeepUpdater.CSharp
MongoDB.DeepUpdater/Fluents/RootFluent.cs
321
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; /// <summary> /// To pass a string we use a custom marshaller (Utf8StringToNative) to convert it /// from a utf8 string to a pointer. If we just pass it as a string it won't be utf8 encoded. /// /// To receive we have a special struct called Utf8StringPointer which can implicitly change /// the pointer to a utf8 string. /// </summary> internal class ConstCharType : BaseType { public override string TypeName => $"string"; public override string TypeNameFrom => $"Utf8StringPointer"; public override string AsArgument() => $"[MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] {Ref}{TypeName} {VarName}"; public override string Ref => ""; }
38.380952
161
0.746898
[ "MIT" ]
AlwaysTooLate/Facepunch.Steamworks
Generator/Types/ConstCharType.cs
808
C#
// <copyright file="ForceEditorView.xaml.cs" company="FT Software"> // Copyright (c) 2016. All rights reserved. // </copyright> // <author>Florian Thurnwald</author> namespace ProjektKatastrophenschutz.Views { using System.Windows; using System.Windows.Controls; using System.Windows.Input; using BSA.Core.Models; using ProjektKatastrophenschutz.Utils; using ProjektKatastrophenschutz.ViewModels; /// <summary> /// Interaction logic for ForceEditorView.xaml /// </summary> public partial class ForceEditorView : UserControl { public ForceEditorView() { this.InitializeComponent(); this.DataContextChanged += (sender, args) => this.RegisterInViewModel(); this.Loaded += (sender, args) => this.RegisterInViewModel(); } /// <summary> /// Join Database /// </summary> public ForceEditorViewModel ViewModel => this.DataContext as ForceEditorViewModel; /// <summary> /// Viewmodelcheck /// </summary> private void RegisterInViewModel() { var forceEditorViewModel = this.ViewModel; if (forceEditorViewModel != null) { forceEditorViewModel.View = this; } //ViewModel.LoadForcesJob(); } /// <summary> /// Person Datacontent on double Click /// </summary> private void PersonsDataGrid_OnMouseDoubleClick(object sender, MouseButtonEventArgs eventArgs) { // If the DataGrid is editable, comment out all lines of this method var person = Gui.GetObjectOfClickedDataGridRow<Person>(sender, eventArgs); if (person != null) { this.ViewModel.EditPerson(person); } } /// <summary> /// Person Datacontent on Right Click /// </summary> private void PersonsDataGrid_OnMouseRightButtonDown(object sender, MouseButtonEventArgs eventArgs) { var person = Gui.GetObjectOfClickedDataGridRow<Person>(sender, eventArgs); if (person == null) { return; } var contextMenu = new ContextMenu(); var editItem = new MenuItem {Header = "Editor für diese Person öffnen"}; editItem.Click += this.EditPersonContextMenuItem_OnClick; var deleteItem = new MenuItem {Header = "Person aus Liste löschen"}; deleteItem.Click += this.DeletePersonContextMenuItem_OnClick; var setAsLeaderItem = new MenuItem {Header = "Als Gruppenführer festlegen"}; setAsLeaderItem.Click += this.SetAsLeaderContextMenuItem_OnClick; contextMenu.Items.Add(editItem); contextMenu.Items.Add(deleteItem); contextMenu.Items.Add(setAsLeaderItem); contextMenu.IsOpen = true; } /// <summary> /// PersonEdit Menueitem on Click /// </summary> private void EditPersonContextMenuItem_OnClick(object sender, RoutedEventArgs e) { var person = this.ViewModel.SelectedPerson; if (person != null) { this.ViewModel.EditPerson(person); } } /// <summary> /// Delete Person on Click /// </summary> private void DeletePersonContextMenuItem_OnClick(object sender, RoutedEventArgs e) { var person = this.ViewModel.SelectedPerson; if (person != null) { this.ViewModel.DeletePerson(person); } } /// <summary> /// Set Person as Leader on Click /// </summary> private void SetAsLeaderContextMenuItem_OnClick(object sender, RoutedEventArgs e) { var person = this.ViewModel.SelectedPerson; if (person != null) { this.ViewModel.SetPersonAsLeader(person); } } /// <summary> /// Leaderbutton Datacontent on Click /// </summary> private void ToggleLeaderButton_OnClick(object sender, RoutedEventArgs eventArgs) { var person = Gui.GetObjectOfClickedControl<Button, Person>(sender); if (person != null) { this.ViewModel.ToggleLeader(person); } } //} // CsvExport.csvPersonWriter(list, force ); // Force force = this.ViewModel.Force; // var list = persons.Cast<Person>(); // var persons = this.ViewModel.PersonsView; //{ //private void CreatePrinterForceTextBlock_MouseLeftButtonUp(object sender, RoutedEventArgs e) } }
33.319444
106
0.578783
[ "MIT" ]
projekt-katastrophenschutz/emergency-management-tool
src/ProjektKatastrophenschutz/Views/ForceEditorView.xaml.cs
4,804
C#
using System.ComponentModel.DataAnnotations; namespace Indice.AspNetCore.Identity.Api.Models { /// <summary> /// Models the request of a user for email confirmation. /// </summary> public class ConfirmEmailRequest { /// <summary> /// The token. /// </summary> [Required(AllowEmptyStrings = false)] public string Token { get; set; } } }
23.705882
60
0.605459
[ "MIT" ]
ChristosAsvestopoulos/Indice.AspNet
src/Indice.AspNetCore.Identity/Features/IdentityServerApi/Models/Requests/ConfirmEmailRequest.cs
405
C#
namespace SharpVectors.Dom.Svg { /// <summary> /// The SvgAnimatedPathData interface supports elements which have a 'd' attribute which /// holds Svg path data, and supports the ability to animate that attribute. /// </summary> public interface ISvgAnimatedPathData { ISvgPathSegList PathSegList{get;} ISvgPathSegList NormalizedPathSegList{get;} ISvgPathSegList AnimatedPathSegList{get;} ISvgPathSegList AnimatedNormalizedPathSegList{get;} } }
31.866667
91
0.751046
[ "MIT", "BSD-3-Clause" ]
Altua/SharpVectors
Source/SharpVectorCore/Svg/Paths/ISvgAnimatedPathData.cs
478
C#
using System.Collections.Generic; using System.Net; using AutoMapper; using Microsoft.Extensions.Options; using Ridics.Authentication.DataContracts; using Vokabular.DataEntities.Database.Entities; using Vokabular.DataEntities.Database.Repositories; using Vokabular.MainService.Core.Communication; using Vokabular.MainService.Core.Utils; using Vokabular.MainService.Core.Works.Users; using Vokabular.MainService.DataContracts; using Vokabular.MainService.DataContracts.Contracts; using Vokabular.RestClient.Results; using Vokabular.Shared.DataEntities.UnitOfWork; using Vokabular.Shared.Options; using AuthChangeContactContract = Ridics.Authentication.DataContracts.ChangeContactContract; using AuthChangePasswordContract = Ridics.Authentication.DataContracts.User.ChangePasswordContract; using AuthChangeTwoFactorContract = Ridics.Authentication.DataContracts.User.ChangeTwoFactorContract; using AuthConfirmContactContract = Ridics.Authentication.DataContracts.ConfirmContactContract; using AuthContactContract = Ridics.Authentication.DataContracts.ContactContract; using AuthUserContract = Ridics.Authentication.DataContracts.User.UserContract; using UserContactContract = Vokabular.MainService.DataContracts.Contracts.UserContactContract; namespace Vokabular.MainService.Core.Managers { public class UserManager { private readonly UserRepository m_userRepository; private readonly CommunicationProvider m_communicationProvider; private readonly AuthenticationManager m_authenticationManager; private readonly UserDetailManager m_userDetailManager; private readonly IMapper m_mapper; private readonly CodeGenerator m_codeGenerator; private readonly RegistrationOption m_registrationOption; public UserManager(UserRepository userRepository, CommunicationProvider communicationProvider, AuthenticationManager authenticationManager, UserDetailManager userDetailManager, IMapper mapper, CodeGenerator codeGenerator, IOptions<RegistrationOption> registrationOption) { m_userRepository = userRepository; m_communicationProvider = communicationProvider; m_authenticationManager = authenticationManager; m_userDetailManager = userDetailManager; m_mapper = mapper; m_codeGenerator = codeGenerator; m_registrationOption = registrationOption.Value; } public int CreateNewUser(CreateUserContract data) { if (m_registrationOption.ReservedUsernames.Contains(data.UserName.ToLower())) { throw new MainServiceException(MainServiceErrorCode.ReservedUsernameError, $"Username '{data.UserName}' is reserved, cannot be used.", HttpStatusCode.BadRequest, data.UserName); } var userId = new CreateNewUserWork(m_userRepository, m_communicationProvider, data, m_codeGenerator).Execute(); return userId; } public int CreateUserIfNotExist(CreateUserIfNotExistContract data) { var userExternalId = data.ExternalId; var userInfo = new UpdateUserInfo(data.Username, data.FirstName, data.LastName); var authUserApiClient = m_communicationProvider.GetAuthUserApiClient(); var userRoles = authUserApiClient.GetRolesByUserAsync(userExternalId).GetAwaiter().GetResult(); var userId = new CreateOrUpdateUserIfNotExistWork(m_userRepository, userExternalId, userRoles, userInfo, m_codeGenerator).Execute(); return userId; } public void UpdateCurrentUser(UpdateUserContract data) { var user = m_authenticationManager.GetCurrentUser(); if (user.ExternalId == null) { throw new MainServiceException(MainServiceErrorCode.UserHasMissingExternalId, $"User with ID {user.Id} has missing ExternalID", HttpStatusCode.BadRequest, new object[] { user.Id } ); } var client = m_communicationProvider.GetAuthUserApiClient(); var authUser = client.GetUserAsync(user.ExternalId.Value).GetAwaiter().GetResult(); authUser.FirstName = data.FirstName; authUser.LastName = data.LastName; client.EditSelfAsync(user.ExternalId.Value, authUser).GetAwaiter().GetResult(); var updateUserInfo = new UpdateUserInfo(authUser.UserName, authUser.FirstName, authUser.LastName); new UpdateUserWork(m_userRepository, user.Id, updateUserInfo).Execute(); } public void UpdateUser(int userId, UpdateUserContract data) { var userExternalId = GetUserExternalId(userId); var client = m_communicationProvider.GetAuthUserApiClient(); var authUser = client.GetUserAsync(userExternalId).GetAwaiter().GetResult(); authUser.FirstName = data.FirstName; authUser.LastName = data.LastName; client.EditUserAsync(userExternalId, authUser).GetAwaiter().GetResult(); var updateUserInfo = new UpdateUserInfo(authUser.UserName, authUser.FirstName, authUser.LastName); new UpdateUserWork(m_userRepository, userId, updateUserInfo).Execute(); } public void UpdateUserContact(int userId, UpdateUserContactContract data) { var userExternalId = GetUserExternalId(userId); var contract = new AuthChangeContactContract { ContactType = m_mapper.Map<ContactTypeEnum>(data.ContactType), UserId = userExternalId, NewContactValue = data.NewContactValue }; var client = m_communicationProvider.GetAuthContactApiClient(); client.ChangeContactAsync(contract).GetAwaiter().GetResult(); } public void UpdateUserPassword(int userId, UpdateUserPasswordContract data) { var userExternalId = GetUserExternalId(userId); var contract = new AuthChangePasswordContract { OriginalPassword = data.OldPassword, Password = data.NewPassword }; var client = m_communicationProvider.GetAuthUserApiClient(); client.PasswordChangeAsync(userExternalId, contract).GetAwaiter().GetResult(); } public PagedResultList<UserDetailContract> GetUserList(int? start, int? count, string filterByName) { var startValue = PagingHelper.GetStart(start); var countValue = PagingHelper.GetCount(count); var client = m_communicationProvider.GetAuthUserApiClient(); var result = client.GetUserListAsync(startValue, countValue, filterByName).GetAwaiter().GetResult(); var userDetailContracts = m_mapper.Map<List<UserDetailContract>>(result.Items); m_userDetailManager.AddIdForExternalUsers(userDetailContracts); return new PagedResultList<UserDetailContract> { List = userDetailContracts, TotalCount = result.ItemsCount, }; } public IList<UserDetailContract> GetUserAutocomplete(string query, int? count) { if (query == null) query = string.Empty; var countValue = PagingHelper.GetAutocompleteCount(count); var client = m_communicationProvider.GetAuthUserApiClient(); var result = client.GetUserListAsync(0, countValue, query).GetAwaiter().GetResult(); var userDetailContracts = m_mapper.Map<List<UserDetailContract>>(result.Items); m_userDetailManager.AddIdForExternalUsers(userDetailContracts); return userDetailContracts; } public UserDetailContract GetUserDetail(int userId) { var dbResult = m_userRepository.InvokeUnitOfWork(x => x.FindById<User>(userId)); return m_userDetailManager.GetUserDetailContractForUser(dbResult); } public bool ConfirmContact(int userId, ConfirmUserContactContract data) { var contract = new AuthConfirmContactContract { UserId = GetUserExternalId(userId), ConfirmCode = data.ConfirmCode, ContactType = m_mapper.Map<ContactTypeEnum>(data.ContactType), }; var client = m_communicationProvider.GetAuthContactApiClient(); return client.ConfirmContactAsync(contract).GetAwaiter().GetResult(); } public void ResendConfirmCode(int userId, UserContactContract data) { var contract = new AuthContactContract { UserId = GetUserExternalId(userId), ContactType = m_mapper.Map<ContactTypeEnum>(data.ContactType), }; var client = m_communicationProvider.GetAuthContactApiClient(); client.ResendCodeAsync(contract).GetAwaiter().GetResult(); } public void SetTwoFactor(int userId, UpdateTwoFactorContract data) { var contract = new AuthChangeTwoFactorContract { TwoFactorIsEnabled = data.TwoFactorIsEnabled, }; var client = m_communicationProvider.GetAuthUserApiClient(); client.SetTwoFactorAsync(GetUserExternalId(userId), contract).GetAwaiter().GetResult(); } public void SelectTwoFactorProvider(int userId, UpdateTwoFactorProviderContract data) { var contract = new AuthChangeTwoFactorContract { TwoFactorProvider = data.TwoFactorProvider, }; var client = m_communicationProvider.GetAuthUserApiClient(); client.SelectTwoFactorProviderAsync(GetUserExternalId(userId), contract).GetAwaiter().GetResult(); } private int GetUserExternalId(int userId) { var user = m_userRepository.InvokeUnitOfWork(x => x.FindById<User>(userId)); if (user.ExternalId == null) { throw new MainServiceException(MainServiceErrorCode.UserHasMissingExternalId, $"User with ID {user.Id} has missing ExternalID", HttpStatusCode.BadRequest, new object[] { user.Id } ); } return user.ExternalId.Value; } public void ResetUserPassword(int userId) { var client = m_communicationProvider.GetAuthUserApiClient(); client.ResetUserPasswordAsync(GetUserExternalId(userId)).GetAwaiter().GetResult(); } } }
43.262097
193
0.675645
[ "BSD-3-Clause" ]
RIDICS/ITJakub
UJCSystem/Vokabular.MainService.Core/Managers/UserManager.cs
10,731
C#
using System; using System.Collections.Generic; using System.Linq; using Orchard.Environment; using Orchard.Layouts.Framework.Display; using Orchard.Layouts.Framework.Elements; using Orchard.Layouts.Framework.Harvesters; using Orchard.Layouts.Helpers; using Orchard.Layouts.Models; using Orchard.Layouts.Services; namespace Orchard.Layouts.Providers { public class BlueprintElementHarvester : Component, IElementHarvester { private readonly Work<IElementBlueprintService> _elementBlueprintService; private readonly Work<IElementManager> _elementManager; public BlueprintElementHarvester(Work<IElementBlueprintService> elementBlueprintService, Work<IElementManager> elementManager) { _elementBlueprintService = elementBlueprintService; _elementManager = elementManager; } public IEnumerable<ElementDescriptor> HarvestElements(HarvestElementsContext context) { if (context.IsHarvesting) return Enumerable.Empty<ElementDescriptor>(); var blueprints = _elementBlueprintService.Value.GetBlueprints().ToArray(); var query = from blueprint in blueprints let describeContext = new DescribeElementsContext {Content = context.Content, CacheVaryParam = "Blueprints", IsHarvesting = true } let baseElementDescriptor = _elementManager.Value.GetElementDescriptorByTypeName(describeContext, blueprint.BaseElementTypeName) let baseElement = _elementManager.Value.ActivateElement(baseElementDescriptor) select new ElementDescriptor( baseElement.Descriptor.ElementType, blueprint.ElementTypeName, T(blueprint.ElementDisplayName), T(!String.IsNullOrWhiteSpace(blueprint.ElementDescription) ? blueprint.ElementDescription : blueprint.ElementDisplayName), GetCategory(blueprint)) { EnableEditorDialog = false, IsSystemElement = false, CreatingDisplay = creatingDisplayContext => CreatingDisplay(creatingDisplayContext, blueprint), Displaying = displayContext => Displaying(displayContext, baseElement), StateBag = new Dictionary<string, object> { {"Blueprint", true}, {"ElementTypeName", baseElement.Descriptor.TypeName} } }; return query.ToArray(); } private static string GetCategory(ElementBlueprint blueprint) { return !String.IsNullOrWhiteSpace(blueprint.ElementCategory) ? blueprint.ElementCategory : "Blueprints"; } private void CreatingDisplay(ElementCreatingDisplayShapeContext context, ElementBlueprint blueprint) { var bluePrintState = ElementDataHelper.Deserialize(blueprint.BaseElementState); context.Element.Data = bluePrintState; } private void Displaying(ElementDisplayingContext context, Element element) { var drivers = _elementManager.Value.GetDrivers(element); foreach (var driver in drivers) { driver.Displaying(context); } if (element.Descriptor.Displaying != null) { element.Descriptor.Displaying(context); } } } }
47.232877
146
0.662413
[ "BSD-3-Clause" ]
1996dylanriley/Orchard
src/Orchard.Web/Modules/Orchard.Layouts/Providers/BlueprintElementHarvester.cs
3,450
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.HttpRepl.Resources; using Microsoft.HttpRepl.Suggestions; using Microsoft.Repl; using Microsoft.Repl.Commanding; using Microsoft.Repl.ConsoleHandling; using Microsoft.Repl.Parsing; namespace Microsoft.HttpRepl.Commands { public class ChangeDirectoryCommand : CommandWithStructuredInputBase<HttpState, ICoreParseResult> { protected override Task ExecuteAsync(IShellState shellState, HttpState programState, DefaultCommandInput<ICoreParseResult> commandInput, ICoreParseResult parseResult, CancellationToken cancellationToken) { commandInput = commandInput ?? throw new ArgumentNullException(nameof(commandInput)); shellState = shellState ?? throw new ArgumentNullException(nameof(shellState)); programState = programState ?? throw new ArgumentNullException(nameof(programState)); if (commandInput.Arguments.Count == 0 || string.IsNullOrEmpty(commandInput.Arguments[0]?.Text)) { shellState.ConsoleManager.WriteLine(programState.GetRelativePathString()); } else { string[] parts = commandInput.Arguments[0].Text.Replace('\\', '/').Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); if (commandInput.Arguments[0].Text.StartsWith("/", StringComparison.Ordinal)) { programState.PathSections.Clear(); } foreach (string part in parts) { switch (part) { case ".": break; case "..": if (programState.PathSections.Count > 0) { programState.PathSections.Pop(); } break; default: programState.PathSections.Push(part); break; } } // If there's no directory structure, we can't traverse it to find the relevant // metadata and display it. The command still succeeded as far as its impact on // future commands, so we can safely just skip this part. if (programState.Structure != null) { IDirectoryStructure s = programState.Structure.TraverseTo(programState.PathSections.Reverse()); string thisDirMethod = "[]"; bool hasRequestMethods = s.RequestInfo?.Methods?.Count > 0; bool hasDirectoryNames = s.DirectoryNames?.Any() == true; // If there's no RequestInfo/Methods AND there's no (sub)DirectoryNames, we currently // assume this must be an auto-generated directory and not one from a swagger definition if (!hasRequestMethods && !hasDirectoryNames) { string warningMessage = string.Format(Resources.Strings.ChangeDirectoryCommand_Warning_UnknownEndpoint, programState.GetRelativePathString()).SetColor(programState.WarningColor); shellState.ConsoleManager.WriteLine(warningMessage); } else if (hasRequestMethods) { thisDirMethod = s.RequestInfo.GetDirectoryMethodListing(); } shellState.ConsoleManager.WriteLine($"{programState.GetRelativePathString()} {thisDirMethod}"); } } return Task.CompletedTask; } public override CommandInputSpecification InputSpec { get; } = CommandInputSpecification.Create("cd") .MaximumArgCount(1) .Finish(); protected override string GetHelpDetails(IShellState shellState, HttpState programState, DefaultCommandInput<ICoreParseResult> commandInput, ICoreParseResult parseResult) { var help = new StringBuilder(); help.Append(Strings.Usage.Bold()); help.AppendLine("cd [directory]"); help.AppendLine(); help.AppendLine("Prints the current directory if no argument is specified, otherwise changes to the specified directory"); return help.ToString(); } public override string GetHelpSummary(IShellState shellState, HttpState programState) { return Resources.Strings.ChangeDirectoryCommand_HelpSummary; } protected override IEnumerable<string> GetArgumentSuggestionsForText(IShellState shellState, HttpState programState, ICoreParseResult parseResult, DefaultCommandInput<ICoreParseResult> commandInput, string normalCompletionString) { return ServerPathCompletion.GetCompletions(programState, normalCompletionString); } } }
45.17094
237
0.608704
[ "Apache-2.0" ]
lcpautotester/HttpRepl
src/Microsoft.HttpRepl/Commands/ChangeDirectoryCommand.cs
5,285
C#
using System; using System.ComponentModel; using Xamarin.Forms.Internals; namespace Xamarin.Forms { public class StackLayout : Layout<View>, IElementConfiguration<StackLayout> { public static readonly BindableProperty OrientationProperty = BindableProperty.Create(nameof(Orientation), typeof(StackOrientation), typeof(StackLayout), StackOrientation.Vertical, propertyChanged: (bindable, oldvalue, newvalue) => ((StackLayout)bindable).InvalidateLayout()); public static readonly BindableProperty SpacingProperty = BindableProperty.Create(nameof(Spacing), typeof(double), typeof(StackLayout), 6d, propertyChanged: (bindable, oldvalue, newvalue) => ((StackLayout)bindable).InvalidateLayout()); LayoutInformation _layoutInformation = new LayoutInformation(); readonly Lazy<PlatformConfigurationRegistry<StackLayout>> _platformConfigurationRegistry; public StackLayout() { _platformConfigurationRegistry = new Lazy<PlatformConfigurationRegistry<StackLayout>>(() => new PlatformConfigurationRegistry<StackLayout>(this)); } public IPlatformElementConfiguration<T, StackLayout> On<T>() where T : IConfigPlatform { return _platformConfigurationRegistry.Value.On<T>(); } public StackOrientation Orientation { get { return (StackOrientation)GetValue(OrientationProperty); } set { SetValue(OrientationProperty, value); } } public double Spacing { get { return (double)GetValue(SpacingProperty); } set { SetValue(SpacingProperty, value); } } protected override void LayoutChildren(double x, double y, double width, double height) { if (!HasVisibleChildren()) { return; } LayoutInformation layoutInformationCopy = _layoutInformation; if (width == layoutInformationCopy.Constraint.Width && height == layoutInformationCopy.Constraint.Height) { StackOrientation orientation = Orientation; AlignOffAxis(layoutInformationCopy, orientation, width, height); ProcessExpanders(layoutInformationCopy, orientation, x, y, width, height); } else { CalculateLayout(layoutInformationCopy, x, y, width, height, true); } for (var i = 0; i < LogicalChildrenInternal.Count; i++) { var child = (View)LogicalChildrenInternal[i]; if (child.IsVisible) LayoutChildIntoBoundingRegion(child, layoutInformationCopy.Plots[i], layoutInformationCopy.Requests[i]); } } [Obsolete("OnSizeRequest is obsolete as of version 2.2.0. Please use OnMeasure instead.")] [EditorBrowsable(EditorBrowsableState.Never)] protected override SizeRequest OnSizeRequest(double widthConstraint, double heightConstraint) { if (!HasVisibleChildren()) { return new SizeRequest(); } // calculate with padding inset for X,Y so we can hopefully re-use this in the layout pass Thickness padding = Padding; CalculateLayout(_layoutInformation, padding.Left, padding.Top, widthConstraint, heightConstraint, false); var result = new SizeRequest(_layoutInformation.Bounds.Size, _layoutInformation.MinimumSize); return result; } internal override void ComputeConstraintForView(View view) { ComputeConstraintForView(view, false); } internal override void InvalidateMeasureInternal(InvalidationTrigger trigger) { _layoutInformation = new LayoutInformation(); base.InvalidateMeasureInternal(trigger); } void AlignOffAxis(LayoutInformation layout, StackOrientation orientation, double widthConstraint, double heightConstraint) { for (var i = 0; i < layout.Plots.Length; i++) { if (!((View)LogicalChildrenInternal[i]).IsVisible) continue; if (orientation == StackOrientation.Vertical) { layout.Plots[i].Width = widthConstraint; } else { layout.Plots[i].Height = heightConstraint; } } } void CalculateLayout(LayoutInformation layout, double x, double y, double widthConstraint, double heightConstraint, bool processExpanders) { layout.Constraint = new Size(widthConstraint, heightConstraint); layout.Expanders = 0; layout.CompressionSpace = 0; layout.Plots = new Rectangle[Children.Count]; layout.Requests = new SizeRequest[Children.Count]; StackOrientation orientation = Orientation; CalculateNaiveLayout(layout, orientation, x, y, widthConstraint, heightConstraint); CompressNaiveLayout(layout, orientation, widthConstraint, heightConstraint); if (processExpanders) { AlignOffAxis(layout, orientation, widthConstraint, heightConstraint); ProcessExpanders(layout, orientation, x, y, widthConstraint, heightConstraint); } } void CalculateNaiveLayout(LayoutInformation layout, StackOrientation orientation, double x, double y, double widthConstraint, double heightConstraint) { layout.CompressionSpace = 0; double xOffset = x; double yOffset = y; double boundsWidth = 0; double boundsHeight = 0; double minimumWidth = 0; double minimumHeight = 0; double spacing = Spacing; if (orientation == StackOrientation.Vertical) { View expander = null; for (var i = 0; i < LogicalChildrenInternal.Count; i++) { var child = (View)LogicalChildrenInternal[i]; if (!child.IsVisible) continue; if (child.VerticalOptions.Expands) { layout.Expanders++; if (expander != null) { // we have multiple expanders, make sure previous expanders are reset to not be fixed because they no logner are ComputeConstraintForView(child, false); } expander = child; } SizeRequest request = child.Measure(widthConstraint, double.PositiveInfinity, MeasureFlags.IncludeMargins); var bounds = new Rectangle(x, yOffset, request.Request.Width, request.Request.Height); layout.Plots[i] = bounds; layout.Requests[i] = request; layout.CompressionSpace += Math.Max(0, request.Request.Height - request.Minimum.Height); yOffset = bounds.Bottom + spacing; boundsWidth = Math.Max(boundsWidth, request.Request.Width); boundsHeight = bounds.Bottom - y; minimumHeight += request.Minimum.Height + spacing; minimumWidth = Math.Max(minimumWidth, request.Minimum.Width); } minimumHeight -= spacing; if (expander != null) ComputeConstraintForView(expander, layout.Expanders == 1); // warning : slightly obtuse, but we either need to setup the expander or clear the last one } else { View expander = null; for (var i = 0; i < LogicalChildrenInternal.Count; i++) { var child = (View)LogicalChildrenInternal[i]; if (!child.IsVisible) continue; if (child.HorizontalOptions.Expands) { layout.Expanders++; if (expander != null) { ComputeConstraintForView(child, false); } expander = child; } SizeRequest request = child.Measure(double.PositiveInfinity, heightConstraint, MeasureFlags.IncludeMargins); var bounds = new Rectangle(xOffset, y, request.Request.Width, request.Request.Height); layout.Plots[i] = bounds; layout.Requests[i] = request; layout.CompressionSpace += Math.Max(0, request.Request.Width - request.Minimum.Width); xOffset = bounds.Right + spacing; boundsWidth = bounds.Right - x; boundsHeight = Math.Max(boundsHeight, request.Request.Height); minimumWidth += request.Minimum.Width + spacing; minimumHeight = Math.Max(minimumHeight, request.Minimum.Height); } minimumWidth -= spacing; if (expander != null) ComputeConstraintForView(expander, layout.Expanders == 1); } layout.Bounds = new Rectangle(x, y, boundsWidth, boundsHeight); layout.MinimumSize = new Size(minimumWidth, minimumHeight); } void CompressHorizontalLayout(LayoutInformation layout, double widthConstraint, double heightConstraint) { double xOffset = 0; if (widthConstraint >= layout.Bounds.Width) { // no need to compress return; } double requiredCompression = layout.Bounds.Width - widthConstraint; double compressionSpace = layout.CompressionSpace; double compressionPressure = (requiredCompression / layout.CompressionSpace).Clamp(0, 1); for (var i = 0; i < layout.Plots.Length; i++) { var child = (View)LogicalChildrenInternal[i]; if (!child.IsVisible) continue; Size minimum = layout.Requests[i].Minimum; layout.Plots[i].X -= xOffset; Rectangle plot = layout.Plots[i]; double availableSpace = plot.Width - minimum.Width; if (availableSpace <= 0) continue; compressionSpace -= availableSpace; double compression = availableSpace * compressionPressure; xOffset += compression; double newWidth = plot.Width - compression; SizeRequest newRequest = child.Measure(newWidth, heightConstraint, MeasureFlags.IncludeMargins); layout.Requests[i] = newRequest; plot.Height = newRequest.Request.Height; if (newRequest.Request.Width < newWidth) { double delta = newWidth - newRequest.Request.Width; newWidth = newRequest.Request.Width; xOffset += delta; requiredCompression = requiredCompression - xOffset; compressionPressure = (requiredCompression / compressionSpace).Clamp(0, 1); } plot.Width = newWidth; layout.Bounds.Height = Math.Max(layout.Bounds.Height, plot.Height); layout.Plots[i] = plot; } } void CompressNaiveLayout(LayoutInformation layout, StackOrientation orientation, double widthConstraint, double heightConstraint) { if (layout.CompressionSpace <= 0) return; if (orientation == StackOrientation.Vertical) { CompressVerticalLayout(layout, widthConstraint, heightConstraint); } else { CompressHorizontalLayout(layout, widthConstraint, heightConstraint); } } void CompressVerticalLayout(LayoutInformation layout, double widthConstraint, double heightConstraint) { double yOffset = 0; if (heightConstraint >= layout.Bounds.Height) { // no need to compress return; } double requiredCompression = layout.Bounds.Height - heightConstraint; double compressionSpace = layout.CompressionSpace; double compressionPressure = (requiredCompression / layout.CompressionSpace).Clamp(0, 1); for (var i = 0; i < layout.Plots.Length; i++) { var child = (View)LogicalChildrenInternal[i]; if (!child.IsVisible) continue; Size minimum = layout.Requests[i].Minimum; layout.Plots[i].Y -= yOffset; Rectangle plot = layout.Plots[i]; double availableSpace = plot.Height - minimum.Height; if (availableSpace <= 0) continue; compressionSpace -= availableSpace; double compression = availableSpace * compressionPressure; yOffset += compression; double newHeight = plot.Height - compression; SizeRequest newRequest = child.Measure(widthConstraint, newHeight, MeasureFlags.IncludeMargins); layout.Requests[i] = newRequest; plot.Width = newRequest.Request.Width; if (newRequest.Request.Height < newHeight) { double delta = newHeight - newRequest.Request.Height; newHeight = newRequest.Request.Height; yOffset += delta; requiredCompression = requiredCompression - yOffset; compressionPressure = (requiredCompression / compressionSpace).Clamp(0, 1); } plot.Height = newHeight; layout.Bounds.Width = Math.Max(layout.Bounds.Width, plot.Width); layout.Plots[i] = plot; } } void ComputeConstraintForView(View view, bool isOnlyExpander) { if (Orientation == StackOrientation.Horizontal) { if ((Constraint & LayoutConstraint.VerticallyFixed) != 0 && view.VerticalOptions.Alignment == LayoutAlignment.Fill) { if (isOnlyExpander && view.HorizontalOptions.Alignment == LayoutAlignment.Fill && Constraint == LayoutConstraint.Fixed) { view.ComputedConstraint = LayoutConstraint.Fixed; } else { view.ComputedConstraint = LayoutConstraint.VerticallyFixed; } } else { view.ComputedConstraint = LayoutConstraint.None; } } else { if ((Constraint & LayoutConstraint.HorizontallyFixed) != 0 && view.HorizontalOptions.Alignment == LayoutAlignment.Fill) { if (isOnlyExpander && view.VerticalOptions.Alignment == LayoutAlignment.Fill && Constraint == LayoutConstraint.Fixed) { view.ComputedConstraint = LayoutConstraint.Fixed; } else { view.ComputedConstraint = LayoutConstraint.HorizontallyFixed; } } else { view.ComputedConstraint = LayoutConstraint.None; } } } bool HasVisibleChildren() { for (var index = 0; index < InternalChildren.Count; index++) { var child = (VisualElement)InternalChildren[index]; if (child.IsVisible) return true; } return false; } void ProcessExpanders(LayoutInformation layout, StackOrientation orientation, double x, double y, double widthConstraint, double heightConstraint) { if (layout.Expanders <= 0) return; if (orientation == StackOrientation.Vertical) { double extraSpace = heightConstraint - layout.Bounds.Height; if (extraSpace <= 0) return; double spacePerExpander = extraSpace / layout.Expanders; double yOffset = 0; for (var i = 0; i < LogicalChildrenInternal.Count; i++) { var child = (View)LogicalChildrenInternal[i]; if (!child.IsVisible) continue; Rectangle plot = layout.Plots[i]; plot.Y += yOffset; if (child.VerticalOptions.Expands) { plot.Height += spacePerExpander; yOffset += spacePerExpander; } layout.Plots[i] = plot; } layout.Bounds.Height = heightConstraint; } else { double extraSpace = widthConstraint - layout.Bounds.Width; if (extraSpace <= 0) return; double spacePerExpander = extraSpace / layout.Expanders; double xOffset = 0; for (var i = 0; i < LogicalChildrenInternal.Count; i++) { var child = (View)LogicalChildrenInternal[i]; if (!child.IsVisible) continue; Rectangle plot = layout.Plots[i]; plot.X += xOffset; if (child.HorizontalOptions.Expands) { plot.Width += spacePerExpander; xOffset += spacePerExpander; } layout.Plots[i] = plot; } layout.Bounds.Width = widthConstraint; } } class LayoutInformation { public Rectangle Bounds; public double CompressionSpace; public Size Constraint; public int Expanders; public Size MinimumSize; public Rectangle[] Plots; public SizeRequest[] Requests; } } }
30.580169
182
0.704795
[ "MIT" ]
1iveowl/Xamarin.Forms
Xamarin.Forms.Core/StackLayout.cs
14,495
C#
using System; using System.Collections.Generic; using System.Text; namespace DiscordBot.MLAPI.Exceptions { public class ReqHandledException : Exception { } }
15.636364
48
0.744186
[ "MIT" ]
TheGrandCoding/discord-bo
DiscordBot/MLAPI/Exceptions/ReqHandledException.cs
174
C#
using ICU4N.Globalization; using Lucene.Net.Support; using Lucene.Net.Util; namespace Lucene.Net.Analysis.Icu.TokenAttributes { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ /// <summary> /// Implementation of <see cref="IScriptAttribute"/> that stores the script /// as an integer. /// <para/> /// @lucene.experimental /// </summary> public class ScriptAttribute : Attribute, IScriptAttribute // LUCENENET specific: Not implementing ICloneable per Microsoft's recommendation { private int code = UScript.Common; /// <summary>Initializes this attribute with <see cref="UScript.Common"/>.</summary> public ScriptAttribute() { } public virtual int Code { get => code; set => code = value; } public virtual string GetName() { return UScript.GetName(code); } [ExceptionToNetNumericConvention] public virtual string GetShortName() { return UScript.GetShortName(code); } public override void Clear() { code = UScript.Common; } public override void CopyTo(IAttribute target) { ScriptAttribute t = (ScriptAttribute)target; t.Code = code; } public override bool Equals(object other) { if (this == other) { return true; } if (other is ScriptAttribute scriptAttribute) { return scriptAttribute.code == code; } return false; } public override int GetHashCode() { return code; } public override void ReflectWith(IAttributeReflector reflector) { // when wordbreaking CJK, we use the 15924 code Japanese (Han+Hiragana+Katakana) to // mark runs of Chinese/Japanese. our use is correct (as for chinese Han is a subset), // but this is just to help prevent confusion. string name = code == UScript.Japanese ? "Chinese/Japanese" : GetName(); reflector.Reflect<IScriptAttribute>("script", name); } } }
32.105263
144
0.603607
[ "Apache-2.0" ]
10088/lucenenet
src/Lucene.Net.Analysis.ICU/Analysis/Icu/TokenAttributes/ScriptAttributeImpl.cs
3,052
C#
/** * Copyright (c) blueback * Released under the MIT License * @brief 検索。 */ /** BlueBack.Excel */ namespace BlueBack.Excel { /** Find */ public static class Find { /** CheckCellFromActiveSheet */ public static bool CheckCellFromActiveSheet(Excel a_excel,int a_x1,int a_y1,string a_text) { Result<string> t_cell_string = a_excel.TryGetCellStringFromActiveSheet(a_x1,a_y1); if(t_cell_string.value == a_text){ return true; }else{ return false; } } /** セル検索。上優先。 */ public static Result<CellPosition> FindCellTopPriorityFromActiveSheetRange(Excel a_excel,int a_x1,int a_y1,int a_x2,int a_y2,string a_text) { for(int yy=a_y1;yy<=a_y2;yy++){ for(int xx=a_x1;xx<=a_x2;xx++){ if(CheckCellFromActiveSheet(a_excel,xx,yy,a_text) == true){ //一致。 return new Result<CellPosition>(){ success = true, value = new CellPosition(xx,yy), }; }else{ //不一致。 } } } //未発見。 return new Result<CellPosition>(){ success = false, value = new CellPosition(0,0), }; } /** セル検索。左優先。 */ public static Result<CellPosition> FindCellLeftPriorityFromActiveSheetRange(Excel a_excel,int a_x1,int a_y1,int a_x2,int a_y2,string a_text) { for(int xx=a_x1;xx<=a_x2;xx++){ for(int yy=a_y1;yy<=a_y2;yy++){ if(CheckCellFromActiveSheet(a_excel,xx,yy,a_text) == true){ //一致。 return new Result<CellPosition>(){ success = true, value = new CellPosition(xx,yy), }; }else{ //不一致。 } } } //未発見。 return new Result<CellPosition>(){ success = false, value = new CellPosition(0,0), }; } /** セル検索。左上優先。 */ public static Result<CellPosition> FindCellLeftTopPriorityFromActiveSheetRange(Excel a_excel,int a_x,int a_y,int a_size,string a_text) { for(int t_size=1;t_size<a_size;t_size++){ //下。 { int yy = t_size - 1; for(int xx=0;xx<t_size;xx++){ if(CheckCellFromActiveSheet(a_excel,xx,yy,a_text) == true){ //一致。 return new Result<CellPosition>(){ success = true, value = new CellPosition(xx,yy), }; }else{ //不一致。 } } } //右。 { int xx = t_size - 1; for(int yy=0;yy<t_size-1;yy++){ if(CheckCellFromActiveSheet(a_excel,xx,yy,a_text) == true){ //一致。 return new Result<CellPosition>(){ success = true, value = new CellPosition(xx,yy), }; }else{ //不一致。 } } } } //未発見。 return new Result<CellPosition>(){ success = false, value = new CellPosition(0,0), }; } } }
20.075758
142
0.587925
[ "MIT" ]
bluebackblue/Excel
BlueBackExcel/Assets/UPM/Runtime/BlueBack/Excel/Find.cs
2,800
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // Types for awaiting Task and Task<T>. These types are emitted from Task{<T>}.GetAwaiter // and Task{<T>}.ConfigureAwait. They are meant to be used only by the compiler, e.g. // // await nonGenericTask; // ===================== // var $awaiter = nonGenericTask.GetAwaiter(); // if (!$awaiter.IsCompleted) // { // SPILL: // $builder.AwaitUnsafeOnCompleted(ref $awaiter, ref this); // return; // Label: // UNSPILL; // } // $awaiter.GetResult(); // // result += await genericTask.ConfigureAwait(false); // =================================================================================== // var $awaiter = genericTask.ConfigureAwait(false).GetAwaiter(); // if (!$awaiter.IsCompleted) // { // SPILL; // $builder.AwaitUnsafeOnCompleted(ref $awaiter, ref this); // return; // Label: // UNSPILL; // } // result += $awaiter.GetResult(); // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Diagnostics; using System.Diagnostics.Tracing; using System.Threading; using System.Threading.Tasks; #if !CORECLR using Internal.Threading.Tasks.Tracing; #endif // NOTE: For performance reasons, initialization is not verified. If a developer // incorrectly initializes a task awaiter, which should only be done by the compiler, // NullReferenceExceptions may be generated (the alternative would be for us to detect // this case and then throw a different exception instead). This is the same tradeoff // that's made with other compiler-focused value types like List<T>.Enumerator. namespace System.Runtime.CompilerServices { /// <summary>Provides an awaiter for awaiting a <see cref="System.Threading.Tasks.Task"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> public readonly struct TaskAwaiter : ICriticalNotifyCompletion, ITaskAwaiter { // WARNING: Unsafe.As is used to access the generic TaskAwaiter<> as TaskAwaiter. // Its layout must remain the same. /// <summary>The task being awaited.</summary> internal readonly Task m_task; /// <summary>Initializes the <see cref="TaskAwaiter"/>.</summary> /// <param name="task">The <see cref="System.Threading.Tasks.Task"/> to be awaited.</param> internal TaskAwaiter(Task task) { Debug.Assert(task != null, "Constructing an awaiter requires a task to await."); m_task = task; } /// <summary>Gets whether the task being awaited is completed.</summary> /// <remarks>This property is intended for compiler user rather than use directly in code.</remarks> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> public bool IsCompleted { get { return m_task.IsCompleted; } } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.InvalidOperationException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void OnCompleted(Action continuation) { OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: true); } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.InvalidOperationException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void UnsafeOnCompleted(Action continuation) { OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: false); } /// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task"/>.</summary> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <exception cref="System.Threading.Tasks.TaskCanceledException">The task was canceled.</exception> /// <exception cref="System.Exception">The task completed in a Faulted state.</exception> [StackTraceHidden] public void GetResult() { ValidateEnd(m_task); } /// <summary> /// Fast checks for the end of an await operation to determine whether more needs to be done /// prior to completing the await. /// </summary> /// <param name="task">The awaited task.</param> [StackTraceHidden] internal static void ValidateEnd(Task task) { // Fast checks that can be inlined. if (task.IsWaitNotificationEnabledOrNotRanToCompletion) { // If either the end await bit is set or we're not completed successfully, // fall back to the slower path. HandleNonSuccessAndDebuggerNotification(task); } } /// <summary> /// Ensures the task is completed, triggers any necessary debugger breakpoints for completing /// the await on the task, and throws an exception if the task did not complete successfully. /// </summary> /// <param name="task">The awaited task.</param> [StackTraceHidden] private static void HandleNonSuccessAndDebuggerNotification(Task task) { // NOTE: The JIT refuses to inline ValidateEnd when it contains the contents // of HandleNonSuccessAndDebuggerNotification, hence the separation. // Synchronously wait for the task to complete. When used by the compiler, // the task will already be complete. This code exists only for direct GetResult use, // for cases where the same exception propagation semantics used by "await" are desired, // but where for one reason or another synchronous rather than asynchronous waiting is needed. if (!task.IsCompleted) { bool taskCompleted = task.InternalWait(Timeout.Infinite, default); Debug.Assert(taskCompleted, "With an infinite timeout, the task should have always completed."); } // Now that we're done, alert the debugger if so requested task.NotifyDebuggerOfWaitCompletionIfNecessary(); // And throw an exception if the task is faulted or canceled. if (!task.IsCompletedSuccessfully) ThrowForNonSuccess(task); } /// <summary>Throws an exception to handle a task that completed in a state other than RanToCompletion.</summary> [StackTraceHidden] private static void ThrowForNonSuccess(Task task) { Debug.Assert(task.IsCompleted, "Task must have been completed by now."); Debug.Assert(task.Status != TaskStatus.RanToCompletion, "Task should not be completed successfully."); // Handle whether the task has been canceled or faulted switch (task.Status) { // If the task completed in a canceled state, throw an OperationCanceledException. // This will either be the OCE that actually caused the task to cancel, or it will be a new // TaskCanceledException. TCE derives from OCE, and by throwing it we automatically pick up the // completed task's CancellationToken if it has one, including that CT in the OCE. case TaskStatus.Canceled: var oceEdi = task.GetCancellationExceptionDispatchInfo(); if (oceEdi != null) { oceEdi.Throw(); Debug.Fail("Throw() should have thrown"); } throw new TaskCanceledException(task); // If the task faulted, throw its first exception, // even if it contained more than one. case TaskStatus.Faulted: var edis = task.GetExceptionDispatchInfos(); if (edis.Count > 0) { edis[0].Throw(); Debug.Fail("Throw() should have thrown"); break; // Necessary to compile: non-reachable, but compiler can't determine that } else { Debug.Fail("There should be exceptions if we're Faulted."); throw task.Exception; } } } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="task">The task being awaited.</param> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <param name="continueOnCapturedContext">Whether to capture and marshal back to the current context.</param> /// <param name="flowExecutionContext">Whether to flow ExecutionContext across the await.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> internal static void OnCompletedInternal(Task task, Action continuation, bool continueOnCapturedContext, bool flowExecutionContext) { if (continuation == null) throw new ArgumentNullException(nameof(continuation)); // If TaskWait* ETW events are enabled, trace a beginning event for this await // and set up an ending event to be traced when the asynchronous await completes. if ( #if CORECLR TplEtwProvider.Log.IsEnabled() || Task.s_asyncDebuggingEnabled #else TaskTrace.Enabled #endif ) { continuation = OutputWaitEtwEvents(task, continuation); } // Set the continuation onto the awaited task. task.SetContinuationForAwait(continuation, continueOnCapturedContext, flowExecutionContext); } #if CORECLR /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="task">The task being awaited.</param> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <param name="continueOnCapturedContext">Whether to capture and marshal back to the current context.</param> /// <param name="flowExecutionContext">Whether to flow ExecutionContext across the await.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> internal static void UnsafeOnCompletedInternal(Task task, IAsyncStateMachineBox stateMachineBox, bool continueOnCapturedContext) { Debug.Assert(stateMachineBox != null); // If TaskWait* ETW events are enabled, trace a beginning event for this await // and set up an ending event to be traced when the asynchronous await completes. if (TplEtwProvider.Log.IsEnabled() || Task.s_asyncDebuggingEnabled) { task.SetContinuationForAwait(OutputWaitEtwEvents(task, stateMachineBox.MoveNextAction), continueOnCapturedContext, flowExecutionContext: false); } else { task.UnsafeSetContinuationForAwait(stateMachineBox, continueOnCapturedContext); } } #endif /// <summary> /// Outputs a WaitBegin ETW event, and augments the continuation action to output a WaitEnd ETW event. /// </summary> /// <param name="task">The task being awaited.</param> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <returns>The action to use as the actual continuation.</returns> private static Action OutputWaitEtwEvents(Task task, Action continuation) { Debug.Assert(task != null, "Need a task to wait on"); Debug.Assert(continuation != null, "Need a continuation to invoke when the wait completes"); #if CORECLR if (Task.s_asyncDebuggingEnabled) { Task.AddToActiveTasks(task); } var etwLog = TplEtwProvider.Log; if (etwLog.IsEnabled()) { // ETW event for Task Wait Begin var currentTaskAtBegin = Task.InternalCurrent; // If this task's continuation is another task, get it. var continuationTask = AsyncMethodBuilderCore.TryGetContinuationTask(continuation); etwLog.TaskWaitBegin( (currentTaskAtBegin != null ? currentTaskAtBegin.m_taskScheduler.Id : TaskScheduler.Default.Id), (currentTaskAtBegin != null ? currentTaskAtBegin.Id : 0), task.Id, TplEtwProvider.TaskWaitBehavior.Asynchronous, (continuationTask != null ? continuationTask.Id : 0)); } #else Debug.Assert(TaskTrace.Enabled, "Should only be used when ETW tracing is enabled"); // ETW event for Task Wait Begin var currentTaskAtBegin = Task.InternalCurrent; TaskTrace.TaskWaitBegin_Asynchronous( (currentTaskAtBegin != null ? currentTaskAtBegin.m_taskScheduler.Id : TaskScheduler.Default.Id), (currentTaskAtBegin != null ? currentTaskAtBegin.Id : 0), task.Id); #endif // Create a continuation action that outputs the end event and then invokes the user // provided delegate. This incurs the allocations for the closure/delegate, but only if the event // is enabled, and in doing so it allows us to pass the awaited task's information into the end event // in a purely pay-for-play manner (the alternatively would be to increase the size of TaskAwaiter // just for this ETW purpose, not pay-for-play, since GetResult would need to know whether a real yield occurred). #if CORECLR return AsyncMethodBuilderCore.CreateContinuationWrapper(continuation, (innerContinuation,innerTask) => { if (Task.s_asyncDebuggingEnabled) { Task.RemoveFromActiveTasks(innerTask.Id); } TplEtwProvider innerEtwLog = TplEtwProvider.Log; // ETW event for Task Wait End. Guid prevActivityId = new Guid(); bool bEtwLogEnabled = innerEtwLog.IsEnabled(); if (bEtwLogEnabled) { var currentTaskAtEnd = Task.InternalCurrent; innerEtwLog.TaskWaitEnd( (currentTaskAtEnd != null ? currentTaskAtEnd.m_taskScheduler.Id : TaskScheduler.Default.Id), (currentTaskAtEnd != null ? currentTaskAtEnd.Id : 0), innerTask.Id); // Ensure the continuation runs under the activity ID of the task that completed for the // case the antecendent is a promise (in the other cases this is already the case). if (innerEtwLog.TasksSetActivityIds && (innerTask.Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0) EventSource.SetCurrentThreadActivityId(TplEtwProvider.CreateGuidForTaskID(innerTask.Id), out prevActivityId); } // Invoke the original continuation provided to OnCompleted. innerContinuation(); if (bEtwLogEnabled) { innerEtwLog.TaskWaitContinuationComplete(innerTask.Id); if (innerEtwLog.TasksSetActivityIds && (innerTask.Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0) EventSource.SetCurrentThreadActivityId(prevActivityId); } }, task); #else return () => { // ETW event for Task Wait End. if (TaskTrace.Enabled) { var currentTaskAtEnd = Task.InternalCurrent; TaskTrace.TaskWaitEnd( (currentTaskAtEnd != null ? currentTaskAtEnd.m_taskScheduler.Id : TaskScheduler.Default.Id), (currentTaskAtEnd != null ? currentTaskAtEnd.Id : 0), task.Id); } // Invoke the original continuation provided to OnCompleted. continuation(); }; #endif } } /// <summary>Provides an awaiter for awaiting a <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> public readonly struct TaskAwaiter<TResult> : ICriticalNotifyCompletion, ITaskAwaiter { // WARNING: Unsafe.As is used to access TaskAwaiter<> as the non-generic TaskAwaiter. // Its layout must remain the same. /// <summary>The task being awaited.</summary> private readonly Task<TResult> m_task; /// <summary>Initializes the <see cref="TaskAwaiter{TResult}"/>.</summary> /// <param name="task">The <see cref="System.Threading.Tasks.Task{TResult}"/> to be awaited.</param> internal TaskAwaiter(Task<TResult> task) { Debug.Assert(task != null, "Constructing an awaiter requires a task to await."); m_task = task; } /// <summary>Gets whether the task being awaited is completed.</summary> /// <remarks>This property is intended for compiler user rather than use directly in code.</remarks> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> public bool IsCompleted { get { return m_task.IsCompleted; } } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void OnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: true); } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void UnsafeOnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: false); } /// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary> /// <returns>The result of the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</returns> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <exception cref="System.Threading.Tasks.TaskCanceledException">The task was canceled.</exception> /// <exception cref="System.Exception">The task completed in a Faulted state.</exception> [StackTraceHidden] public TResult GetResult() { TaskAwaiter.ValidateEnd(m_task); return m_task.ResultOnSuccess; } } /// <summary> /// Marker interface used to know whether a particular awaiter is either a /// TaskAwaiter or a TaskAwaiter`1. It must not be implemented by any other /// awaiters. /// </summary> internal interface ITaskAwaiter { } /// <summary> /// Marker interface used to know whether a particular awaiter is either a /// CTA.ConfiguredTaskAwaiter or a CTA`1.ConfiguredTaskAwaiter. It must not /// be implemented by any other awaiters. /// </summary> internal interface IConfiguredTaskAwaiter { } /// <summary>Provides an awaitable object that allows for configured awaits on <see cref="System.Threading.Tasks.Task"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> public readonly struct ConfiguredTaskAwaitable { /// <summary>The task being awaited.</summary> private readonly ConfiguredTaskAwaitable.ConfiguredTaskAwaiter m_configuredTaskAwaiter; /// <summary>Initializes the <see cref="ConfiguredTaskAwaitable"/>.</summary> /// <param name="task">The awaitable <see cref="System.Threading.Tasks.Task"/>.</param> /// <param name="continueOnCapturedContext"> /// true to attempt to marshal the continuation back to the original context captured; otherwise, false. /// </param> internal ConfiguredTaskAwaitable(Task task, bool continueOnCapturedContext) { Debug.Assert(task != null, "Constructing an awaitable requires a task to await."); m_configuredTaskAwaiter = new ConfiguredTaskAwaitable.ConfiguredTaskAwaiter(task, continueOnCapturedContext); } /// <summary>Gets an awaiter for this awaitable.</summary> /// <returns>The awaiter.</returns> public ConfiguredTaskAwaitable.ConfiguredTaskAwaiter GetAwaiter() { return m_configuredTaskAwaiter; } /// <summary>Provides an awaiter for a <see cref="ConfiguredTaskAwaitable"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> public readonly struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion, IConfiguredTaskAwaiter { // WARNING: Unsafe.As is used to access the generic ConfiguredTaskAwaiter as this. // Its layout must remain the same. /// <summary>The task being awaited.</summary> internal readonly Task m_task; /// <summary>Whether to attempt marshaling back to the original context.</summary> internal readonly bool m_continueOnCapturedContext; /// <summary>Initializes the <see cref="ConfiguredTaskAwaiter"/>.</summary> /// <param name="task">The <see cref="System.Threading.Tasks.Task"/> to await.</param> /// <param name="continueOnCapturedContext"> /// true to attempt to marshal the continuation back to the original context captured /// when BeginAwait is called; otherwise, false. /// </param> internal ConfiguredTaskAwaiter(Task task, bool continueOnCapturedContext) { Debug.Assert(task != null, "Constructing an awaiter requires a task to await."); m_task = task; m_continueOnCapturedContext = continueOnCapturedContext; } /// <summary>Gets whether the task being awaited is completed.</summary> /// <remarks>This property is intended for compiler user rather than use directly in code.</remarks> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> public bool IsCompleted { get { return m_task.IsCompleted; } } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void OnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: true); } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void UnsafeOnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: false); } /// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task"/>.</summary> /// <returns>The result of the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</returns> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <exception cref="System.Threading.Tasks.TaskCanceledException">The task was canceled.</exception> /// <exception cref="System.Exception">The task completed in a Faulted state.</exception> [StackTraceHidden] public void GetResult() { TaskAwaiter.ValidateEnd(m_task); } } } /// <summary>Provides an awaitable object that allows for configured awaits on <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> public readonly struct ConfiguredTaskAwaitable<TResult> { /// <summary>The underlying awaitable on whose logic this awaitable relies.</summary> private readonly ConfiguredTaskAwaitable<TResult>.ConfiguredTaskAwaiter m_configuredTaskAwaiter; /// <summary>Initializes the <see cref="ConfiguredTaskAwaitable{TResult}"/>.</summary> /// <param name="task">The awaitable <see cref="System.Threading.Tasks.Task{TResult}"/>.</param> /// <param name="continueOnCapturedContext"> /// true to attempt to marshal the continuation back to the original context captured; otherwise, false. /// </param> internal ConfiguredTaskAwaitable(Task<TResult> task, bool continueOnCapturedContext) { m_configuredTaskAwaiter = new ConfiguredTaskAwaitable<TResult>.ConfiguredTaskAwaiter(task, continueOnCapturedContext); } /// <summary>Gets an awaiter for this awaitable.</summary> /// <returns>The awaiter.</returns> public ConfiguredTaskAwaitable<TResult>.ConfiguredTaskAwaiter GetAwaiter() { return m_configuredTaskAwaiter; } /// <summary>Provides an awaiter for a <see cref="ConfiguredTaskAwaitable{TResult}"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> public readonly struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion, IConfiguredTaskAwaiter { // WARNING: Unsafe.As is used to access this as the non-generic ConfiguredTaskAwaiter. // Its layout must remain the same. /// <summary>The task being awaited.</summary> private readonly Task<TResult> m_task; /// <summary>Whether to attempt marshaling back to the original context.</summary> private readonly bool m_continueOnCapturedContext; /// <summary>Initializes the <see cref="ConfiguredTaskAwaiter"/>.</summary> /// <param name="task">The awaitable <see cref="System.Threading.Tasks.Task{TResult}"/>.</param> /// <param name="continueOnCapturedContext"> /// true to attempt to marshal the continuation back to the original context captured; otherwise, false. /// </param> internal ConfiguredTaskAwaiter(Task<TResult> task, bool continueOnCapturedContext) { Debug.Assert(task != null, "Constructing an awaiter requires a task to await."); m_task = task; m_continueOnCapturedContext = continueOnCapturedContext; } /// <summary>Gets whether the task being awaited is completed.</summary> /// <remarks>This property is intended for compiler user rather than use directly in code.</remarks> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> public bool IsCompleted { get { return m_task.IsCompleted; } } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void OnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: true); } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void UnsafeOnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: false); } /// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary> /// <returns>The result of the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</returns> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <exception cref="System.Threading.Tasks.TaskCanceledException">The task was canceled.</exception> /// <exception cref="System.Exception">The task completed in a Faulted state.</exception> [StackTraceHidden] public TResult GetResult() { TaskAwaiter.ValidateEnd(m_task); return m_task.ResultOnSuccess; } } } }
56.183607
160
0.639998
[ "MIT" ]
L-Dogg/corefx
src/Common/src/CoreLib/System/Runtime/CompilerServices/TaskAwaiter.cs
34,272
C#
namespace LinkHelper { 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) { ChangeClipboardChain(this.Handle, nextClipboardViewer); 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.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm)); this.trayIcon = new System.Windows.Forms.NotifyIcon(this.components); this.label1 = new System.Windows.Forms.Label(); this.versionLabel = new System.Windows.Forms.Label(); this.linkLabel1 = new System.Windows.Forms.LinkLabel(); this.button1 = new System.Windows.Forms.Button(); this.label2 = new System.Windows.Forms.Label(); this.shortSize = new System.Windows.Forms.NumericUpDown(); this.label3 = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.shortSize)).BeginInit(); this.SuspendLayout(); // // trayIcon // this.trayIcon.BalloonTipIcon = System.Windows.Forms.ToolTipIcon.Info; this.trayIcon.BalloonTipText = "LinkHelper läuft!"; this.trayIcon.BalloonTipTitle = "LinkHelper wurde in den Hintergrund verschoben!"; this.trayIcon.Icon = ((System.Drawing.Icon)(resources.GetObject("trayIcon.Icon"))); this.trayIcon.Text = "LinkHelper"; this.trayIcon.Visible = true; this.trayIcon.DoubleClick += new System.EventHandler(this.onClick); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Arial", 20.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(12, 9); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(144, 32); this.label1.TabIndex = 0; this.label1.Text = "LinkHelper"; // // versionLabel // this.versionLabel.AutoSize = true; this.versionLabel.Font = new System.Drawing.Font("Arial", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.versionLabel.Location = new System.Drawing.Point(11, 41); this.versionLabel.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.versionLabel.Name = "versionLabel"; this.versionLabel.Size = new System.Drawing.Size(78, 16); this.versionLabel.TabIndex = 1; this.versionLabel.Text = "Version: %s"; // // linkLabel1 // this.linkLabel1.AutoSize = true; this.linkLabel1.Location = new System.Drawing.Point(11, 130); this.linkLabel1.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.linkLabel1.Name = "linkLabel1"; this.linkLabel1.Size = new System.Drawing.Size(165, 16); this.linkLabel1.TabIndex = 2; this.linkLabel1.TabStop = true; this.linkLabel1.Text = "by StefanArts Development"; this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked); // // button1 // this.button1.Location = new System.Drawing.Point(12, 104); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(156, 23); this.button1.TabIndex = 3; this.button1.Text = "Terminate LinkHelper"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(11, 85); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(110, 16); this.label2.TabIndex = 4; this.label2.Text = "Link Host: s-ls.de"; // // shortSize // this.shortSize.Location = new System.Drawing.Point(107, 60); this.shortSize.Maximum = new decimal(new int[] { 50, 0, 0, 0}); this.shortSize.Minimum = new decimal(new int[] { 25, 0, 0, 0}); this.shortSize.Name = "shortSize"; this.shortSize.Size = new System.Drawing.Size(63, 22); this.shortSize.TabIndex = 5; this.shortSize.Value = new decimal(new int[] { 25, 0, 0, 0}); this.shortSize.ValueChanged += new System.EventHandler(this.shortSize_ValueChanged); // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(11, 62); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(90, 16); this.label3.TabIndex = 6; this.label3.Text = "Shorting Size:"; // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.White; this.ClientSize = new System.Drawing.Size(180, 159); this.Controls.Add(this.label3); this.Controls.Add(this.shortSize); this.Controls.Add(this.label2); this.Controls.Add(this.button1); this.Controls.Add(this.linkLabel1); this.Controls.Add(this.versionLabel); this.Controls.Add(this.label1); this.Font = new System.Drawing.Font("Arial", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); this.Name = "MainForm"; this.ShowIcon = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "LinkHelper"; this.TopMost = true; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.onClose); this.Load += new System.EventHandler(this.MainForm_Load); ((System.ComponentModel.ISupportInitialize)(this.shortSize)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.NotifyIcon trayIcon; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label versionLabel; private System.Windows.Forms.LinkLabel linkLabel1; private System.Windows.Forms.Button button1; private System.Windows.Forms.Label label2; private System.Windows.Forms.NumericUpDown shortSize; private System.Windows.Forms.Label label3; } }
45.679558
159
0.583091
[ "Apache-2.0" ]
StefanArts/LinkHelper
MainForm.Designer.cs
8,271
C#
#pragma checksum "C:\Users\gabri\OneDrive\Documentos\GitHub\Last_Project_M03_BackEnd\CarStore\Views\Carro\Create.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "18b93b472f39b1c07e7da25e94ec46b7610e1e42" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Carro_Create), @"mvc.1.0.view", @"/Views/Carro/Create.cshtml")] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #nullable restore #line 1 "C:\Users\gabri\OneDrive\Documentos\GitHub\Last_Project_M03_BackEnd\CarStore\Views\_ViewImports.cshtml" using CarStore; #line default #line hidden #nullable disable #nullable restore #line 2 "C:\Users\gabri\OneDrive\Documentos\GitHub\Last_Project_M03_BackEnd\CarStore\Views\_ViewImports.cshtml" using CarStore.Models; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"18b93b472f39b1c07e7da25e94ec46b7610e1e42", @"/Views/Carro/Create.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"725beeeed864e424913aa610ea4dec60ab577d87", @"/Views/_ViewImports.cshtml")] public class Views_Carro_Create : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<Carro> { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("control-label"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("form-control"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("text-danger"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("btn btn-dark"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-area", "", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-controller", "Carro", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_6 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Index", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_7 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("role", new global::Microsoft.AspNetCore.Html.HtmlString("button"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_8 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("col-md-4"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_9 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Create", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; #pragma warning restore 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { WriteLiteral("\r\n<h2>Preencha os campos com os dados do veívulo </h2>\r\n"); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "18b93b472f39b1c07e7da25e94ec46b7610e1e427182", async() => { WriteLiteral("\r\n <div class=\"form-group\">\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "18b93b472f39b1c07e7da25e94ec46b7610e1e427482", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper); #nullable restore #line 6 "C:\Users\gabri\OneDrive\Documentos\GitHub\Last_Project_M03_BackEnd\CarStore\Views\Carro\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.marca); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "18b93b472f39b1c07e7da25e94ec46b7610e1e429088", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #nullable restore #line 7 "C:\Users\gabri\OneDrive\Documentos\GitHub\Last_Project_M03_BackEnd\CarStore\Views\Carro\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.marca); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "18b93b472f39b1c07e7da25e94ec46b7610e1e4210688", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); #nullable restore #line 8 "C:\Users\gabri\OneDrive\Documentos\GitHub\Last_Project_M03_BackEnd\CarStore\Views\Carro\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.marca); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "18b93b472f39b1c07e7da25e94ec46b7610e1e4212413", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper); #nullable restore #line 11 "C:\Users\gabri\OneDrive\Documentos\GitHub\Last_Project_M03_BackEnd\CarStore\Views\Carro\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.modelo); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "18b93b472f39b1c07e7da25e94ec46b7610e1e4214022", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #nullable restore #line 12 "C:\Users\gabri\OneDrive\Documentos\GitHub\Last_Project_M03_BackEnd\CarStore\Views\Carro\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.modelo); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "18b93b472f39b1c07e7da25e94ec46b7610e1e4215625", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); #nullable restore #line 13 "C:\Users\gabri\OneDrive\Documentos\GitHub\Last_Project_M03_BackEnd\CarStore\Views\Carro\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.modelo); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "18b93b472f39b1c07e7da25e94ec46b7610e1e4217352", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper); #nullable restore #line 16 "C:\Users\gabri\OneDrive\Documentos\GitHub\Last_Project_M03_BackEnd\CarStore\Views\Carro\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.preco); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "18b93b472f39b1c07e7da25e94ec46b7610e1e4218960", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #nullable restore #line 17 "C:\Users\gabri\OneDrive\Documentos\GitHub\Last_Project_M03_BackEnd\CarStore\Views\Carro\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.preco); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "18b93b472f39b1c07e7da25e94ec46b7610e1e4220562", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); #nullable restore #line 18 "C:\Users\gabri\OneDrive\Documentos\GitHub\Last_Project_M03_BackEnd\CarStore\Views\Carro\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.preco); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "18b93b472f39b1c07e7da25e94ec46b7610e1e4222288", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper); #nullable restore #line 21 "C:\Users\gabri\OneDrive\Documentos\GitHub\Last_Project_M03_BackEnd\CarStore\Views\Carro\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.ano); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "18b93b472f39b1c07e7da25e94ec46b7610e1e4223894", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #nullable restore #line 22 "C:\Users\gabri\OneDrive\Documentos\GitHub\Last_Project_M03_BackEnd\CarStore\Views\Carro\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.ano); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "18b93b472f39b1c07e7da25e94ec46b7610e1e4225494", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); #nullable restore #line 23 "C:\Users\gabri\OneDrive\Documentos\GitHub\Last_Project_M03_BackEnd\CarStore\Views\Carro\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.ano); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "18b93b472f39b1c07e7da25e94ec46b7610e1e4227218", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper); #nullable restore #line 26 "C:\Users\gabri\OneDrive\Documentos\GitHub\Last_Project_M03_BackEnd\CarStore\Views\Carro\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.url1); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "18b93b472f39b1c07e7da25e94ec46b7610e1e4228825", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #nullable restore #line 27 "C:\Users\gabri\OneDrive\Documentos\GitHub\Last_Project_M03_BackEnd\CarStore\Views\Carro\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.url1); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "18b93b472f39b1c07e7da25e94ec46b7610e1e4230426", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); #nullable restore #line 28 "C:\Users\gabri\OneDrive\Documentos\GitHub\Last_Project_M03_BackEnd\CarStore\Views\Carro\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.url1); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "18b93b472f39b1c07e7da25e94ec46b7610e1e4232151", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper); #nullable restore #line 31 "C:\Users\gabri\OneDrive\Documentos\GitHub\Last_Project_M03_BackEnd\CarStore\Views\Carro\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.descricao); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "18b93b472f39b1c07e7da25e94ec46b7610e1e4233763", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #nullable restore #line 32 "C:\Users\gabri\OneDrive\Documentos\GitHub\Last_Project_M03_BackEnd\CarStore\Views\Carro\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.descricao); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n </div>\r\n <div class=\"col-12\">\r\n <input type=\"submit\" class=\"btn btn-primary\" value=\"Criar!\" />\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "18b93b472f39b1c07e7da25e94ec46b7610e1e4235493", async() => { WriteLiteral("Voltar"); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_3); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Area = (string)__tagHelperAttribute_4.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Controller = (string)__tagHelperAttribute_5.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_5); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_6.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_6); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_7); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n </div>\r\n"); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_8); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Action = (string)__tagHelperAttribute_9.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_9); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n"); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<Carro> Html { get; private set; } } } #pragma warning restore 1591
77.570577
351
0.745681
[ "MIT" ]
Glightman/Last_Project_M03_BackEnd
CarStore/obj/Debug/net5.0/Razor/Views/Carro/Create.cshtml.g.cs
39,019
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/devicetopology.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace TerraFX.Interop { [Guid("BB11C46F-EC28-493C-B88A-5DB88062CE98")] [NativeTypeName("struct IAudioChannelConfig : IUnknown")] public unsafe partial struct IAudioChannelConfig { public void** lpVtbl; [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int QueryInterface([NativeTypeName("const IID &")] Guid* riid, [NativeTypeName("void **")] void** ppvObject) { return ((delegate* stdcall<IAudioChannelConfig*, Guid*, void**, int>)(lpVtbl[0]))((IAudioChannelConfig*)Unsafe.AsPointer(ref this), riid, ppvObject); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("ULONG")] public uint AddRef() { return ((delegate* stdcall<IAudioChannelConfig*, uint>)(lpVtbl[1]))((IAudioChannelConfig*)Unsafe.AsPointer(ref this)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("ULONG")] public uint Release() { return ((delegate* stdcall<IAudioChannelConfig*, uint>)(lpVtbl[2]))((IAudioChannelConfig*)Unsafe.AsPointer(ref this)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int SetChannelConfig([NativeTypeName("DWORD")] uint dwConfig, [NativeTypeName("LPCGUID")] Guid* pguidEventContext) { return ((delegate* stdcall<IAudioChannelConfig*, uint, Guid*, int>)(lpVtbl[3]))((IAudioChannelConfig*)Unsafe.AsPointer(ref this), dwConfig, pguidEventContext); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int GetChannelConfig([NativeTypeName("DWORD *")] uint* pdwConfig) { return ((delegate* stdcall<IAudioChannelConfig*, uint*, int>)(lpVtbl[4]))((IAudioChannelConfig*)Unsafe.AsPointer(ref this), pdwConfig); } } }
44.018519
171
0.682793
[ "MIT" ]
Ethereal77/terrafx.interop.windows
sources/Interop/Windows/um/devicetopology/IAudioChannelConfig.cs
2,379
C#
using System; using System.Collections.Generic; using System.Web.Http; using System.Web.Mvc; using System.Web.Routing; using System.Web.SessionState; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Web.WebApi; namespace Umbraco.Web.Mvc { internal static class AreaRegistrationExtensions { /// <summary> /// Creates a custom individual route for the specified controller plugin. Individual routes /// are required by controller plugins to map to a unique URL based on ID. /// </summary> /// <param name="globalSettings"></param> /// <param name="controllerName"></param> /// <param name="controllerType"></param> /// <param name="routes">An existing route collection</param> /// <param name="controllerSuffixName"> /// The suffix name that the controller name must end in before the "Controller" string for example: /// ContentTreeController has a controllerSuffixName of "Tree", this is used for route constraints. /// </param> /// <param name="defaultAction"></param> /// <param name="defaultId"></param> /// <param name="area"></param> /// <param name="umbracoTokenValue">The DataToken value to set for the 'umbraco' key, this defaults to 'backoffice' </param> /// <param name="routeTokens">By default this value is just {action}/{id} but can be modified for things like web api routes</param> /// <param name="isMvc">Default is true for MVC, otherwise false for WebAPI</param> /// <param name="areaPathPrefix"> /// If specified will add this string to the path between the umbraco path and the area path name, for example: /// /umbraco/CUSTOMPATHPREFIX/areaname /// if not specified, will just route like: /// /umbraco/areaname /// </param> /// <remarks> /// </remarks> internal static Route RouteControllerPlugin(this AreaRegistration area, IGlobalSettings globalSettings, string controllerName, Type controllerType, RouteCollection routes, string controllerSuffixName, string defaultAction, object defaultId, string umbracoTokenValue = "backoffice", string routeTokens = "{action}/{id}", bool isMvc = true, string areaPathPrefix = "") { if (controllerName == null) throw new ArgumentNullException(nameof(controllerName)); if (string.IsNullOrEmpty(controllerName)) throw new ArgumentException("Value can't be empty.", nameof(controllerName)); if (controllerSuffixName == null) throw new ArgumentNullException(nameof(controllerSuffixName)); if (controllerType == null) throw new ArgumentNullException(nameof(controllerType)); if (routes == null) throw new ArgumentNullException(nameof(routes)); if (defaultId == null) throw new ArgumentNullException(nameof(defaultId)); var umbracoArea = globalSettings.GetUmbracoMvcArea(); //routes are explicitly named with controller names and IDs var url = umbracoArea + "/" + (areaPathPrefix.IsNullOrWhiteSpace() ? "" : areaPathPrefix + "/") + area.AreaName + "/" + controllerName + "/" + routeTokens; Route controllerPluginRoute; //var meta = PluginController.GetMetadata(controllerType); if (isMvc) { //create a new route with custom name, specified url, and the namespace of the controller plugin controllerPluginRoute = routes.MapRoute( //name string.Format("umbraco-{0}-{1}", area.AreaName, controllerName), //url format url, //set the namespace of the controller to match new[] {controllerType.Namespace}); //set defaults controllerPluginRoute.Defaults = new RouteValueDictionary( new Dictionary<string, object> { {"controller", controllerName}, {"action", defaultAction}, {"id", defaultId} }); } else { controllerPluginRoute = routes.MapHttpRoute( //name string.Format("umbraco-{0}-{1}-{2}", "api", area.AreaName, controllerName), //url format url, new {controller = controllerName, id = defaultId}); //web api routes don't set the data tokens object if (controllerPluginRoute.DataTokens == null) { controllerPluginRoute.DataTokens = new RouteValueDictionary(); } //look in this namespace to create the controller controllerPluginRoute.DataTokens.Add("Namespaces", new[] {controllerType.Namespace}); //Special case! Check if the controller type implements IRequiresSessionState and if so use our //custom webapi session handler if (typeof(IRequiresSessionState).IsAssignableFrom(controllerType)) { controllerPluginRoute.RouteHandler = new SessionHttpControllerRouteHandler(); } } //Don't look anywhere else except this namespace! controllerPluginRoute.DataTokens.Add("UseNamespaceFallback", false); //constraints: only match controllers ending with 'controllerSuffixName' and only match this controller's ID for this route if (controllerSuffixName.IsNullOrWhiteSpace() == false) { controllerPluginRoute.Constraints = new RouteValueDictionary( new Dictionary<string, object> { {"controller", @"(\w+)" + controllerSuffixName} }); } //match this area controllerPluginRoute.DataTokens.Add("area", area.AreaName); controllerPluginRoute.DataTokens.Add(Core.Constants.Web.UmbracoDataToken, umbracoTokenValue); //ensure the umbraco token is set return controllerPluginRoute; } } }
48.165414
140
0.594287
[ "MIT" ]
AesisGit/Umbraco-CMS
src/Umbraco.Web/Mvc/AreaRegistrationExtensions.cs
6,408
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace server { public class AppSettings { public string JwtSecret { get; set; } public string AwsAccessKeyId { get; set; } public string AwsSecretAccessKey { get; set; } } }
20.866667
54
0.677316
[ "MIT" ]
Dara2004/EmployeeDirectory
amplify/backend/function/server/src/AppSettings.cs
315
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Globalization; using System.Text.RegularExpressions; namespace Microsoft.Build.BuildEngine.Shared { /// <summary> /// This class contains utility methods for file IO. /// Separate from FileUtilities because some assemblies may only need the patterns. /// PERF\COVERAGE NOTE: Try to keep classes in 'shared' as granular as possible. All the methods in /// each class get pulled into the resulting assembly. /// </summary> /// <owner>SumedhK, JomoF</owner> internal static class FileUtilitiesRegex { // regular expression used to match file-specs beginning with "<drive letter>:" internal static readonly Regex DrivePattern = new Regex(@"^[A-Za-z]:"); // regular expression used to match UNC paths beginning with "\\<server>\<share>" internal static readonly Regex UNCPattern = new Regex(String.Format(CultureInfo.InvariantCulture, @"^[\{0}\{1}][\{0}\{1}][^\{0}\{1}]+[\{0}\{1}][^\{0}\{1}]+", Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)); } }
44.321429
134
0.690572
[ "MIT" ]
0xced/msbuild
src/Deprecated/Engine/Shared/FileUtilitiesRegex.cs
1,241
C#
/* * IVS - project 2 - Calculator * Team Orient Express * Ac. y. 2019/20 */ /** * @file Math.cs * @author Samuel Olekšák * @brief File responsible for implementing math operations and constants * @return all functions return nullable decimal * @brief null represents an error (e.g. out of bounds, division by zero), non-null value is result */ using System; namespace MathComponentsNS { public class MathComponents { private decimal? error = null; public decimal constPI = (decimal)Math.PI; public decimal constE = (decimal)Math.E; /** * @return error/scientific notation if more than 9 whole places (?) * @brief truncates result to fit calc screen * @brief if less than 9 whole, leave all whole and truncate decimal to sum up to 9 max */ public decimal? TruncateToFit(decimal a) { int wholeDigits = (int)Math.Floor(1 + Math.Log10((double)Math.Abs(a))); if (wholeDigits > 9) return error; else if (a == 0) { return 0; } else if (Math.Abs(a) < 10) { decimal? result = (decimal)(Math.Truncate((double)a * 10e7) / 10e7); return result; } else { decimal? result = (decimal)(Math.Truncate((double)a * Math.Pow(10, 9 - wholeDigits)) / Math.Pow(10, 9 - wholeDigits)); return result; } } /** * @brief Addition operation function * @param[in] decimal first addend (a) * @param[in] decimal second addend (b) * @return sum (result of a + b) */ public decimal? Add(decimal a, decimal b) { decimal res = a + b; return TruncateToFit(res); } /** * @brief Subtraction operation function * @param[in] decimal minuend (a) * @param[in] decimal subtrahend (b) * @return difference (result of a - b) */ public decimal? Subtract(decimal a, decimal b) { decimal res = a - b; return TruncateToFit(res); } /** * @brief Multiplication operation function * @param[in] decimal first factor (a) * @param[in] decimal second factor (b) * @return product (result of a * b) */ public decimal? Multiply(decimal a, decimal b) { decimal res = a * b; return TruncateToFit(res); } /** * @brief Division operation function * @param[in] decimal dividend (a) * @param[in] decimal divisor (b) * @return quotient (result of a / b) * @return error if divisor is zero */ public decimal? Divide(decimal a, decimal b) { if (b == 0) return error; decimal res = a / b; return TruncateToFit(res); } /** * @brief non-integer exponent or base expect error (?) * @param[in] decimal base (b) * @param[in] decimal exponent (e) * @return result of b^e * @return error if 0^0 or 0^-1 */ public decimal? Exponentiate(decimal b, decimal e) { if ((b == 0 && e == 0) || (b == 0 && e == -1)) return error; if (e == 0) return (1m); /* if (e < 0) { decimal? part = Divide(1m, b); if (part.Item1) return error; b = part.Item2; e = -e; } */ decimal res = 0; try { res = (decimal)Math.Pow((double)b, (double)e); } catch (OverflowException exception) { return error; } return TruncateToFit(res); } /** * @brief Funtion of root to ath * @param[in] decimal degree d * @param[in] decimal radicand r * @return ath root of b * @return error if negative radicant */ public decimal? Root(decimal d, decimal r) { if (r < 0 || d == 0) return error; decimal res = (decimal)System.Math.Pow((double)r, 1d / (double)d); return TruncateToFit(res); } /** * @param[in] decimal argument (a) * @param[in] decimal base (b) * @brief Logarithm function * @brief expect log-argument positive * @brief expect base positive and different from 1 * @return log of a with base of b */ public decimal? Logarithm(decimal a, decimal b) { if (b <= 0 || b == 1 || a <= 0) return error; if (a == b) return 1; decimal res = (decimal)System.Math.Log((double)a, (double)b); return TruncateToFit(res); } /** * @brief sine function * @brief using Taylor series algorithm * @brief sin x = x − x^3/3! + x^5/5! − x^7/7! + ... * @param[in] decimal a * @return result with 5 decimal places precision */ public decimal? Sin(decimal a) { decimal res = (decimal)Math.Sin((double)a); /* decimal res = a; res -= Exponentiate(a, 3).Item2 / UnconstrainedFactorial(3).Item2; res += Exponentiate(a, 5).Item2 / UnconstrainedFactorial(5).Item2; res -= Exponentiate(a, 7).Item2 / UnconstrainedFactorial(7).Item2; res += Exponentiate(a, 9).Item2 / UnconstrainedFactorial(9).Item2; res -= Exponentiate(a, 11).Item2 / UnconstrainedFactorial(11).Item2; res += Exponentiate(a, 13).Item2 / UnconstrainedFactorial(13).Item2; res -= Exponentiate(a, 15).Item2 / UnconstrainedFactorial(15).Item2; res += Exponentiate(a, 17).Item2 / UnconstrainedFactorial(17).Item2; res -= Exponentiate(a, 19).Item2 / UnconstrainedFactorial(19).Item2; */ return TruncateToFit(res); } /** * @brief Function cosine * @brief using Taylor series algorithm * @brief cos x = 1 − x^2/2! + x^4/4! − x^6/6! + ... * @param[in] decimal number a * @return result with 5 decimal places precision (?) */ public decimal? Cos(decimal a) { decimal res = (decimal)Math.Cos((double)a); //decimal ress = (decimal)(Math.Round(res * 1e10d) / 1e10d); /* decimal res = 1; res -= Exponentiate(a, 2).Item2 / UnconstrainedFactorial(2).Item2; res += Exponentiate(a, 4).Item2 / UnconstrainedFactorial(4).Item2; res -= Exponentiate(a, 6).Item2 / UnconstrainedFactorial(6).Item2; res += Exponentiate(a, 8).Item2 / UnconstrainedFactorial(8).Item2; res -= Exponentiate(a, 10).Item2 / UnconstrainedFactorial(10).Item2; res += Exponentiate(a, 12).Item2 / UnconstrainedFactorial(12).Item2; res -= Exponentiate(a, 14).Item2 / UnconstrainedFactorial(14).Item2; res += Exponentiate(a, 16).Item2 / UnconstrainedFactorial(16).Item2; res -= Exponentiate(a, 18).Item2 / UnconstrainedFactorial(18).Item2; */ return TruncateToFit(res); } /** * @brief Function tangent * @param[in] decimal number a * @brief tan x = sin x / cos x * @return result with 5 decimal places precision (?) */ public decimal? Tan(decimal a) { double b = (double)a; if (b % Math.PI == Math.PI / 2d) return error; decimal res = (decimal)Math.Tan((double)a); return TruncateToFit(res); } /** * @brief Function arcsin * @param[in] decimal number a * @return result with 5 decimal places precision (?) * expect value between -pi/2 and pi/2 */ public decimal? Arcsin(decimal a) { if (a < -1.57079632679m || a > 1.57079632679m) return error; decimal res = (decimal)Math.Asin((double)a); return TruncateToFit(res); } /** * @brief Function arccos * @param[in] decimal number a * @return result with 5 decimal places precision (?) * @brief expect value between -1 and 1 */ public decimal? Arccos(decimal a) { if (a < -1 || a > 1) return error; decimal res = (decimal)Math.Acos((double)a); return TruncateToFit(res); } /** * @brief Function arctan * @param[in] decimal number a * @return result with 5 decimal places precision (?) */ public decimal? Arctan(decimal a) { decimal res = (decimal)Math.Atan((double)a); return TruncateToFit(res); } /** * @brief Factorial operation function * @param[in] decimal number a * @brief expect number non-negative integer not greater than 12 * @return error if a is negative integer * @return error if a is greater than 12 * @return error if a has decimal point */ public decimal? Factorial(decimal a) { if (a % 1 != 0 || a < 0 || a > 12) return error; else if (a == 0) return (1); else return (a * Factorial(a - 1)); } /** * @brief Factorial operation function without upper limit * @brief helper function, don't use in calculator * @param[in] decimal number a * @brief expect number non-negative integer * @return error if a is negative integer * @return error if a has decimal point */ public decimal? UnconstrainedFactorial(decimal a) { if (a % 1 != 0 || a < 0) return error; else if (a == 0) return 1; else return (a * UnconstrainedFactorial(a - 1)); } /** * @brief Function of random number * @brief generates random decimal number between 0 inclusive to 1 exclusive */ public decimal? Random() { decimal res = (decimal)new Random().NextDouble(); return TruncateToFit(res); } } }
32.051829
134
0.514981
[ "Unlicense" ]
leSamo/IVS-projekt
src/Kalkulacka/Math.cs
10,523
C#
using CartService.Database.Repositories.Interfaces; using MassTransit; using Microsoft.Extensions.Logging; using System; using System.Linq; using System.Threading.Tasks; using CartService.Contracts; namespace CartService.Consumers { public class AddCartPositionConsumer : IConsumer<AddCartPosition> { private readonly ILogger<AddCartPositionConsumer> _logger; private readonly ICartRepository _cartRepository; private readonly IGoodRepository _goodRepository; private readonly ICartPositionRepository _cartPositionRepository; private readonly Random _random; public AddCartPositionConsumer(ILogger<AddCartPositionConsumer> logger, ICartRepository cartRepository, IGoodRepository goodRepository, ICartPositionRepository cartPositionRepository) { _random = new Random(); _logger = logger; _cartRepository = cartRepository; _goodRepository = goodRepository; _cartPositionRepository = cartPositionRepository; } public async Task Consume(ConsumeContext<AddCartPosition> context) { var newCartPosition = context.Message; if (!await _cartRepository.CartExistsAsync(newCartPosition.OrderId)) { await _cartRepository.AddCartAsync(newCartPosition.OrderId); } if (!await _goodRepository.GoodExistsAsync(newCartPosition.Name)) { await _goodRepository.AddGoodAsync(Guid.NewGuid(), newCartPosition.Name, _random.Next(100, 150)); } var cart = await _cartRepository.GetCartWithCartPositionsAsync(newCartPosition.OrderId); var cartPosition = cart.CartPositions!.FirstOrDefault(cp => cp.Good!.Name == newCartPosition.Name); if (cartPosition != null) { await _cartPositionRepository.UpdateCartPositionAsync(cartPosition.Id, cartPosition.CartId, cartPosition.GoodId, cartPosition.Amount + newCartPosition.Amount); } else { var good = await _goodRepository.GetGoodByNameAsync(newCartPosition.Name); await _cartPositionRepository.AddCartPositionAsync(Guid.NewGuid(), newCartPosition.OrderId, good.Id, newCartPosition.Amount); } //to-do: respond } } }
35.550725
175
0.662454
[ "MIT" ]
konvovden/masstransit-demo
src/CartService/Consumers/AddCartPositionConsumer.cs
2,455
C#
#nullable enable using Content.Shared.Chemistry; using Robust.Server.Interfaces.GameObjects; using Robust.Shared.Interfaces.GameObjects; using Robust.Shared.Interfaces.Map; using Robust.Shared.IoC; using Robust.Shared.Map; namespace Content.Server.GameObjects.Components.Fluids { public static class SpillHelper { /// <summary> /// Spills the specified solution at the entity's location if possible. /// </summary> /// <param name="entity">Entity location to spill at</param> /// <param name="solution">Initial solution for the prototype</param> /// <param name="prototype">Prototype to use</param> /// <param name="sound">Play the spill sound</param> internal static void SpillAt(IEntity entity, Solution solution, string prototype, bool sound = true) { var entityLocation = entity.Transform.GridPosition; SpillAt(entityLocation, solution, prototype, sound); } // Other functions will be calling this one /// <summary> /// Spills solution at the specified grid co-ordinates /// </summary> /// <param name="gridCoordinates"></param> /// <param name="solution">Initial solution for the prototype</param> /// <param name="prototype">Prototype to use</param> /// <param name="sound">Play the spill sound</param> internal static PuddleComponent? SpillAt(GridCoordinates gridCoordinates, Solution solution, string prototype, bool sound = true) { if (solution.TotalVolume == 0) { return null; } var mapManager = IoCManager.Resolve<IMapManager>(); var entityManager = IoCManager.Resolve<IEntityManager>(); var serverEntityManager = IoCManager.Resolve<IServerEntityManager>(); var mapGrid = mapManager.GetGrid(gridCoordinates.GridID); // If space return early, let that spill go out into the void var tileRef = mapGrid.GetTileRef(gridCoordinates); if (tileRef.Tile.IsEmpty) { return null; } // Get normalized co-ordinate for spill location and spill it in the centre // TODO: Does SnapGrid or something else already do this? var spillTileMapGrid = mapManager.GetGrid(gridCoordinates.GridID); var spillTileRef = spillTileMapGrid.GetTileRef(gridCoordinates).GridIndices; var spillGridCoords = spillTileMapGrid.GridTileToLocal(spillTileRef); var spilt = false; foreach (var spillEntity in entityManager.GetEntitiesAt(spillTileMapGrid.ParentMapId, spillGridCoords.Position)) { if (!spillEntity.TryGetComponent(out PuddleComponent puddleComponent)) { continue; } if (!puddleComponent.TryAddSolution(solution, sound)) { continue; } spilt = true; break; } // Did we add to an existing puddle if (spilt) { return null; } var puddle = serverEntityManager.SpawnEntity(prototype, spillGridCoords); var newPuddleComponent = puddle.GetComponent<PuddleComponent>(); newPuddleComponent.TryAddSolution(solution, sound); return newPuddleComponent; } } }
36.604167
137
0.607854
[ "MIT" ]
Hughgent/space-station-14
Content.Server/GameObjects/Components/Fluids/SpillHelper.cs
3,514
C#
using Emgu.CV; using Emgu.CV.Structure; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PickandPlaceV2 { public class VideoProcessing { // work in progress // camera init private Emgu.CV.VideoCapture capture; public bool CameraHasData = false; public void StartCamera() { capture = new Emgu.CV.VideoCapture(); /* capture.SetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_AUTO_EXPOSURE, 0); capture.SetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_BRIGHTNESS, 33); capture.SetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_CONTRAST, 54); capture.SetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_EXPOSURE, -7); */ } public bool GetVideoData(System.Windows.Forms.PictureBox picturebox1, System.Windows.Forms.PictureBox picturebox2) { CameraHasData = false; /* frm.SetText(frm.Controls["textBoxImageY"], "0"); frm.SetText(frm.Controls["textBoxDeg"], "0"); frm.SetText(frm.Controls["textBoxImageX"], "0"); */ // capture.Start(); int cappturecounter = 1; while (!CameraHasData || cappturecounter <= 20) { GetCameraXY(picturebox1, picturebox2); cappturecounter++; } capture.Stop(); return true; } private void GetCameraXY(System.Windows.Forms.PictureBox picturebox1, System.Windows.Forms.PictureBox picturebox2) { /* Image<Bgr, Byte> frame = capture.QueryFrame(); //Image<Bgr, Byte> frame = new Image<Bgr, Byte>("Capture.jpg"); if (frame != null) { Image<Gray, Byte> gray = frame.Convert<Gray, Byte>(); double cannyThreshold = 180.0; double cannyThresholdLinking = 120.0; Image<Gray, Byte> cannyEdges = gray.Canny(cannyThreshold, cannyThresholdLinking); List<Triangle2DF> triangleList = new List<Triangle2DF>(); List<MCvBox2D> boxList = new List<MCvBox2D>(); //a box is a rotated rectangle using (MemStorage storage = new MemStorage()) //allocate storage for contour approximation for ( Contour<Point> contours = cannyEdges.FindContours( Emgu.CV.CvEnum.CHAIN_APPROX_METHOD.CV_CHAIN_APPROX_SIMPLE, Emgu.CV.CvEnum.RETR_TYPE.CV_RETR_LIST, storage); contours != null; contours = contours.HNext) { Contour<Point> currentContour = contours.ApproxPoly(contours.Perimeter * 0.05, storage); if (currentContour.Area > 400 && currentContour.Area < 20000) //only consider contours with area greater than 250 { if (currentContour.Total == 4) //The contour has 4 vertices. { // determine if all the angles in the contour are within [80, 100] degree bool isRectangle = true; Point[] pts = currentContour.ToArray(); LineSegment2D[] edges = PointCollection.PolyLine(pts, true); for (int i = 0; i < edges.Length; i++) { double angle = Math.Abs( edges[(i + 1) % edges.Length].GetExteriorAngleDegree(edges[i])); if (angle < 80 || angle > 100) { isRectangle = false; break; } } if (isRectangle) boxList.Add(currentContour.GetMinAreaRect()); } } } Image<Bgr, Byte> triangleRectangleImage = frame.CopyBlank(); foreach (Triangle2DF triangle in triangleList) triangleRectangleImage.Draw(triangle, new Bgr(Color.DarkBlue), 2); foreach (MCvBox2D box in boxList) { frm.SetText(frm.Controls["textBoxImageY"], box.center.Y.ToString()); frm.SetText(frm.Controls["textBoxDeg"], box.angle.ToString()); frm.SetText(frm.Controls["textBoxImageX"], box.center.X.ToString()); CameraHasData = true; triangleRectangleImage.Draw(box, new Bgr(Color.DarkOrange), 2); } // add cross hairs to image int totalwidth = frame.Width; int totalheight = frame.Height; PointF[] linepointshor = new PointF[] { new PointF(0, totalheight/2), new PointF(totalwidth, totalheight/2) }; PointF[] linepointsver = new PointF[] { new PointF(totalwidth/2, 0), new PointF(totalwidth/2, totalheight) }; triangleRectangleImage.DrawPolyline(Array.ConvertAll<PointF, Point>(linepointshor, Point.Round), false, new Bgr(Color.AntiqueWhite), 1); triangleRectangleImage.DrawPolyline(Array.ConvertAll<PointF, Point>(linepointsver, Point.Round), false, new Bgr(Color.AntiqueWhite), 1); picturebox2.Image = triangleRectangleImage.ToBitmap(); frame.DrawPolyline(Array.ConvertAll<PointF, Point>(linepointshor, Point.Round), false, new Bgr(Color.AntiqueWhite), 1); frame.DrawPolyline(Array.ConvertAll<PointF, Point>(linepointsver, Point.Round), false, new Bgr(Color.AntiqueWhite), 1); picturebox1.Image = frame.ToBitmap(); } */ } } }
43.212329
152
0.519892
[ "MIT" ]
briandorey/DIY-Pick-and-Place-Software
PickandPlaceV2/VideoProcessing.cs
6,311
C#
// Copyright (c) Daniel Crenna. All rights reserved. // // 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 http://mozilla.org/MPL/2.0/. using System.Collections.Concurrent; using Microsoft.Extensions.Logging; namespace BetterAPI.Logging { internal sealed class LightningLoggerProvider : ILoggerProvider { private readonly ConcurrentDictionary<string, LightningLogger> _loggers = new ConcurrentDictionary<string, LightningLogger>(); private readonly LightningLoggingStore _store; public LightningLoggerProvider(LightningLoggingStore store) { _store = store; } public ILogger CreateLogger(string categoryName) { return _loggers.GetOrAdd(categoryName, name => new LightningLogger(_store)); } public void Dispose() { _loggers.Clear(); } } }
29.823529
88
0.670611
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
danielcrenna/BetterAPI
src/BetterAPI/Logging/LightningLoggerProvider.cs
1,016
C#
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using System.Collections.Generic; using System.Linq; using Velentr.Audio.Sounds; using Velentr.Audio.Tagging; using IUpdateable = Velentr.Audio.Helpers.IUpdateable; namespace Velentr.Audio.Playlists { /// <summary> /// List of plays. /// </summary> /// /// <seealso cref="Velentr.Audio.Helpers.IUpdateable"/> public class Playlist : IUpdateable { /// <summary> /// The music. /// </summary> public Dictionary<string, PlaylistMusicInfo> Music; /// <summary> /// The playlist paused tags. /// </summary> public TagSet PlaylistPausedTags; /// <summary> /// The playlist valid tags. /// </summary> public TagSet PlaylistValidTags; /// <summary> /// The current music name. /// </summary> protected string _currentMusicName; /// <summary> /// Constructor. /// </summary> /// /// <param name="manager"> The manager. </param> /// <param name="name"> The name. </param> /// <param name="randomize"> (Optional) True to randomize. </param> /// <param name="maxTriesToAvoidRepeats"> (Optional) The maximum tries to avoid repeats. </param> /// <param name="playlistValidTags"> (Optional) The playlist valid tags. </param> /// <param name="playlistPausedTags"> (Optional) The playlist paused tags. </param> internal Playlist(AudioManager manager, string name, bool randomize = true, int maxTriesToAvoidRepeats = 3, TagSet? playlistValidTags = null, TagSet? playlistPausedTags = null) { Manager = manager; Name = name; Randomize = randomize; MaxTriesToAvoidRepeats = maxTriesToAvoidRepeats; _currentMusicName = string.Empty; PlaylistValidTags = playlistValidTags ?? new TagSet(); PlaylistPausedTags = playlistPausedTags ?? new TagSet(); Music = new Dictionary<string, PlaylistMusicInfo>(); IsPaused = false; PlaylistType = PlaylistType.Normal; } /// <summary> /// Gets or sets a value indicating whether this object is paused. /// </summary> /// /// <value> /// True if this object is paused, false if not. /// </value> public bool IsPaused { get; internal set; } /// <summary> /// Gets the manager. /// </summary> /// /// <value> /// The manager. /// </value> public AudioManager Manager { get; } /// <summary> /// Gets or sets the maximum tries to avoid repeats. /// </summary> /// /// <value> /// The maximum tries to avoid repeats. /// </value> public int MaxTriesToAvoidRepeats { get; set; } /// <summary> /// Gets the name. /// </summary> /// /// <value> /// The name. /// </value> public string Name { get; } /// <summary> /// Gets or sets a value indicating whether the randomize. /// </summary> /// /// <value> /// True if randomize, false if not. /// </value> public bool Randomize { get; set; } /// <summary> /// Gets or sets the type of the playlist. /// </summary> /// /// <value> /// The type of the playlist. /// </value> public PlaylistType PlaylistType { get; protected set; } /// <summary> /// Adds a playlist music to 'tags'. /// </summary> /// /// <param name="name"> The name. </param> /// <param name="tags"> The tags. </param> public void AddPlaylistMusic(string name, TagSet tags) { AddPlaylistMusic(new PlaylistMusicInfo(name, tags)); } /// <summary> /// Adds a playlist music to 'tags'. /// </summary> /// /// <param name="name"> The name. </param> /// <param name="tags"> (Optional) The tags. </param> /// <param name="exclusionTags"> (Optional) The exclusion tags. </param> /// <param name="requiredTags"> (Optional) The required tags. </param> public void AddPlaylistMusic(string name, List<string> tags = null, List<string> exclusionTags = null, List<string> requiredTags = null) { AddPlaylistMusic(new PlaylistMusicInfo(name, tags, exclusionTags, requiredTags)); } /// <summary> /// Adds a playlist music to 'tags'. /// </summary> /// /// <param name="music"> The music. </param> public void AddPlaylistMusic(PlaylistMusicInfo music) { Music.Add(music.Name, music); } /// <summary> /// Adds a playlist paused tag. /// </summary> /// /// <param name="tag"> The tag. </param> /// <param name="tagType"> Type of the tag. </param> public void AddPlaylistPausedTag(string tag, TagType tagType) { PlaylistPausedTags.AddTag(tag, tagType); } /// <summary> /// Adds a playlist paused tag. /// </summary> /// /// <param name="tags"> The tags. </param> /// <param name="tagType"> Type of the tag. </param> public void AddPlaylistPausedTag(List<string> tags, TagType tagType) { PlaylistPausedTags.AddTag(tags, tagType); } /// <summary> /// Adds a playlist paused tag. /// </summary> /// /// <param name="tags"> The tags. </param> public void AddPlaylistPausedTag(List<(string, TagType)> tags) { PlaylistPausedTags.AddTag(tags); } /// <summary> /// Adds a playlist valid tag. /// </summary> /// /// <param name="tag"> The tag. </param> /// <param name="tagType"> Type of the tag. </param> public void AddPlaylistValidTag(string tag, TagType tagType) { PlaylistValidTags.AddTag(tag, tagType); } /// <summary> /// Adds a playlist valid tag. /// </summary> /// /// <param name="tags"> The tags. </param> /// <param name="tagType"> Type of the tag. </param> public void AddPlaylistValidTag(List<string> tags, TagType tagType) { PlaylistValidTags.AddTag(tags, tagType); } /// <summary> /// Adds a playlist valid tag. /// </summary> /// /// <param name="tags"> The tags. </param> public void AddPlaylistValidTag(List<(string, TagType)> tags) { PlaylistValidTags.AddTag(tags); } /// <summary> /// Pauses this object. /// </summary> public virtual void Pause() { var instances = Manager.GetAudioInstances(Manager.MusicCategory.GetPlaylistAudioInstances(Name), true); for (var i = 0; i < instances.Count; i++) { instances[i].Pause(); } IsPaused = true; } /// <summary> /// Removes the playlist music described by name. /// </summary> /// /// <param name="name"> The name. </param> /// /// <returns> /// True if it succeeds, false if it fails. /// </returns> public bool RemovePlaylistMusic(string name) { return Music.Remove(name); } /// <summary> /// Removes the playlist paused tag described by tags. /// </summary> /// /// <param name="tag"> The tag. </param> /// <param name="tagType"> Type of the tag. </param> /// /// <returns> /// A List&lt;bool&gt; /// </returns> public bool RemovePlaylistPausedTag(string tag, TagType tagType) { return PlaylistPausedTags.RemoveTag(tag, tagType); } /// <summary> /// Removes the playlist paused tag described by tags. /// </summary> /// /// <param name="tags"> The tags. </param> /// <param name="tagType"> Type of the tag. </param> /// /// <returns> /// A List&lt;bool&gt; /// </returns> public List<bool> RemovePlaylistPausedTag(List<string> tags, TagType tagType) { return PlaylistPausedTags.RemoveTag(tags, tagType); } /// <summary> /// Removes the playlist paused tag described by tags. /// </summary> /// /// <param name="tags"> The tags. </param> /// /// <returns> /// A List&lt;bool&gt; /// </returns> public List<bool> RemovePlaylistPausedTag(List<(string, TagType)> tags) { return PlaylistPausedTags.RemoveTag(tags); } /// <summary> /// Removes the playlist valid tag described by tags. /// </summary> /// /// <param name="tag"> The tag. </param> /// <param name="tagType"> Type of the tag. </param> /// /// <returns> /// A List&lt;bool&gt; /// </returns> public bool RemovePlaylistValidTag(string tag, TagType tagType) { return PlaylistValidTags.RemoveTag(tag, tagType); } /// <summary> /// Removes the playlist valid tag described by tags. /// </summary> /// /// <param name="tags"> The tags. </param> /// <param name="tagType"> Type of the tag. </param> /// /// <returns> /// A List&lt;bool&gt; /// </returns> public List<bool> RemovePlaylistValidTag(List<string> tags, TagType tagType) { return PlaylistValidTags.RemoveTag(tags, tagType); } /// <summary> /// Removes the playlist valid tag described by tags. /// </summary> /// /// <param name="tags"> The tags. </param> /// /// <returns> /// A List&lt;bool&gt; /// </returns> public List<bool> RemovePlaylistValidTag(List<(string, TagType)> tags) { return PlaylistValidTags.RemoveTag(tags); } /// <summary> /// Determine if we should playlist be paused. /// </summary> /// /// <param name="currentTags"> The current tags. </param> /// /// <returns> /// True if it succeeds, false if it fails. /// </returns> public bool ShouldPlaylistBePaused(List<Tag> currentTags) { return PlaylistPausedTags.IsValid(currentTags); } /// <summary> /// Determine if we should playlist be played. /// </summary> /// /// <param name="currentTags"> The current tags. </param> /// /// <returns> /// True if it succeeds, false if it fails. /// </returns> public bool ShouldPlaylistBePlayed(List<Tag> currentTags) { return PlaylistValidTags.IsValid(currentTags); } /// <summary> /// Determine if we should playlist be stopped. /// </summary> /// /// <param name="currentTags"> The current tags. </param> /// /// <returns> /// True if it succeeds, false if it fails. /// </returns> public bool ShouldPlaylistBeStopped(List<Tag> currentTags) { return !(ShouldPlaylistBePlayed(currentTags) || ShouldPlaylistBePaused(currentTags)); } /// <summary> /// Stops this object. /// </summary> public virtual void Stop() { var instances = Manager.GetAudioInstances(Manager.MusicCategory.GetPlaylistAudioInstances(Name), true); for (var i = 0; i < instances.Count; i++) { instances[i].Stop(true); } Manager.RemoveAudioInstances(instances.Select(x => x.ID).ToList(), AudioManager.MUSIC_CATEGORY); IsPaused = false; } /// <summary> /// Updates the class. /// </summary> /// /// <param name="gameTime"> The game time. </param> /// /// <seealso cref="IUpdateable.Update(GameTime)"/> public virtual void Update(GameTime gameTime) { var instances = Manager.GetAudioInstancesForCategory(AudioManager.MUSIC_CATEGORY); var newMusic = instances.Count == 0; var instancestoKill = new List<ulong>(); for (var i = 0; i < instances.Count; i++) { if (instances[i].State == SoundState.Stopped) { instancestoKill.Add(instances[i].ID); if (instances[i].Name.Equals(_currentMusicName)) { _currentMusicName = string.Empty; newMusic = true; } } else if (instances[i].State == SoundState.Paused) { instances[i].Resume(); } } Manager.RemoveAudioInstances(instancestoKill, AudioManager.MUSIC_CATEGORY); Manager.MusicCategory.UnRegisterInstance(instancestoKill); if (newMusic) { var categoryTags = Manager.MusicCategory.GetCurrentTags(); var associatedMusic = Manager.GetPlaylistMusic(Music.Keys.ToList()); if (associatedMusic.Count == 0) { _currentMusicName = string.Empty; } else { var validMusic = new List<(Music, List<Tag>)>(); for (var i = 0; i < associatedMusic.Count; i++) { if (Music[associatedMusic[i].Name].Tags.IsValid(categoryTags, out var validTags)) { validMusic.Add((associatedMusic[i], validTags)); } } if (validMusic.Count == 0) { _currentMusicName = string.Empty; } else if (validMusic.Count == 1) { _currentMusicName = associatedMusic[0].Name; Manager.GenerateNewAudioInstance(_currentMusicName, AudioManager.MUSIC_CATEGORY, true); } else { var itemId = 0; if (Randomize) { for (var i = 0; i < MaxTriesToAvoidRepeats; i++) { itemId = Manager.Randomizer.GetNextRandomInt(0, associatedMusic.Count, true); if (!_currentMusicName.Equals(associatedMusic[itemId].Name)) { break; } } } else { itemId = -1; if (!string.IsNullOrEmpty(_currentMusicName)) { itemId = associatedMusic.FindIndex(x => x.Name == _currentMusicName); } if (itemId == -1 || itemId >= associatedMusic.Count - 1) { itemId = 0; } else { itemId++; } } _currentMusicName = associatedMusic[itemId].Name; Manager.GenerateNewAudioInstance(associatedMusic[itemId].Name, AudioManager.MUSIC_CATEGORY); } } } } } }
34.164609
184
0.479403
[ "MIT" ]
vonderborch/Velentr.Audio
Velentr.Audio/Playlists/Playlist.cs
16,606
C#
#region License /* * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * */ #endregion using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Data; using System.Globalization; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using Common.Logging; using Quartz.Impl.Matchers; using Quartz.Impl.Triggers; using Quartz.Spi; using Quartz.Util; namespace Quartz.Impl.AdoJobStore { /// <summary> /// This is meant to be an abstract base class for most, if not all, <see cref="IDriverDelegate" /> /// implementations. Subclasses should override only those methods that need /// special handling for the DBMS driver in question. /// </summary> /// <author><a href="mailto:jeff@binaryfeed.org">Jeffrey Wescott</a></author> /// <author>James House</author> /// <author>Marko Lahma (.NET)</author> public class StdAdoDelegate : StdAdoConstants, IDriverDelegate { protected const int DefaultTriggersToAcquireLimit = 5; protected ILog logger; protected string tablePrefix = DefaultTablePrefix; protected string instanceId; protected string schedName; protected bool useProperties; protected IDbProvider dbProvider; protected readonly ITypeLoadHelper typeLoadHelper; protected AdoUtil adoUtil; protected IList<ITriggerPersistenceDelegate> triggerPersistenceDelegates = new List<ITriggerPersistenceDelegate>(); /// <summary> /// Create new StdAdoDelegate instance. /// </summary> /// <param name="logger">the logger to use during execution</param> /// <param name="tablePrefix">the prefix of all table names</param> /// <param name="instanceId">The instance id.</param> /// <param name="dbProvider">The db provider.</param> public StdAdoDelegate(ILog logger, string tablePrefix, string schedName, string instanceId, IDbProvider dbProvider, ITypeLoadHelper typeLoadHelper) { this.logger = logger; this.tablePrefix = tablePrefix; this.schedName = schedName; this.instanceId = instanceId; this.dbProvider = dbProvider; this.typeLoadHelper = typeLoadHelper; adoUtil = new AdoUtil(dbProvider); AddDefaultTriggerPersistenceDelegates(); } /// <summary> /// Create new StdAdoDelegate instance. /// </summary> /// <param name="logger">the logger to use during execution</param> /// <param name="tablePrefix">the prefix of all table names</param> /// <param name="instanceId">The instance id.</param> /// <param name="dbProvider">The db provider.</param> /// <param name="useProperties">if set to <c>true</c> [use properties].</param> public StdAdoDelegate(ILog logger, string tablePrefix, string schedName, string instanceId, IDbProvider dbProvider, ITypeLoadHelper typeLoadHelper, bool useProperties) { this.logger = logger; this.tablePrefix = tablePrefix; this.schedName = schedName; this.instanceId = instanceId; this.dbProvider = dbProvider; this.typeLoadHelper = typeLoadHelper; adoUtil = new AdoUtil(dbProvider); this.useProperties = useProperties; AddDefaultTriggerPersistenceDelegates(); } /// <summary> /// initStrings are of the format: /// settingName=settingValue|otherSettingName=otherSettingValue|... /// </summary> public void Initialize(string initString) { if (initString == null) { return; } string[] settings = initString.Split('\\', '|'); foreach (string setting in settings) { String[] parts = setting.Split('='); String name = parts[0]; if (parts.Length == 1 || parts[1].Equals(null) || parts[1].Equals("")) { continue; } if (name.Equals("triggerPersistenceDelegateClasses")) { string[] trigDelegates = parts[1].Split(','); foreach (string triggerTypeName in trigDelegates) { try { Type trigDelClass = typeLoadHelper.LoadType(triggerTypeName); AddTriggerPersistenceDelegate((ITriggerPersistenceDelegate) Activator.CreateInstance(trigDelClass)); } catch (Exception e) { throw new NoSuchDelegateException("Error instantiating TriggerPersistenceDelegate of type: " + triggerTypeName, e); } } } else { throw new NoSuchDelegateException("Unknown setting: '" + name + "'"); } } } protected void AddDefaultTriggerPersistenceDelegates() { AddTriggerPersistenceDelegate(new SimpleTriggerPersistenceDelegate()); AddTriggerPersistenceDelegate(new CronTriggerPersistenceDelegate()); AddTriggerPersistenceDelegate(new CalendarIntervalTriggerPersistenceDelegate()); } protected virtual bool CanUseProperties { get { return useProperties; } } public void AddTriggerPersistenceDelegate(ITriggerPersistenceDelegate del) { logger.Debug("Adding TriggerPersistenceDelegate of type: " + del.GetType()); del.Initialize(tablePrefix, schedName, adoUtil); this.triggerPersistenceDelegates.Add(del); } public ITriggerPersistenceDelegate FindTriggerPersistenceDelegate(IOperableTrigger trigger) { foreach (ITriggerPersistenceDelegate del in triggerPersistenceDelegates) { if (del.CanHandleTriggerType(trigger)) { return del; } } return null; } public ITriggerPersistenceDelegate FindTriggerPersistenceDelegate(string discriminator) { foreach (ITriggerPersistenceDelegate del in triggerPersistenceDelegates) { if (del.GetHandledTriggerTypeDiscriminator().Equals(discriminator)) { return del; } } return null; } //--------------------------------------------------------------------------- // startup / recovery //--------------------------------------------------------------------------- /// <summary> /// Insert the job detail record. /// </summary> /// <param name="conn">the DB Connection</param> /// <param name="newState">the new state for the triggers</param> /// <param name="oldState1">the first old state to update</param> /// <param name="oldState2">the second old state to update</param> /// <returns>number of rows updated</returns> public virtual int UpdateTriggerStatesFromOtherStates(ConnectionAndTransactionHolder conn, string newState, string oldState1, string oldState2) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlUpdateTriggerStatesFromOtherStates))) { AddCommandParameter(cmd, "newState", newState); AddCommandParameter(cmd, "oldState1", oldState1); AddCommandParameter(cmd, "oldState2", oldState2); return cmd.ExecuteNonQuery(); } } /// <summary> /// Get the names of all of the triggers that have misfired. /// </summary> /// <param name="conn">the DB Connection</param> /// <param name="ts">The ts.</param> /// <returns>an array of <see cref="TriggerKey" /> objects</returns> public virtual IList<TriggerKey> SelectMisfiredTriggers(ConnectionAndTransactionHolder conn, long ts) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectMisfiredTriggers))) { AddCommandParameter(cmd, "timestamp", ts); using (IDataReader rs = cmd.ExecuteReader()) { List<TriggerKey> list = new List<TriggerKey>(); while (rs.Read()) { string triggerName = rs.GetString(ColumnTriggerName); string groupName = rs.GetString(ColumnTriggerGroup); list.Add(new TriggerKey(triggerName, groupName)); } return list; } } } /// <summary> /// Select all of the triggers in a given state. /// </summary> /// <param name="conn">The DB Connection</param> /// <param name="state">The state the triggers must be in</param> /// <returns> an array of trigger <see cref="TriggerKey" />s </returns> public virtual IList<TriggerKey> SelectTriggersInState(ConnectionAndTransactionHolder conn, string state) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectTriggersInState))) { AddCommandParameter(cmd, "state", state); using (IDataReader rs = cmd.ExecuteReader()) { List<TriggerKey> list = new List<TriggerKey>(); while (rs.Read()) { list.Add(new TriggerKey(rs.GetString(0), rs.GetString(1))); } return list; } } } /// <summary> /// Get the names of all of the triggers in the given state that have /// misfired - according to the given timestamp. /// </summary> /// <param name="conn">The DB Connection</param> /// <param name="state">The state.</param> /// <param name="ts">The time stamp.</param> /// <returns>An array of <see cref="TriggerKey" /> objects</returns> public virtual IList<TriggerKey> HasMisfiredTriggersInState(ConnectionAndTransactionHolder conn, string state, long ts) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectMisfiredTriggersInState))) { AddCommandParameter(cmd, "timestamp", ts); AddCommandParameter(cmd, "state", state); using (IDataReader rs = cmd.ExecuteReader()) { List<TriggerKey> list = new List<TriggerKey>(); while (rs.Read()) { string triggerName = rs.GetString(ColumnTriggerName); string groupName = rs.GetString(ColumnTriggerGroup); list.Add(new TriggerKey(triggerName, groupName)); } return list; } } } /// <summary> /// Get the names of all of the triggers in the given state that have /// misfired - according to the given timestamp. No more than count will /// be returned. /// </summary> /// <param name="conn">The conn.</param> /// <param name="state1">The state1.</param> /// <param name="ts">The ts.</param> /// <param name="count">The most misfired triggers to return, negative for all</param> /// <param name="resultList"> /// Output parameter. A List of <see cref="TriggerKey" /> objects. Must not be null /// </param> /// <returns>Whether there are more misfired triggers left to find beyond the given count.</returns> public virtual bool HasMisfiredTriggersInState(ConnectionAndTransactionHolder conn, string state1, DateTimeOffset ts, int count, IList<TriggerKey> resultList) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectHasMisfiredTriggersInState))) { AddCommandParameter(cmd, "nextFireTime", Convert.ToDecimal(ts.Ticks)); AddCommandParameter(cmd, "state1", state1); using (IDataReader rs = cmd.ExecuteReader()) { bool hasReachedLimit = false; while (rs.Read() && (hasReachedLimit == false)) { if (resultList.Count == count) { hasReachedLimit = true; } else { string triggerName = rs.GetString(ColumnTriggerName); string groupName = rs.GetString(ColumnTriggerGroup); resultList.Add(new TriggerKey(triggerName, groupName)); } } return hasReachedLimit; } } } /// <summary> /// Get the number of triggers in the given state that have /// misfired - according to the given timestamp. /// </summary> /// <param name="conn"></param> /// <param name="state1"></param> /// <param name="ts"></param> /// <returns></returns> public int CountMisfiredTriggersInState(ConnectionAndTransactionHolder conn, string state1, DateTimeOffset ts) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlCountMisfiredTriggersInStates))) { AddCommandParameter(cmd, "nextFireTime", Convert.ToDecimal(ts.Ticks)); AddCommandParameter(cmd, "state1", state1); using (IDataReader rs = cmd.ExecuteReader()) { if (rs.Read()) { return Convert.ToInt32(rs.GetValue(0), CultureInfo.InvariantCulture); } } throw new Exception("No misfired trigger count returned."); } } /// <summary> /// Get the names of all of the triggers in the given group and state that /// have misfired. /// </summary> /// <param name="conn">The DB Connection</param> /// <param name="groupName">Name of the group.</param> /// <param name="state">The state.</param> /// <param name="ts">The timestamp.</param> /// <returns>an array of <see cref="TriggerKey" /> objects</returns> public virtual IList<TriggerKey> SelectMisfiredTriggersInGroupInState(ConnectionAndTransactionHolder conn, string groupName, string state, long ts) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectMisfiredTriggersInGroupInState)) ) { AddCommandParameter(cmd, "timestamp", Convert.ToDecimal(ts)); AddCommandParameter(cmd, "triggerGroup", groupName); AddCommandParameter(cmd, "state", state); using (IDataReader rs = cmd.ExecuteReader()) { List<TriggerKey> list = new List<TriggerKey>(); while (rs.Read()) { string triggerName = rs.GetString(ColumnTriggerName); list.Add(new TriggerKey(triggerName, groupName)); } return list; } } } /// <summary> /// Select all of the triggers for jobs that are requesting recovery. The /// returned trigger objects will have unique "recoverXXX" trigger names and /// will be in the <see cref="SchedulerConstants.DefaultRecoveryGroup" /> /// trigger group. /// </summary> /// <remarks> /// In order to preserve the ordering of the triggers, the fire time will be /// set from the <i>ColumnFiredTime</i> column in the <i>TableFiredTriggers</i> /// table. The caller is responsible for calling <see cref="IOperableTrigger.ComputeFirstFireTimeUtc" /> /// on each returned trigger. It is also up to the caller to insert the /// returned triggers to ensure that they are fired. /// </remarks> /// <param name="conn">The DB Connection</param> /// <returns> an array of <see cref="ITrigger" /> objects</returns> public virtual IList<IOperableTrigger> SelectTriggersForRecoveringJobs(ConnectionAndTransactionHolder conn) { List<IOperableTrigger> list = new List<IOperableTrigger>(); using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectInstancesRecoverableFiredTriggers))) { AddCommandParameter(cmd, "instanceName", instanceId); AddCommandParameter(cmd, "requestsRecovery", GetDbBooleanValue(true)); using (IDataReader rs = cmd.ExecuteReader()) { long dumId = SystemTime.UtcNow().Ticks; while (rs.Read()) { string jobName = rs.GetString(ColumnJobName); string jobGroup = rs.GetString(ColumnJobGroup); // string trigName = rs.GetString(ColumnTriggerName); // string trigGroup = rs.GetString(ColumnTriggerGroup); long firedTimeInTicks = Convert.ToInt64(rs[ColumnFiredTime], CultureInfo.InvariantCulture); int priority = Convert.ToInt32(rs[ColumnPriority], CultureInfo.InvariantCulture); DateTimeOffset firedTime = new DateTimeOffset(firedTimeInTicks, TimeSpan.Zero); SimpleTriggerImpl rcvryTrig = new SimpleTriggerImpl("recover_" + instanceId + "_" + Convert.ToString(dumId++, CultureInfo.InvariantCulture), SchedulerConstants.DefaultRecoveryGroup, firedTime); rcvryTrig.JobName = jobName; rcvryTrig.JobGroup = jobGroup; rcvryTrig.Priority = priority; rcvryTrig.MisfireInstruction = MisfireInstruction.SimpleTrigger.FireNow; list.Add(rcvryTrig); } } } // read JobDataMaps with different reader.. foreach (SimpleTriggerImpl trigger in list) { JobDataMap jd = SelectTriggerJobDataMap(conn, trigger.Key); jd.Put(SchedulerConstants.FailedJobOriginalTriggerName, trigger.Name); jd.Put(SchedulerConstants.FailedJobOriginalTriggerGroup, trigger.Group); jd.Put(SchedulerConstants.FailedJobOriginalTriggerFiretimeInMillisecoonds, Convert.ToString(trigger.StartTimeUtc, CultureInfo.InvariantCulture)); trigger.JobDataMap = jd; } return list.ToArray(); } /// <summary> /// Delete all fired triggers. /// </summary> /// <param name="conn">The DB Connection.</param> /// <returns>The number of rows deleted.</returns> public virtual int DeleteFiredTriggers(ConnectionAndTransactionHolder conn) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlDeleteFiredTriggers))) { return cmd.ExecuteNonQuery(); } } /// <summary> /// Delete all fired triggers of the given instance. /// </summary> /// <param name="conn">The DB Connection</param> /// <param name="instanceName">The instance id.</param> /// <returns>The number of rows deleted</returns> public virtual int DeleteFiredTriggers(ConnectionAndTransactionHolder conn, string instanceName) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlDeleteInstancesFiredTriggers))) { AddCommandParameter(cmd, "instanceName", instanceName); return cmd.ExecuteNonQuery(); } } /// <summary> /// Clear (delete!) all scheduling data - all <see cref="IJob"/>s, <see cref="ITrigger" />s /// <see cref="ICalendar" />s. /// </summary> /// <remarks> /// </remarks> public void ClearData(ConnectionAndTransactionHolder conn) { IDbCommand ps = null; ps = PrepareCommand(conn, ReplaceTablePrefix(SqlDeleteAllSimpleTriggers)); ps.ExecuteNonQuery(); ps = PrepareCommand(conn, ReplaceTablePrefix(SqlDeleteAllSimpropTriggers)); ps.ExecuteNonQuery(); ps = PrepareCommand(conn, ReplaceTablePrefix(SqlDeleteAllCronTriggers)); ps.ExecuteNonQuery(); ps = PrepareCommand(conn, ReplaceTablePrefix(SqlDeleteAllBlobTriggers)); ps.ExecuteNonQuery(); ps = PrepareCommand(conn, ReplaceTablePrefix(SqlDeleteAllTriggers)); ps.ExecuteNonQuery(); ps = PrepareCommand(conn, ReplaceTablePrefix(SqlDeleteAllJobDetails)); ps.ExecuteNonQuery(); ps = PrepareCommand(conn, ReplaceTablePrefix(SqlDeleteAllCalendars)); ps.ExecuteNonQuery(); ps = PrepareCommand(conn, ReplaceTablePrefix(SqlDeleteAllPausedTriggerGrps)); ps.ExecuteNonQuery(); } //--------------------------------------------------------------------------- // jobs //--------------------------------------------------------------------------- /// <summary> /// Insert the job detail record. /// </summary> /// <param name="conn">The DB Connection.</param> /// <param name="job">The job to insert.</param> /// <returns>Number of rows inserted.</returns> public virtual int InsertJobDetail(ConnectionAndTransactionHolder conn, IJobDetail job) { byte[] baos = SerializeJobData(job.JobDataMap); int insertResult; using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlInsertJobDetail))) { AddCommandParameter(cmd, "jobName", job.Key.Name); AddCommandParameter(cmd, "jobGroup", job.Key.Group); AddCommandParameter(cmd, "jobDescription", job.Description); AddCommandParameter(cmd, "jobType", GetStorableJobTypeName(job.JobType)); AddCommandParameter(cmd, "jobDurable", GetDbBooleanValue(job.Durable)); AddCommandParameter(cmd, "jobVolatile", GetDbBooleanValue(job.ConcurrentExectionDisallowed)); AddCommandParameter(cmd, "jobStateful", GetDbBooleanValue(job.PersistJobDataAfterExecution)); AddCommandParameter(cmd, "jobRequestsRecovery", GetDbBooleanValue(job.RequestsRecovery)); AddCommandParameter(cmd, "jobDataMap", baos, dbProvider.Metadata.DbBinaryType); insertResult = cmd.ExecuteNonQuery(); } return insertResult; } /// <summary> /// Gets the db presentation for boolean value. Subclasses can overwrite this behaviour. /// </summary> /// <param name="booleanValue">Value to map to database.</param> /// <returns></returns> protected virtual object GetDbBooleanValue(bool booleanValue) { // works nicely for databases we have currently supported return booleanValue ? 1 : 0; } protected virtual string GetStorableJobTypeName(Type jobType) { int idx = jobType.AssemblyQualifiedName.IndexOf(','); // find next idx = jobType.AssemblyQualifiedName.IndexOf(',', idx + 1); string retValue = jobType.AssemblyQualifiedName.Substring(0, idx); return retValue; } /// <summary> /// Update the job detail record. /// </summary> /// <param name="conn">The DB Connection.</param> /// <param name="job">The job to update.</param> /// <returns>Number of rows updated.</returns> public virtual int UpdateJobDetail(ConnectionAndTransactionHolder conn, IJobDetail job) { byte[] baos = SerializeJobData(job.JobDataMap); using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlUpdateJobDetail))) { AddCommandParameter(cmd, "jobDescription", job.Description); AddCommandParameter(cmd, "jobType", GetStorableJobTypeName(job.JobType)); AddCommandParameter(cmd, "jobDurable", GetDbBooleanValue(job.Durable)); AddCommandParameter(cmd, "jobVolatile", GetDbBooleanValue(job.ConcurrentExectionDisallowed)); AddCommandParameter(cmd, "jobStateful", GetDbBooleanValue(job.PersistJobDataAfterExecution)); AddCommandParameter(cmd, "jobRequestsRecovery", GetDbBooleanValue(job.RequestsRecovery)); AddCommandParameter(cmd, "jobDataMap", baos, dbProvider.Metadata.DbBinaryType); AddCommandParameter(cmd, "jobName", job.Key.Name); AddCommandParameter(cmd, "jobGroup", job.Key.Group); int insertResult = cmd.ExecuteNonQuery(); return insertResult; } } /// <summary> /// Get the names of all of the triggers associated with the given job. /// </summary> /// <param name="conn">The DB Connection.</param> /// <param name="jobKey">The key identifying the job.</param> /// <returns>An array of <see cref="TriggerKey" /> objects</returns> public virtual IList<TriggerKey> SelectTriggerNamesForJob(ConnectionAndTransactionHolder conn, JobKey jobKey) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectTriggersForJob))) { AddCommandParameter(cmd, "jobName", jobKey.Name); AddCommandParameter(cmd, "jobGroup", jobKey.Group); using (IDataReader rs = cmd.ExecuteReader()) { List<TriggerKey> list = new List<TriggerKey>(10); while (rs.Read()) { string trigName = rs.GetString(ColumnTriggerName); string trigGroup = rs.GetString(ColumnTriggerGroup); list.Add(new TriggerKey(trigName, trigGroup)); } return list; } } } /// <summary> /// Delete the job detail record for the given job. /// </summary> /// <param name="conn">the DB Connection</param> /// <param name="jobKey">The key identifying the job.</param> /// <returns>the number of rows deleted</returns> public virtual int DeleteJobDetail(ConnectionAndTransactionHolder conn, JobKey jobKey) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlDeleteJobDetail))) { if (logger.IsDebugEnabled) { logger.Debug("Deleting job: " + jobKey); } AddCommandParameter(cmd, "jobName", jobKey.Name); AddCommandParameter(cmd, "jobGroup", jobKey.Group); return cmd.ExecuteNonQuery(); } } /// <summary> /// Check whether or not the given job is stateful. /// </summary> /// <param name="conn">the DB Connection</param> /// <param name="jobKey">The key identifying the job.</param> /// <returns> /// true if the job exists and is stateful, false otherwise /// </returns> public virtual bool IsJobStateful(ConnectionAndTransactionHolder conn, JobKey jobKey) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectJobNonConcurrent))) { AddCommandParameter(cmd, "jobName", jobKey.Name); AddCommandParameter(cmd, "jobGroup", jobKey.Group); object o = cmd.ExecuteScalar(); if (o != null) { return (bool) o; } return false; } } /// <summary> /// Check whether or not the given job exists. /// </summary> /// <param name="conn">the DB Connection</param> /// <param name="jobKey">The key identifying the job.</param> /// <returns>true if the job exists, false otherwise</returns> public virtual bool JobExists(ConnectionAndTransactionHolder conn, JobKey jobKey) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectJobExistence))) { AddCommandParameter(cmd, "jobName", jobKey.Name); AddCommandParameter(cmd, "jobGroup", jobKey.Group); using (IDataReader dr = cmd.ExecuteReader()) { if (dr.Read()) { return true; } return false; } } } /// <summary> /// Update the job data map for the given job. /// </summary> /// <param name="conn">The conn.</param> /// <param name="job">the job to update</param> /// <returns>the number of rows updated</returns> public virtual int UpdateJobData(ConnectionAndTransactionHolder conn, IJobDetail job) { byte[] baos = SerializeJobData(job.JobDataMap); using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlUpdateJobData))) { AddCommandParameter(cmd, "jobDataMap", baos, dbProvider.Metadata.DbBinaryType); AddCommandParameter(cmd, "jobName", job.Key.Name); AddCommandParameter(cmd, "jobGroup", job.Key.Group); return cmd.ExecuteNonQuery(); } } /// <summary> /// Select the JobDetail object for a given job name / group name. /// </summary> /// <param name="conn">The DB Connection.</param> /// <param name="jobKey">The key identifying the job.</param> /// <param name="loadHelper">The load helper.</param> /// <returns>The populated JobDetail object.</returns> public virtual IJobDetail SelectJobDetail(ConnectionAndTransactionHolder conn, JobKey jobKey, ITypeLoadHelper loadHelper) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectJobDetail))) { AddCommandParameter(cmd, "jobName", jobKey.Name); AddCommandParameter(cmd, "jobGroup", jobKey.Group); using (IDataReader rs = cmd.ExecuteReader()) { JobDetailImpl job = null; if (rs.Read()) { job = new JobDetailImpl(); job.Name = rs.GetString(ColumnJobName); job.Group = rs.GetString(ColumnJobGroup); job.Description = rs.GetString(ColumnDescription); job.JobType = loadHelper.LoadType(rs.GetString(ColumnJobClass)); job.Durable = rs.GetBoolean(ColumnIsDurable); job.RequestsRecovery = rs.GetBoolean(ColumnRequestsRecovery); IDictionary map; if (CanUseProperties) { map = GetMapFromProperties(rs, 9); } else { map = (IDictionary) GetObjectFromBlob(rs, 9); } if (null != map) { job.JobDataMap = new JobDataMap(map); } } return job; } } } /// <summary> build Map from java.util.Properties encoding.</summary> private IDictionary GetMapFromProperties(IDataReader rs, int idx) { IDictionary map; NameValueCollection properties = (NameValueCollection)GetJobDataFromBlob(rs, idx); if (properties == null) { return null; } map = ConvertFromProperty(properties); return map; } /// <summary> /// Select the total number of jobs stored. /// </summary> /// <param name="conn">The DB Connection.</param> /// <returns>The total number of jobs stored.</returns> public virtual int SelectNumJobs(ConnectionAndTransactionHolder conn) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectNumJobs))) { return (int)cmd.ExecuteScalar(); } } /// <summary> /// Select all of the job group names that are stored. /// </summary> /// <param name="conn">The DB Connection.</param> /// <returns>An array of <see cref="String" /> group names.</returns> public virtual IList<string> SelectJobGroups(ConnectionAndTransactionHolder conn) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectJobGroups))) { using (IDataReader rs = cmd.ExecuteReader()) { List<string> list = new List<string>(); while (rs.Read()) { list.Add(rs.GetString(0)); } return list.ToArray(); } } } /// <summary> /// Select all of the jobs contained in a given group. /// </summary> /// <param name="conn">The DB Connection.</param> /// <param name="matcher"></param> /// <returns>An array of <see cref="String" /> job names.</returns> public virtual Collection.ISet<JobKey> SelectJobsInGroup(ConnectionAndTransactionHolder conn, GroupMatcher<JobKey> matcher) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectJobsInGroup))) { AddCommandParameter(cmd, "jobGroup", ToSqlLikeClause(matcher)); using (IDataReader rs = cmd.ExecuteReader()) { Collection.HashSet<JobKey> list = new Collection.HashSet<JobKey>(); while (rs.Read()) { list.Add(new JobKey(rs.GetString(0), rs.GetString(1))); } return list; } } } protected static string ToSqlLikeClause<T>(GroupMatcher<T> matcher) where T : Key<T> { string groupName; if (matcher.CompareWithOperator == StringOperator.Equality) { groupName = matcher.CompareToValue; } else if (matcher.CompareWithOperator == StringOperator.Contains) { groupName = "%" + matcher.CompareToValue + "%"; } else if (matcher.CompareWithOperator == StringOperator.EndsWith) { groupName = "%" + matcher.CompareToValue; } else if (matcher.CompareWithOperator == StringOperator.StartsWith) { groupName = matcher.CompareToValue + "%"; } else { throw new ArgumentOutOfRangeException("Don't know how to translate " + matcher.CompareWithOperator + " into SQL"); } return groupName; } //--------------------------------------------------------------------------- // triggers //--------------------------------------------------------------------------- /// <summary> /// Insert the base trigger data. /// </summary> /// <param name="conn">the DB Connection</param> /// <param name="trigger">the trigger to insert</param> /// <param name="state">the state that the trigger should be stored in</param> /// <param name="jobDetail">The job detail.</param> /// <returns>the number of rows inserted</returns> public virtual int InsertTrigger(ConnectionAndTransactionHolder conn, IOperableTrigger trigger, string state, IJobDetail jobDetail) { byte[] baos = null; if (trigger.JobDataMap.Count > 0) { baos = SerializeJobData(trigger.JobDataMap); } using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlInsertTrigger))) { AddCommandParameter(cmd, "triggerName", trigger.Key.Name); AddCommandParameter(cmd, "triggerGroup", trigger.Key.Group); AddCommandParameter(cmd, "triggerJobName", trigger.JobKey.Name); AddCommandParameter(cmd, "triggerJobGroup", trigger.JobKey.Group); AddCommandParameter(cmd, "triggerDescription", trigger.Description); if (trigger.GetNextFireTimeUtc().HasValue) { AddCommandParameter(cmd, "triggerNextFireTime", Convert.ToDecimal(trigger.GetNextFireTimeUtc().Value.Ticks)); } else { AddCommandParameter(cmd, "triggerNextFireTime", null); } long prevFireTime = -1; if (trigger.GetPreviousFireTimeUtc().HasValue) { prevFireTime = trigger.GetPreviousFireTimeUtc().Value.Ticks; } AddCommandParameter(cmd, "triggerPreviousFireTime", Convert.ToDecimal(prevFireTime)); AddCommandParameter(cmd, "triggerState", state); string paramName = "triggerType"; ITriggerPersistenceDelegate tDel = FindTriggerPersistenceDelegate(trigger); string type = TriggerTypeBlob; if (tDel != null) { type = tDel.GetHandledTriggerTypeDiscriminator(); } AddCommandParameter(cmd, paramName, type); AddCommandParameter(cmd, "triggerStartTime", Convert.ToDecimal(trigger.StartTimeUtc.Ticks)); long endTime = 0; if (trigger.EndTimeUtc.HasValue) { endTime = trigger.EndTimeUtc.Value.Ticks; } AddCommandParameter(cmd, "triggerEndTime", Convert.ToDecimal(endTime)); AddCommandParameter(cmd, "triggerCalendarName", trigger.CalendarName); AddCommandParameter(cmd, "triggerMisfireInstruction", trigger.MisfireInstruction); paramName = "triggerJobJobDataMap"; if (baos != null) { AddCommandParameter(cmd, paramName, baos, dbProvider.Metadata.DbBinaryType); } else { AddCommandParameter(cmd, paramName, null, dbProvider.Metadata.DbBinaryType); } AddCommandParameter(cmd, "triggerPriority", trigger.Priority); int insertResult = cmd.ExecuteNonQuery(); if (tDel == null) { InsertBlobTrigger(conn, trigger); } else { tDel.InsertExtendedTriggerProperties(conn, trigger, state, jobDetail); } return insertResult; } } /// <summary> /// Insert the blob trigger data. /// </summary> /// <param name="conn">The DB Connection.</param> /// <param name="trigger">The trigger to insert.</param> /// <returns>The number of rows inserted.</returns> public virtual int InsertBlobTrigger(ConnectionAndTransactionHolder conn, IOperableTrigger trigger) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlInsertBlobTrigger))) { // update the blob byte[] buf = SerializeObject(trigger); AddCommandParameter(cmd, "triggerName", trigger.Key.Name); AddCommandParameter(cmd, "triggerGroup", trigger.Key.Group); AddCommandParameter(cmd, "blob", buf, dbProvider.Metadata.DbBinaryType); return cmd.ExecuteNonQuery(); } } /// <summary> /// Update the base trigger data. /// </summary> /// <param name="conn">The DB Connection.</param> /// <param name="trigger">The trigger to insert.</param> /// <param name="state">The state that the trigger should be stored in.</param> /// <param name="jobDetail">The job detail.</param> /// <returns>The number of rows updated.</returns> public virtual int UpdateTrigger(ConnectionAndTransactionHolder conn, IOperableTrigger trigger, string state, IJobDetail jobDetail) { // save some clock cycles by unnecessarily writing job data blob ... bool updateJobData = trigger.JobDataMap.Dirty; byte[] baos = null; if (updateJobData && trigger.JobDataMap.Count > 0) { baos = SerializeJobData(trigger.JobDataMap); } IDbCommand cmd; int insertResult; if (updateJobData) { cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlUpdateTrigger)); } else { cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlUpdateTriggerSkipData)); } AddCommandParameter(cmd, "triggerJobName", trigger.JobKey.Name); AddCommandParameter(cmd, "triggerJobGroup", trigger.JobKey.Group); AddCommandParameter(cmd, "triggerDescription", trigger.Description); long nextFireTime = -1; if (trigger.GetNextFireTimeUtc().HasValue) { nextFireTime = trigger.GetNextFireTimeUtc().Value.Ticks; } AddCommandParameter(cmd, "triggerNextFireTime", Convert.ToDecimal(nextFireTime)); long prevFireTime = -1; if (trigger.GetPreviousFireTimeUtc().HasValue) { prevFireTime = trigger.GetPreviousFireTimeUtc().Value.Ticks; } AddCommandParameter(cmd, "triggerPreviousFireTime", Convert.ToDecimal(prevFireTime)); AddCommandParameter(cmd, "triggerState", state); ITriggerPersistenceDelegate tDel = FindTriggerPersistenceDelegate(trigger); string type = TriggerTypeBlob; if (tDel != null) { type = tDel.GetHandledTriggerTypeDiscriminator(); } AddCommandParameter(cmd, "triggerType", TriggerTypeSimple); AddCommandParameter(cmd, "triggerStartTime", Convert.ToDecimal(trigger.StartTimeUtc.Ticks)); long endTime = 0; if (trigger.EndTimeUtc.HasValue) { endTime = trigger.EndTimeUtc.Value.Ticks; } AddCommandParameter(cmd, "triggerEndTime", Convert.ToDecimal(endTime)); AddCommandParameter(cmd, "triggerCalendarName", trigger.CalendarName); AddCommandParameter(cmd, "triggerMisfireInstruction", trigger.MisfireInstruction); AddCommandParameter(cmd, "triggerPriority", trigger.Priority); const string JobDataMapParameter = "triggerJobJobDataMap"; if (updateJobData) { if (baos != null) { AddCommandParameter(cmd, JobDataMapParameter, baos, dbProvider.Metadata.DbBinaryType); } else { AddCommandParameter(cmd, JobDataMapParameter, null, dbProvider.Metadata.DbBinaryType); } AddCommandParameter(cmd, "triggerName", trigger.Key.Name); AddCommandParameter(cmd, "triggerGroup", trigger.Key.Group); } else { AddCommandParameter(cmd, "triggerName", trigger.Key.Name); AddCommandParameter(cmd, "triggerGroup", trigger.Key.Group); } insertResult = cmd.ExecuteNonQuery(); if (tDel == null) { UpdateBlobTrigger(conn, trigger); } else { tDel.UpdateExtendedTriggerProperties(conn, trigger, state, jobDetail); } return insertResult; } /// <summary> /// Update the blob trigger data. /// </summary> /// <param name="conn">The DB Connection.</param> /// <param name="trigger">The trigger to insert.</param> /// <returns>The number of rows updated.</returns> public virtual int UpdateBlobTrigger(ConnectionAndTransactionHolder conn, IOperableTrigger trigger) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlUpdateBlobTrigger))) { // update the blob byte[] os = SerializeObject(trigger); AddCommandParameter(cmd, "blob", os, dbProvider.Metadata.DbBinaryType); AddCommandParameter(cmd, "triggerName", trigger.Key.Name); AddCommandParameter(cmd, "triggerGroup", trigger.Key.Group); return cmd.ExecuteNonQuery(); } } /// <summary> /// Check whether or not a trigger exists. /// </summary> /// <param name="conn">The DB Connection.</param> /// <param name="triggerKey">the key of the trigger</param> /// <returns>true if the trigger exists, false otherwise</returns> public virtual bool TriggerExists(ConnectionAndTransactionHolder conn, TriggerKey triggerKey) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectTriggerExistence))) { AddCommandParameter(cmd, "triggerName", triggerKey.Name); AddCommandParameter(cmd, "triggerGroup", triggerKey.Group); using (IDataReader dr = cmd.ExecuteReader()) { if (dr.Read()) { return true; } else { return false; } } } } /// <summary> /// Update the state for a given trigger. /// </summary> /// <param name="conn">The DB Connection.</param> /// <param name="triggerKey">the key of the trigger</param> /// <param name="state">The new state for the trigger.</param> /// <returns>The number of rows updated.</returns> public virtual int UpdateTriggerState(ConnectionAndTransactionHolder conn, TriggerKey triggerKey, string state) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlUpdateTriggerState))) { AddCommandParameter(cmd, "state", state); AddCommandParameter(cmd, "triggerName", triggerKey.Name); AddCommandParameter(cmd, "triggerGroup", triggerKey.Group); return cmd.ExecuteNonQuery(); } } /// <summary> /// Update the given trigger to the given new state, if it is one of the /// given old states. /// </summary> /// <param name="conn">The DB connection.</param> /// <param name="triggerKey">the key of the trigger</param> /// <param name="newState">The new state for the trigger.</param> /// <param name="oldState1">One of the old state the trigger must be in.</param> /// <param name="oldState2">One of the old state the trigger must be in.</param> /// <param name="oldState3">One of the old state the trigger must be in.</param> /// <returns>The number of rows updated.</returns> public virtual int UpdateTriggerStateFromOtherStates(ConnectionAndTransactionHolder conn, TriggerKey triggerKey, string newState, string oldState1, string oldState2, string oldState3) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlUpdateTriggerStateFromStates))) { AddCommandParameter(cmd, "newState", newState); AddCommandParameter(cmd, "triggerName", triggerKey.Name); AddCommandParameter(cmd, "triggerGroup", triggerKey.Group); AddCommandParameter(cmd, "oldState1", oldState1); AddCommandParameter(cmd, "oldState2", oldState2); AddCommandParameter(cmd, "oldState3", oldState3); return cmd.ExecuteNonQuery(); } } /// <summary> /// Update all triggers in the given group to the given new state, if they /// are in one of the given old states. /// </summary> /// <param name="conn">The DB connection.</param> /// <param name="matcher"></param> /// <param name="newState">The new state for the trigger.</param> /// <param name="oldState1">One of the old state the trigger must be in.</param> /// <param name="oldState2">One of the old state the trigger must be in.</param> /// <param name="oldState3">One of the old state the trigger must be in.</param> /// <returns>The number of rows updated.</returns> public virtual int UpdateTriggerGroupStateFromOtherStates(ConnectionAndTransactionHolder conn, GroupMatcher<TriggerKey> matcher, string newState, string oldState1, string oldState2, string oldState3) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlUpdateTriggerGroupStateFromStates))) { AddCommandParameter(cmd, "newState", newState); AddCommandParameter(cmd, "groupName", ToSqlLikeClause(matcher)); AddCommandParameter(cmd, "oldState1", oldState1); AddCommandParameter(cmd, "oldState2", oldState2); AddCommandParameter(cmd, "oldState3", oldState3); return cmd.ExecuteNonQuery(); } } /// <summary> /// Update the given trigger to the given new state, if it is in the given /// old state. /// </summary> /// <param name="conn">the DB connection</param> /// <param name="triggerKey">the key of the trigger</param> /// <param name="newState">the new state for the trigger</param> /// <param name="oldState">the old state the trigger must be in</param> /// <returns>int the number of rows updated</returns> public virtual int UpdateTriggerStateFromOtherState(ConnectionAndTransactionHolder conn, TriggerKey triggerKey, string newState, string oldState) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlUpdateTriggerStateFromState))) { AddCommandParameter(cmd, "newState", newState); AddCommandParameter(cmd, "triggerName", triggerKey.Name); AddCommandParameter(cmd, "triggerGroup", triggerKey.Group); AddCommandParameter(cmd, "oldState", oldState); return cmd.ExecuteNonQuery(); } } /// <summary> /// Update all of the triggers of the given group to the given new state, if /// they are in the given old state. /// </summary> /// <param name="conn">the DB connection</param> /// <param name="matcher"></param> /// <param name="newState">the new state for the trigger group</param> /// <param name="oldState">the old state the triggers must be in</param> /// <returns>int the number of rows updated</returns> public virtual int UpdateTriggerGroupStateFromOtherState(ConnectionAndTransactionHolder conn, GroupMatcher<TriggerKey> matcher, string newState, string oldState) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlUpdateTriggerGroupStateFromState))) { AddCommandParameter(cmd, "newState", newState); AddCommandParameter(cmd, "triggerGroup", ToSqlLikeClause(matcher)); AddCommandParameter(cmd, "oldState", oldState); return cmd.ExecuteNonQuery(); } } /// <summary> /// Update the states of all triggers associated with the given job. /// </summary> /// <param name="conn">the DB Connection</param> /// <param name="jobKey">the key of the job</param> /// <param name="state">the new state for the triggers</param> /// <returns>the number of rows updated</returns> public virtual int UpdateTriggerStatesForJob(ConnectionAndTransactionHolder conn, JobKey jobKey, string state) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlUpdateJobTriggerStates))) { AddCommandParameter(cmd, "state", state); AddCommandParameter(cmd, "jobName", jobKey.Name); AddCommandParameter(cmd, "jobGroup", jobKey.Group); return cmd.ExecuteNonQuery(); } } /// <summary> /// Updates the state of the trigger states for job from other. /// </summary> /// <param name="conn">The conn.</param> /// <param name="jobKey">Key of the job.</param> /// <param name="state">The state.</param> /// <param name="oldState">The old state.</param> /// <returns></returns> public virtual int UpdateTriggerStatesForJobFromOtherState(ConnectionAndTransactionHolder conn, JobKey jobKey, string state, string oldState) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlUpdateJobTriggerStatesFromOtherState))) { AddCommandParameter(cmd, "state", state); AddCommandParameter(cmd, "jobName", jobKey.Name); AddCommandParameter(cmd, "jobGroup", jobKey.Group); AddCommandParameter(cmd, "oldState", oldState); return cmd.ExecuteNonQuery(); } } /// <summary> /// Delete the cron trigger data for a trigger. /// </summary> /// <param name="conn">the DB Connection</param> /// <param name="triggerKey">the key of the trigger</param> /// <returns>the number of rows deleted</returns> public virtual int DeleteBlobTrigger(ConnectionAndTransactionHolder conn, TriggerKey triggerKey) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlDeleteBlobTrigger))) { AddCommandParameter(cmd, "triggerName", triggerKey.Name); AddCommandParameter(cmd, "triggerGroup", triggerKey.Group); return cmd.ExecuteNonQuery(); } } /// <summary> /// Delete the base trigger data for a trigger. /// </summary> /// <param name="conn">the DB Connection</param> /// <param name="triggerKey">the key of the trigger</param> /// <returns>the number of rows deleted</returns> public virtual int DeleteTrigger(ConnectionAndTransactionHolder conn, TriggerKey triggerKey) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlDeleteTrigger))) { AddCommandParameter(cmd, "triggerName", triggerKey.Name); AddCommandParameter(cmd, "triggerGroup", triggerKey.Group); return cmd.ExecuteNonQuery(); } } protected void deleteTriggerExtension(ConnectionAndTransactionHolder conn, TriggerKey triggerKey) { foreach (ITriggerPersistenceDelegate tDel in triggerPersistenceDelegates) { if (tDel.DeleteExtendedTriggerProperties(conn, triggerKey) > 0) { return; // as soon as one affects a row, we're done. } } } /// <summary> /// Select the number of triggers associated with a given job. /// </summary> /// <param name="conn">the DB Connection</param> /// <param name="jobKey">the key of the job</param> /// <returns>the number of triggers for the given job</returns> public virtual int SelectNumTriggersForJob(ConnectionAndTransactionHolder conn, JobKey jobKey) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectNumTriggersForJob))) { AddCommandParameter(cmd, "jobName", jobKey.Name); AddCommandParameter(cmd, "jobGroup", jobKey.Group); using (IDataReader rs = cmd.ExecuteReader()) { if (rs.Read()) { return Convert.ToInt32(rs.GetValue(0), CultureInfo.InvariantCulture); } else { return 0; } } } } /// <summary> /// Select the job to which the trigger is associated. /// </summary> /// <param name="conn">the DB Connection</param> /// <param name="triggerKey">the key of the trigger</param> /// <param name="loadHelper">The load helper.</param> /// <returns>The <see cref="IJobDetail" /> object associated with the given trigger</returns> public virtual IJobDetail SelectJobForTrigger(ConnectionAndTransactionHolder conn, TriggerKey triggerKey, ITypeLoadHelper loadHelper) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectJobForTrigger))) { AddCommandParameter(cmd, "triggerName", triggerKey.Name); AddCommandParameter(cmd, "triggerGroup", triggerKey.Group); using (IDataReader rs = cmd.ExecuteReader()) { if (rs.Read()) { JobDetailImpl job = new JobDetailImpl(); job.Name = rs.GetString(ColumnJobName); job.Group = rs.GetString(ColumnJobGroup); job.Durable = rs.GetBoolean(ColumnIsDurable); job.JobType = loadHelper.LoadType(rs.GetString(ColumnJobClass)); job.RequestsRecovery = rs.GetBoolean(ColumnRequestsRecovery); return job; } else { if (logger.IsDebugEnabled) { logger.Debug("No job for trigger '" +triggerKey + "'."); } return null; } } } } /// <summary> /// Select the triggers for a job /// </summary> /// <param name="conn">the DB Connection</param> /// <param name="jobKey">the key of the job</param> /// <returns> /// an array of <see cref="ITrigger" /> objects /// associated with a given job. /// </returns> public virtual IList<IOperableTrigger> SelectTriggersForJob(ConnectionAndTransactionHolder conn, JobKey jobKey) { List<IOperableTrigger> trigList = new List<IOperableTrigger>(); List<TriggerKey> keys = new List<TriggerKey>(); using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectTriggersForJob))) { AddCommandParameter(cmd, "jobName", jobKey.Name); AddCommandParameter(cmd, "jobGroup", jobKey.Group); using (IDataReader rs = cmd.ExecuteReader()) { while (rs.Read()) { keys.Add(new TriggerKey(rs.GetString(0), rs.GetString(1))); } } } foreach (TriggerKey triggerKey in keys) { IOperableTrigger t = SelectTrigger(conn, triggerKey); if (t != null) { trigList.Add(t); } } return trigList; } /// <summary> /// Select the triggers for a calendar /// </summary> /// <param name="conn">The DB Connection.</param> /// <param name="calName">Name of the calendar.</param> /// <returns> /// An array of <see cref="ITrigger" /> objects associated with a given job. /// </returns> public virtual IList<IOperableTrigger> SelectTriggersForCalendar(ConnectionAndTransactionHolder conn, string calName) { List<TriggerKey> keys = new List<TriggerKey>(); using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectTriggersForCalendar))) { AddCommandParameter(cmd, "calendarName", calName); using (IDataReader rs = cmd.ExecuteReader()) { while (rs.Read()) { keys.Add(new TriggerKey(rs.GetString(ColumnTriggerName), rs.GetString(ColumnTriggerGroup))); } } } List<IOperableTrigger> trigList = new List<IOperableTrigger>(); foreach (TriggerKey key in keys) { trigList.Add(SelectTrigger(conn, key)); } return trigList; } /// <summary> /// Select a trigger. /// </summary> /// <param name="conn">the DB Connection</param> /// <param name="triggerKey">the key of the trigger</param> /// <returns>The <see cref="ITrigger" /> object</returns> public virtual IOperableTrigger SelectTrigger(ConnectionAndTransactionHolder conn, TriggerKey triggerKey) { IOperableTrigger trigger = null; string jobName = null; string jobGroup = null; string description = null; string triggerType = ""; string calendarName = null; int misFireInstr = Int32.MinValue; int priority = Int32.MinValue; IDictionary map = null; DateTimeOffset? pft = null; DateTimeOffset? endTimeD = null; DateTimeOffset? nft = null; DateTimeOffset startTimeD = DateTimeOffset.MinValue; using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectTrigger))) { AddCommandParameter(cmd, "triggerName", triggerKey.Name); AddCommandParameter(cmd, "triggerGroup", triggerKey.Group); using (IDataReader rs = cmd.ExecuteReader()) { if (rs.Read()) { jobName = rs.GetString(ColumnJobName); jobGroup = rs.GetString(ColumnJobGroup); description = rs.GetString(ColumnDescription); long nextFireTime = rs.GetInt64(ColumnNextFireTime); long prevFireTime = rs.GetInt64(ColumnPreviousFireTime); triggerType = rs.GetString(ColumnTriggerType); long startTime = rs.GetInt64(ColumnStartTime); long endTime = rs.GetInt64(ColumnEndTime); calendarName = rs.GetString(ColumnCalendarName); misFireInstr = rs.GetInt32(ColumnMifireInstruction); priority = rs.GetInt32(ColumnPriority); if (CanUseProperties) { map = GetMapFromProperties(rs, 15); } else { map = (IDictionary)GetObjectFromBlob(rs, 15); } if (nextFireTime > 0) { nft = new DateTimeOffset(nextFireTime, TimeSpan.Zero); } if (prevFireTime > 0) { pft = new DateTimeOffset(prevFireTime, TimeSpan.Zero); } startTimeD = new DateTimeOffset(startTime, TimeSpan.Zero); if (endTime > 0) { endTimeD = new DateTimeOffset(endTime, TimeSpan.Zero); } // done reading rs.Close(); if (triggerType.Equals(TriggerTypeBlob)) { using (IDbCommand cmd2 = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectBlobTrigger))) { AddCommandParameter(cmd2, "triggerName", triggerKey.Name); AddCommandParameter(cmd2, "triggerGroup", triggerKey.Group); using (IDataReader rs2 = cmd2.ExecuteReader()) { if (rs2.Read()) { trigger = (IOperableTrigger) GetObjectFromBlob(rs2, 3); } } } } else { ITriggerPersistenceDelegate tDel = FindTriggerPersistenceDelegate(triggerType); if (tDel == null) throw new JobPersistenceException("No TriggerPersistenceDelegate for trigger discriminator type: " + triggerType); TriggerPropertyBundle triggerProps = tDel.LoadExtendedTriggerProperties(conn, triggerKey); TriggerBuilder tb = TriggerBuilder.Create() .WithDescription(description) .WithPriority(priority) .StartAt(startTimeD) .EndAt(endTimeD) .WithIdentity(triggerKey) .ModifiedByCalendar(calendarName) .WithSchedule(triggerProps.ScheduleBuilder) .ForJob(new JobKey(jobName, jobGroup)); if (null != map) { tb.UsingJobData(new JobDataMap(map)); } trigger = (IOperableTrigger) tb.Build(); trigger.MisfireInstruction = misFireInstr; trigger.SetNextFireTimeUtc(nft); trigger.SetPreviousFireTimeUtc(pft); setTriggerStateProperties(trigger, triggerProps); } } } } return trigger; } private void setTriggerStateProperties(IOperableTrigger trigger, TriggerPropertyBundle props) { if (props.StatePropertyNames == null) { return; } ObjectUtils.SetObjectProperties(trigger, props.StatePropertyNames, props.StatePropertyValues); } /// <summary> /// Select a trigger's JobDataMap. /// </summary> /// <param name="conn">the DB Connection</param> /// <param name="triggerKey">the key of the trigger</param> /// <returns>The <see cref="JobDataMap" /> of the Trigger, never null, but possibly empty. </returns> public virtual JobDataMap SelectTriggerJobDataMap(ConnectionAndTransactionHolder conn, TriggerKey triggerKey) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectTriggerData))) { AddCommandParameter(cmd, "triggerName", triggerKey.Name); AddCommandParameter(cmd, "triggerGroup", triggerKey.Group); using (IDataReader rs = cmd.ExecuteReader()) { if (rs.Read()) { IDictionary map; if (CanUseProperties) { map = GetMapFromProperties(rs, 0); } else { map = (IDictionary) GetObjectFromBlob(rs, 0); } if (null != map) { return new JobDataMap(map); } } } } return new JobDataMap(); } /// <summary> /// Select a trigger's state value. /// </summary> /// <param name="conn">the DB Connection</param> /// <param name="triggerKey">the key of the trigger</param> /// <returns>The <see cref="ITrigger" /> object</returns> public virtual string SelectTriggerState(ConnectionAndTransactionHolder conn, TriggerKey triggerKey) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectTriggerState))) { string state; AddCommandParameter(cmd, "triggerName", triggerKey.Name); AddCommandParameter(cmd, "triggerGroup", triggerKey.Group); using (IDataReader rs = cmd.ExecuteReader()) { if (rs.Read()) { state = rs.GetString(ColumnTriggerState); } else { state = StateDeleted; } } return String.Intern(state); } } /// <summary> /// Select a trigger status (state and next fire time). /// </summary> /// <param name="conn">the DB Connection</param> /// <param name="triggerKey">the key of the trigger</param> /// <returns> /// a <see cref="TriggerStatus" /> object, or null /// </returns> public virtual TriggerStatus SelectTriggerStatus(ConnectionAndTransactionHolder conn, TriggerKey triggerKey) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectTriggerStatus))) { TriggerStatus status = null; AddCommandParameter(cmd, "triggerName", triggerKey.Name); AddCommandParameter(cmd, "triggerGroup", triggerKey.Group); using (IDataReader rs = cmd.ExecuteReader()) { if (rs.Read()) { string state = rs.GetString(ColumnTriggerState); long nextFireTime = Convert.ToInt64(rs[ColumnNextFireTime], CultureInfo.InvariantCulture); string jobName = rs.GetString(ColumnJobName); string jobGroup = rs.GetString(ColumnJobGroup); DateTimeOffset? nft = null; if (nextFireTime > 0) { nft = new DateTimeOffset(nextFireTime, TimeSpan.Zero); } status = new TriggerStatus(state, nft); status.Key = triggerKey; status.JobKey = new JobKey(jobName, jobGroup); } } return status; } } /// <summary> /// Select the total number of triggers stored. /// </summary> /// <param name="conn">the DB Connection</param> /// <returns>the total number of triggers stored</returns> public virtual int SelectNumTriggers(ConnectionAndTransactionHolder conn) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectNumTriggers))) { int count = 0; using (IDataReader rs = cmd.ExecuteReader()) { if (rs.Read()) { count = Convert.ToInt32(rs.GetInt32(0)); } } return count; } } /// <summary> /// Select all of the trigger group names that are stored. /// </summary> /// <param name="conn">the DB Connection</param> /// <returns> /// an array of <see cref="String" /> group names /// </returns> public virtual IList<string> SelectTriggerGroups(ConnectionAndTransactionHolder conn) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectTriggerGroups))) { using (IDataReader rs = cmd.ExecuteReader()) { List<string> list = new List<string>(); while (rs.Read()) { list.Add((string) rs[0]); } return list.ToArray(); } } } public IList<String> SelectTriggerGroups(ConnectionAndTransactionHolder conn, GroupMatcher<TriggerKey> matcher) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectTriggerGroupsFiltered))) { AddCommandParameter(cmd, "triggerGroup", ToSqlLikeClause(matcher)); using (IDataReader rs = cmd.ExecuteReader()) { List<string> list = new List<string>(); while (rs.Read()) { list.Add((string) rs[0]); } return list; } } } /// <summary> /// Select all of the triggers contained in a given group. /// </summary> /// <param name="conn">the DB Connection</param> /// <param name="matcher"></param> /// <returns> /// an array of <see cref="String" /> trigger names /// </returns> public virtual Collection.ISet<TriggerKey> SelectTriggersInGroup(ConnectionAndTransactionHolder conn, GroupMatcher<TriggerKey> matcher) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectTriggersInGroup))) { AddCommandParameter(cmd, "triggerGroup", ToSqlLikeClause(matcher)); using (IDataReader rs = cmd.ExecuteReader()) { Collection.HashSet<TriggerKey> keys = new Collection.HashSet<TriggerKey>(); while (rs.Read()) { keys.Add(new TriggerKey(rs.GetString(0), rs.GetString(1))); } return keys; } } } /// <summary> /// Inserts the paused trigger group. /// </summary> /// <param name="conn">The conn.</param> /// <param name="groupName">Name of the group.</param> /// <returns></returns> public virtual int InsertPausedTriggerGroup(ConnectionAndTransactionHolder conn, string groupName) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlInsertPausedTriggerGroup))) { AddCommandParameter(cmd, "triggerGroup", groupName); int rows = cmd.ExecuteNonQuery(); return rows; } } /// <summary> /// Deletes the paused trigger group. /// </summary> /// <param name="conn">The conn.</param> /// <param name="groupName">Name of the group.</param> /// <returns></returns> public virtual int DeletePausedTriggerGroup(ConnectionAndTransactionHolder conn, string groupName) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlDeletePausedTriggerGroup))) { AddCommandParameter(cmd, "triggerGroup", groupName); int rows = cmd.ExecuteNonQuery(); return rows; } } public virtual int DeletePausedTriggerGroup(ConnectionAndTransactionHolder conn, GroupMatcher<TriggerKey> matcher) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlDeletePausedTriggerGroup))) { AddCommandParameter(cmd, "triggerGroup", ToSqlLikeClause(matcher)); int rows = cmd.ExecuteNonQuery(); return rows; } } /// <summary> /// Deletes all paused trigger groups. /// </summary> /// <param name="conn">The conn.</param> /// <returns></returns> public virtual int DeleteAllPausedTriggerGroups(ConnectionAndTransactionHolder conn) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlDeletePausedTriggerGroups))) { int rows = cmd.ExecuteNonQuery(); return rows; } } /// <summary> /// Determines whether the specified trigger group is paused. /// </summary> /// <param name="conn">The conn.</param> /// <param name="groupName">Name of the group.</param> /// <returns> /// <c>true</c> if trigger group is paused; otherwise, <c>false</c>. /// </returns> public virtual bool IsTriggerGroupPaused(ConnectionAndTransactionHolder conn, string groupName) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectPausedTriggerGroup))) { AddCommandParameter(cmd, "triggerGroup", groupName); using (IDataReader rs = cmd.ExecuteReader()) { return rs.Read(); } } } /// <summary> /// Determines whether given trigger group already exists. /// </summary> /// <param name="conn">The conn.</param> /// <param name="groupName">Name of the group.</param> /// <returns> /// <c>true</c> if trigger group exists; otherwise, <c>false</c>. /// </returns> public virtual bool IsExistingTriggerGroup(ConnectionAndTransactionHolder conn, string groupName) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectNumTriggersInGroup))) { AddCommandParameter(cmd, "triggerGroup", groupName); using (IDataReader rs = cmd.ExecuteReader()) { if (!rs.Read()) { return false; } return (Convert.ToInt32(rs.GetInt32(0)) > 0); } } } //--------------------------------------------------------------------------- // calendars //--------------------------------------------------------------------------- /// <summary> /// Insert a new calendar. /// </summary> /// <param name="conn">the DB Connection</param> /// <param name="calendarName">The name for the new calendar.</param> /// <param name="calendar">The calendar.</param> /// <returns>the number of rows inserted</returns> /// <throws> IOException </throws> public virtual int InsertCalendar(ConnectionAndTransactionHolder conn, string calendarName, ICalendar calendar) { byte[] baos = SerializeObject(calendar); using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlInsertCalendar))) { AddCommandParameter(cmd, "calendarName", calendarName); AddCommandParameter(cmd, "calendar", baos, dbProvider.Metadata.DbBinaryType); return cmd.ExecuteNonQuery(); } } /// <summary> /// Update a calendar. /// </summary> /// <param name="conn">the DB Connection</param> /// <param name="calendarName">The name for the new calendar.</param> /// <param name="calendar">The calendar.</param> /// <returns>the number of rows updated</returns> /// <throws> IOException </throws> public virtual int UpdateCalendar(ConnectionAndTransactionHolder conn, string calendarName, ICalendar calendar) { byte[] baos = SerializeObject(calendar); using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlUpdateCalendar))) { AddCommandParameter(cmd, "calendar", baos, dbProvider.Metadata.DbBinaryType); AddCommandParameter(cmd, "calendarName", calendarName); return cmd.ExecuteNonQuery(); } } /// <summary> /// Check whether or not a calendar exists. /// </summary> /// <param name="conn">the DB Connection</param> /// <param name="calendarName">The name of the calendar.</param> /// <returns> /// true if the trigger exists, false otherwise /// </returns> public virtual bool CalendarExists(ConnectionAndTransactionHolder conn, string calendarName) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectCalendarExistence))) { AddCommandParameter(cmd, "calendarName", calendarName); using (IDataReader rs = cmd.ExecuteReader()) { if (rs.Read()) { return true; } return false; } } } /// <summary> /// Select a calendar. /// </summary> /// <param name="conn">the DB Connection</param> /// <param name="calendarName">The name of the calendar.</param> /// <returns>the Calendar</returns> /// <throws> ClassNotFoundException </throws> /// <throws> IOException </throws> public virtual ICalendar SelectCalendar(ConnectionAndTransactionHolder conn, string calendarName) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectCalendar))) { AddCommandParameter(cmd, "calendarName", calendarName); using (IDataReader rs = cmd.ExecuteReader()) { ICalendar cal = null; if (rs.Read()) { cal = (ICalendar) GetObjectFromBlob(rs, 2); } if (null == cal) { logger.Warn("Couldn't find calendar with name '" + calendarName + "'."); } return cal; } } } /// <summary> /// Check whether or not a calendar is referenced by any triggers. /// </summary> /// <param name="conn">the DB Connection</param> /// <param name="calendarName">The name of the calendar.</param> /// <returns> /// true if any triggers reference the calendar, false otherwise /// </returns> public virtual bool CalendarIsReferenced(ConnectionAndTransactionHolder conn, string calendarName) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectReferencedCalendar))) { AddCommandParameter(cmd, "calendarName", calendarName); using (IDataReader rs = cmd.ExecuteReader()) { if (rs.Read()) { return true; } return false; } } } /// <summary> /// Delete a calendar. /// </summary> /// <param name="conn">the DB Connection</param> /// <param name="calendarName">The name of the trigger.</param> /// <returns>the number of rows deleted</returns> public virtual int DeleteCalendar(ConnectionAndTransactionHolder conn, string calendarName) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlDeleteCalendar))) { AddCommandParameter(cmd, "calendarName", calendarName); return cmd.ExecuteNonQuery(); } } /// <summary> /// Select the total number of calendars stored. /// </summary> /// <param name="conn">the DB Connection</param> /// <returns>the total number of calendars stored</returns> public virtual int SelectNumCalendars(ConnectionAndTransactionHolder conn) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectNumCalendars))) { int count = 0; using (IDataReader rs = cmd.ExecuteReader()) { if (rs.Read()) { count = Convert.ToInt32(rs.GetValue(0), CultureInfo.InvariantCulture); } return count; } } } /// <summary> /// Select all of the stored calendars. /// </summary> /// <param name="conn">the DB Connection</param> /// <returns> /// an array of <see cref="String" /> calendar names /// </returns> public virtual IList<string> SelectCalendars(ConnectionAndTransactionHolder conn) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectCalendars))) { using (IDataReader rs = cmd.ExecuteReader()) { List<string> list = new List<string>(); while (rs.Read()) { list.Add((string) rs[0]); } return list.ToArray(); } } } //--------------------------------------------------------------------------- // trigger firing //--------------------------------------------------------------------------- /// <summary> /// Select the trigger that will be fired at the given fire time. /// </summary> /// <param name="conn">the DB Connection</param> /// <param name="fireTime">the time that the trigger will be fired</param> /// <returns> /// a <see cref="TriggerKey" /> representing the /// trigger that will be fired at the given fire time, or null if no /// trigger will be fired at that time /// </returns> public virtual TriggerKey SelectTriggerForFireTime(ConnectionAndTransactionHolder conn, DateTimeOffset fireTime) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectTriggerForFireTime))) { AddCommandParameter(cmd, "state", StateWaiting); AddCommandParameter(cmd, "fireTime", Convert.ToDecimal(fireTime.Ticks)); using (IDataReader rs = cmd.ExecuteReader()) { if (rs.Read()) { return new TriggerKey(rs.GetString(ColumnTriggerName), rs.GetString(ColumnTriggerGroup)); } return null; } } } /// <summary> /// Select the next trigger which will fire to fire between the two given timestamps /// in ascending order of fire time, and then descending by priority. /// </summary> /// <param name="conn">The conn.</param> /// <param name="noLaterThan">highest value of <see cref="ITrigger.GetNextFireTimeUtc"/> of the triggers (exclusive)</param> /// <param name="noEarlierThan">highest value of <see cref="ITrigger.GetNextFireTimeUtc"/> of the triggers (inclusive)</param> /// <returns></returns> public virtual IList<TriggerKey> SelectTriggerToAcquire(ConnectionAndTransactionHolder conn, DateTimeOffset noLaterThan, DateTimeOffset noEarlierThan) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectNextTriggerToAcquire))) { List<TriggerKey> nextTriggers = new List<TriggerKey>(); AddCommandParameter(cmd, "state", StateWaiting); AddCommandParameter(cmd, "noLaterThan", Convert.ToDecimal(noLaterThan.Ticks)); AddCommandParameter(cmd, "noEarlierThan", Convert.ToDecimal(noEarlierThan.Ticks)); using (IDataReader rs = cmd.ExecuteReader()) { int limit = TriggersToAcquireLimit; while (rs.Read() && nextTriggers.Count < limit) { nextTriggers.Add(new TriggerKey((string)rs[ColumnTriggerName], (string)rs[ColumnTriggerGroup])); } } return nextTriggers; } } /// <summary> /// Gets the triggers to acquire limit. /// </summary> /// <value>The triggers to acquire limit.</value> protected virtual int TriggersToAcquireLimit { get { return DefaultTriggersToAcquireLimit; } } /// <summary> /// Gets the select next trigger to acquire SQL clause. /// This can be overriden for a more performant, result limiting /// SQL. For Example SQL Server, MySQL and SQLite support limiting returned rows. /// </summary> /// <returns></returns> protected virtual string GetSelectNextTriggerToAcquireSql() { return SqlSelectNextTriggerToAcquire; } /// <summary> /// Insert a fired trigger. /// </summary> /// <param name="conn">the DB Connection</param> /// <param name="trigger">the trigger</param> /// <param name="state">the state that the trigger should be stored in</param> /// <param name="job">The job.</param> /// <returns>the number of rows inserted</returns> public virtual int InsertFiredTrigger(ConnectionAndTransactionHolder conn, IOperableTrigger trigger, string state, IJobDetail job) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlInsertFiredTrigger))) { AddCommandParameter(cmd, "triggerEntryId", trigger.FireInstanceId); AddCommandParameter(cmd, "triggerName", trigger.Key.Name); AddCommandParameter(cmd, "triggerGroup", trigger.Key.Group); AddCommandParameter(cmd, "triggerInstanceName", instanceId); AddCommandParameter(cmd, "triggerFireTime", Convert.ToDecimal(trigger.GetNextFireTimeUtc().Value.Ticks)); AddCommandParameter(cmd, "triggerState", state); if (job != null) { AddCommandParameter(cmd, "triggerJobName", trigger.JobKey.Name); AddCommandParameter(cmd, "triggerJobGroup", trigger.JobKey.Group); AddCommandParameter(cmd, "triggerJobStateful", GetDbBooleanValue(job.ConcurrentExectionDisallowed)); AddCommandParameter(cmd, "triggerJobRequestsRecovery", GetDbBooleanValue(job.RequestsRecovery)); } else { AddCommandParameter(cmd, "triggerJobName", null); AddCommandParameter(cmd, "triggerJobGroup", null); AddCommandParameter(cmd, "triggerJobStateful", GetDbBooleanValue(false)); AddCommandParameter(cmd, "triggerJobRequestsRecovery", GetDbBooleanValue(false)); } AddCommandParameter(cmd, "triggerPriority", trigger.Priority); return cmd.ExecuteNonQuery(); } } /// <summary> /// <p> /// Update a fired trigger. /// </p> /// </summary> /// <remarks> /// </remarks> /// <param name="conn"></param> /// the DB Connection /// <param name="trigger"></param> /// the trigger /// <param name="state"></param> /// the state that the trigger should be stored in /// <returns>the number of rows inserted</returns> public int UpdateFiredTrigger(ConnectionAndTransactionHolder conn, IOperableTrigger trigger, string state, IJobDetail job) { IDbCommand ps = PrepareCommand(conn, ReplaceTablePrefix(SqlUpdateFiredTrigger)); AddCommandParameter(ps, "instanceName", instanceId); AddCommandParameter(ps, "firedTime", trigger.GetNextFireTimeUtc().Value.Ticks); AddCommandParameter(ps, "entryState", state); if (job != null) { AddCommandParameter(ps, "jobName", trigger.JobKey.Name); AddCommandParameter(ps, "jobGroup", trigger.JobKey.Group); AddCommandParameter(ps, "isNonConcurrent", job.ConcurrentExectionDisallowed); AddCommandParameter(ps, "requestsRecover", job.RequestsRecovery); } else { AddCommandParameter(ps, "jobName", null); AddCommandParameter(ps, "JobGroup", null); AddCommandParameter(ps, "isNonConcurrent", false); AddCommandParameter(ps, "requestsRecover", false); } AddCommandParameter(ps, "entryId", trigger.FireInstanceId); return ps.ExecuteNonQuery(); } /// <summary> /// Select the states of all fired-trigger records for a given trigger, or /// trigger group if trigger name is <see langword="null" />. /// </summary> /// <param name="conn">The DB connection.</param> /// <param name="triggerName">Name of the trigger.</param> /// <param name="groupName">Name of the group.</param> /// <returns>a List of <see cref="FiredTriggerRecord" /> objects.</returns> public virtual IList<FiredTriggerRecord> SelectFiredTriggerRecords(ConnectionAndTransactionHolder conn, string triggerName, string groupName) { IDbCommand cmd; IList<FiredTriggerRecord> lst = new List<FiredTriggerRecord>(); if (triggerName != null) { cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectFiredTrigger)); AddCommandParameter(cmd, "triggerName", triggerName); AddCommandParameter(cmd, "triggerGroup", groupName); } else { cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectFiredTriggerGroup)); AddCommandParameter(cmd, "triggerGroup", groupName); } using (IDataReader rs = cmd.ExecuteReader()) { while (rs.Read()) { FiredTriggerRecord rec = new FiredTriggerRecord(); rec.FireInstanceId = rs.GetString(ColumnEntryId); rec.FireInstanceState = rs.GetString(ColumnEntryState); rec.FireTimestamp = Convert.ToInt64(rs[ColumnFiredTime], CultureInfo.InvariantCulture); rec.Priority = Convert.ToInt32(rs[ColumnPriority], CultureInfo.InvariantCulture); rec.SchedulerInstanceId = rs.GetString(ColumnInstanceName); rec.TriggerKey = new TriggerKey(rs.GetString(ColumnTriggerName), rs.GetString(ColumnTriggerGroup)); if (!rec.FireInstanceState.Equals(StateAcquired)) { rec.JobDisallowsConcurrentExecution = rs.GetBoolean(ColumnIsNonConcurrent); rec.JobRequestsRecovery = rs.GetBoolean(ColumnRequestsRecovery); rec.JobKey = new JobKey(rs.GetString(ColumnJobName), rs.GetString(ColumnJobGroup)); } lst.Add(rec); } } return lst; } /// <summary> /// Select the states of all fired-trigger records for a given job, or job /// group if job name is <see langword="null" />. /// </summary> /// <param name="conn">The DB connection.</param> /// <param name="jobName">Name of the job.</param> /// <param name="groupName">Name of the group.</param> /// <returns>a List of <see cref="FiredTriggerRecord" /> objects.</returns> public virtual IList<FiredTriggerRecord> SelectFiredTriggerRecordsByJob(ConnectionAndTransactionHolder conn, string jobName, string groupName) { IList<FiredTriggerRecord> lst = new List<FiredTriggerRecord>(); IDbCommand cmd; if (jobName != null) { cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectFiredTriggersOfJob)); AddCommandParameter(cmd, "jobName", jobName); AddCommandParameter(cmd, "jobGroup", groupName); } else { cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectFiredTriggersOfJobGroup)); AddCommandParameter(cmd, "jobGroup", groupName); } using (IDataReader rs = cmd.ExecuteReader()) { while (rs.Read()) { FiredTriggerRecord rec = new FiredTriggerRecord(); rec.FireInstanceId = rs.GetString(ColumnEntryId); rec.FireInstanceState = rs.GetString(ColumnEntryState); rec.FireTimestamp = Convert.ToInt64(rs[ColumnFiredTime], CultureInfo.InvariantCulture); rec.Priority = Convert.ToInt32(rs[ColumnPriority], CultureInfo.InvariantCulture); rec.SchedulerInstanceId = rs.GetString(ColumnInstanceName); rec.TriggerKey = new TriggerKey(rs.GetString(ColumnTriggerName), rs.GetString(ColumnTriggerGroup)); if (!rec.FireInstanceState.Equals(StateAcquired)) { rec.JobDisallowsConcurrentExecution = rs.GetBoolean(ColumnIsNonConcurrent); rec.JobRequestsRecovery = rs.GetBoolean(ColumnRequestsRecovery); rec.JobKey = new JobKey(rs.GetString(ColumnJobName), rs.GetString(ColumnJobGroup)); } lst.Add(rec); } } return lst; } /// <summary> /// Select the states of all fired-trigger records for a given scheduler /// instance. /// </summary> /// <param name="conn">The DB Connection</param> /// <param name="instanceName">Name of the instance.</param> /// <returns>A list of FiredTriggerRecord objects.</returns> public virtual IList<FiredTriggerRecord> SelectInstancesFiredTriggerRecords(ConnectionAndTransactionHolder conn, string instanceName) { IList<FiredTriggerRecord> lst = new List<FiredTriggerRecord>(); using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectInstancesFiredTriggers))) { AddCommandParameter(cmd, "instanceName", instanceName); using (IDataReader rs = cmd.ExecuteReader()) { while (rs.Read()) { FiredTriggerRecord rec = new FiredTriggerRecord(); rec.FireInstanceId = rs.GetString(ColumnEntryId); rec.FireInstanceState = rs.GetString(ColumnEntryState); rec.FireTimestamp = Convert.ToInt64(rs[ColumnFiredTime], CultureInfo.InvariantCulture); rec.SchedulerInstanceId = rs.GetString(ColumnInstanceName); rec.TriggerKey = new TriggerKey(rs.GetString(ColumnTriggerName), rs.GetString(ColumnTriggerGroup)); if (!rec.FireInstanceState.Equals(StateAcquired)) { rec.JobDisallowsConcurrentExecution = rs.GetBoolean(ColumnIsNonConcurrent); rec.JobRequestsRecovery = rs.GetBoolean(ColumnRequestsRecovery); rec.JobKey = new JobKey(rs.GetString(ColumnJobName), rs.GetString(ColumnJobGroup)); } lst.Add(rec); } } return lst; } } /// <summary> /// Select the distinct instance names of all fired-trigger records. /// </summary> /// <param name="conn">The conn.</param> /// <returns></returns> /// <remarks> /// This is useful when trying to identify orphaned fired triggers (a /// fired trigger without a scheduler state record.) /// </remarks> public Collection.ISet<string> SelectFiredTriggerInstanceNames(ConnectionAndTransactionHolder conn) { Collection.HashSet<string> instanceNames = new Collection.HashSet<string>(); using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectFiredTriggerInstanceNames))) { using (IDataReader rs = cmd.ExecuteReader()) { while (rs.Read()) { instanceNames.Add(rs.GetString(ColumnInstanceName)); } return instanceNames; } } } /// <summary> /// Delete a fired trigger. /// </summary> /// <param name="conn">the DB Connection</param> /// <param name="entryId">the fired trigger entry to delete</param> /// <returns>the number of rows deleted</returns> public virtual int DeleteFiredTrigger(ConnectionAndTransactionHolder conn, string entryId) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlDeleteFiredTrigger))) { AddCommandParameter(cmd, "triggerEntryId", entryId); return cmd.ExecuteNonQuery(); } } /// <summary> /// Selects the job execution count. /// </summary> /// <param name="conn">The DB connection.</param> /// <param name="jobKey">The key of the job.</param> /// <returns></returns> public virtual int SelectJobExecutionCount(ConnectionAndTransactionHolder conn, JobKey jobKey) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectJobExecutionCount))) { AddCommandParameter(cmd, "jobName", jobKey.Name); AddCommandParameter(cmd, "jobGroup", jobKey.Group); using (IDataReader rs = cmd.ExecuteReader()) { if (rs.Read()) { return Convert.ToInt32(rs.GetValue(0), CultureInfo.InvariantCulture); } return 0; } } } /// <summary> /// Inserts the state of the scheduler. /// </summary> /// <param name="conn">The conn.</param> /// <param name="instanceName">The instance id.</param> /// <param name="checkInTime">The check in time.</param> /// <param name="interval">The interval.</param> /// <returns></returns> public virtual int InsertSchedulerState(ConnectionAndTransactionHolder conn, string instanceName, DateTimeOffset checkInTime, TimeSpan interval) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlInsertSchedulerState))) { AddCommandParameter(cmd, "instanceName", instanceName); AddCommandParameter(cmd, "lastCheckinTime", checkInTime.Ticks); AddCommandParameter(cmd, "checkinInterval", interval.TotalMilliseconds); return cmd.ExecuteNonQuery(); } } /// <summary> /// Deletes the state of the scheduler. /// </summary> /// <param name="conn">The database connection.</param> /// <param name="instanceName">The instance id.</param> /// <returns></returns> public virtual int DeleteSchedulerState(ConnectionAndTransactionHolder conn, string instanceName) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlDeleteSchedulerState))) { AddCommandParameter(cmd, "instanceName", instanceName); return cmd.ExecuteNonQuery(); } } /// <summary> /// Updates the state of the scheduler. /// </summary> /// <param name="conn">The database connection.</param> /// <param name="instanceName">The instance id.</param> /// <param name="checkInTime">The check in time.</param> /// <returns></returns> public virtual int UpdateSchedulerState(ConnectionAndTransactionHolder conn, string instanceName, DateTimeOffset checkInTime) { using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlUpdateSchedulerState))) { AddCommandParameter(cmd, "lastCheckinTime", checkInTime.Ticks); AddCommandParameter(cmd, "instanceName", instanceName); return cmd.ExecuteNonQuery(); } } /// <summary> /// A List of all current <see cref="SchedulerStateRecord" />s. /// <p> /// If instanceId is not null, then only the record for the identified /// instance will be returned. /// </p> /// </summary> /// <param name="conn">The DB Connection</param> /// <param name="instanceName">The instance id.</param> /// <returns></returns> public virtual IList<SchedulerStateRecord> SelectSchedulerStateRecords(ConnectionAndTransactionHolder conn, string instanceName) { IDbCommand cmd; List<SchedulerStateRecord> list = new List<SchedulerStateRecord>(); if (instanceName != null) { cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectSchedulerState)); AddCommandParameter(cmd, "instanceName", instanceName); } else { cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectSchedulerStates)); } using (IDataReader rs = cmd.ExecuteReader()) { while (rs.Read()) { SchedulerStateRecord rec = new SchedulerStateRecord(); rec.SchedulerInstanceId = rs.GetString(ColumnInstanceName); rec.CheckinTimestamp = new DateTimeOffset(Convert.ToInt64(rs[ColumnLastCheckinTime], CultureInfo.InvariantCulture), TimeSpan.Zero); rec.CheckinInterval = TimeSpan.FromMilliseconds(Convert.ToInt64(rs[ColumnCheckinInterval], CultureInfo.InvariantCulture)); list.Add(rec); } } return list; } //--------------------------------------------------------------------------- // protected methods that can be overridden by subclasses //--------------------------------------------------------------------------- /// <summary> /// Replace the table prefix in a query by replacing any occurrences of /// "{0}" with the table prefix. /// </summary> /// <param name="query">The unsubstitued query</param> /// <returns>The query, with proper table prefix substituted</returns> protected internal string ReplaceTablePrefix(string query) { return AdoJobStoreUtil.ReplaceTablePrefix(query, tablePrefix, SchedulerNameLiteral); } private string schedNameLiteral; protected string SchedulerNameLiteral { get { if (schedNameLiteral == null) { schedNameLiteral = "'" + schedName + "'"; } return schedNameLiteral; } } /// <summary> /// Create a serialized <see lanword="byte[]"/> version of an Object. /// </summary> /// <param name="obj">the object to serialize</param> /// <returns>Serialized object as byte array.</returns> protected internal virtual byte[] SerializeObject(object obj) { byte[] retValue = null; if (null != obj) { MemoryStream ms = new MemoryStream(); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(ms, obj); retValue = ms.ToArray(); } return retValue; } /// <summary> /// Remove the transient data from and then create a serialized <see cref="MemoryStream" /> /// version of a <see cref="JobDataMap" /> and returns the underlying bytes. /// </summary> /// <param name="data">The data.</param> /// <returns>the serialized data as byte array</returns> public virtual byte[] SerializeJobData(JobDataMap data) { if (CanUseProperties) { return SerializeProperties(data); } try { return SerializeObject(data); } catch (SerializationException e) { throw new SerializationException( "Unable to serialize JobDataMap for insertion into " + "database because the value of property '" + GetKeyOfNonSerializableValue((IDictionary) data) + "' is not serializable: " + e.Message); } } protected object GetKeyOfNonSerializableValue(IDictionary data) { foreach (DictionaryEntry entry in data) { try { SerializeObject(entry.Value); } catch (Exception) { return entry.Key; } } // As long as it is true that the Map was not serializable, we should // not hit this case. return null; } /// <summary> /// serialize /// </summary> /// <param name="data">The data.</param> /// <returns></returns> private byte[] SerializeProperties(JobDataMap data) { byte[] retValue = null; if (null != data) { NameValueCollection properties = ConvertToProperty(data.WrappedMap); retValue = SerializeObject(properties); } return retValue; } /// <summary> /// Convert the JobDataMap into a list of properties. /// </summary> protected virtual IDictionary ConvertFromProperty(NameValueCollection properties) { IDictionary<string, string> data = new Dictionary<string, string>(); foreach (string key in properties.AllKeys) { data[key] = properties[key]; } return (IDictionary) data; } /// <summary> /// Convert the JobDataMap into a list of properties. /// </summary> protected internal virtual NameValueCollection ConvertToProperty(IDictionary<string, object> data) { NameValueCollection properties = new NameValueCollection(); foreach (KeyValuePair<string, object> entry in data) { object key = entry.Key; object val = entry.Value ?? string.Empty; if (!(key is string)) { throw new IOException("JobDataMap keys/values must be Strings " + "when the 'useProperties' property is set. " + " offending Key: " + key); } if (!(val is string)) { throw new IOException("JobDataMap values must be Strings " + "when the 'useProperties' property is set. " + " Key of offending value: " + key); } properties[(string)key] = (string)val; } return properties; } /// <summary> /// This method should be overridden by any delegate subclasses that need /// special handling for BLOBs. The default implementation uses standard /// ADO.NET operations. /// </summary> /// <param name="rs">The data reader, already queued to the correct row.</param> /// <param name="colIndex">The column index for the BLOB.</param> /// <returns>The deserialized object from the DataReader BLOB.</returns> protected internal virtual object GetObjectFromBlob(IDataReader rs, int colIndex) { object obj = null; byte[] data = ReadBytesFromBlob(rs, colIndex); if (data != null && data.Length > 0) { MemoryStream ms = new MemoryStream(data); BinaryFormatter bf = new BinaryFormatter(); obj = bf.Deserialize(ms); } return obj; } protected virtual byte[] ReadBytesFromBlob(IDataReader dr, int colIndex) { if (dr.IsDBNull(colIndex)) { return null; } byte[] outbyte = new byte[dr.GetBytes(colIndex, 0, null, 0, Int32.MaxValue)]; dr.GetBytes(colIndex, 0, outbyte, 0, outbyte.Length); using (MemoryStream stream = new MemoryStream()) { stream.Write(outbyte, 0, outbyte.Length); } return outbyte; } /// <summary> /// This method should be overridden by any delegate subclasses that need /// special handling for BLOBs for job details. /// </summary> /// <param name="rs">The result set, already queued to the correct row.</param> /// <param name="colIndex">The column index for the BLOB.</param> /// <returns>The deserialized Object from the ResultSet BLOB.</returns> protected virtual object GetJobDataFromBlob(IDataReader rs, int colIndex) { if (CanUseProperties) { if (!rs.IsDBNull(colIndex)) { // should be NameValueCollection return GetObjectFromBlob(rs, colIndex); } return null; } return GetObjectFromBlob(rs, colIndex); } /// <summary> /// Selects the paused trigger groups. /// </summary> /// <param name="conn">The DB Connection.</param> /// <returns></returns> public virtual Collection.ISet<string> SelectPausedTriggerGroups(ConnectionAndTransactionHolder conn) { Collection.HashSet<string> retValue = new Collection.HashSet<string>(); using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectPausedTriggerGroups))) { using (IDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { string groupName = (string)dr[ColumnTriggerGroup]; retValue.Add(groupName); } } return retValue; } } protected virtual IDbCommand PrepareCommand(ConnectionAndTransactionHolder cth, string commandText) { return adoUtil.PrepareCommand(cth, commandText); } protected virtual void AddCommandParameter(IDbCommand cmd, string paramName, object paramValue) { AddCommandParameter(cmd, paramName, paramValue, null); } protected virtual void AddCommandParameter(IDbCommand cmd, string paramName, object paramValue, Enum dataType) { adoUtil.AddCommandParameter(cmd, paramName, paramValue, dataType); } } }
42.36569
207
0.541201
[ "Apache-2.0" ]
Leftyx/quartznet
src/Quartz/Impl/AdoJobStore/StdAdoDelegate.cs
120,022
C#
using UnityEngine; public class ShapeGenerator { private readonly ShapeSettings settings; private readonly NoiseFilter[] noiseFilters; public ShapeGenerator(ShapeSettings settings) { this.settings = settings; var layers = settings.GetNoiseLayers; noiseFilters = new NoiseFilter[layers.Count]; for (int i = 0; i < noiseFilters.Length; i++) { noiseFilters[i] = new NoiseFilter(layers[i].noiseSettings); } } public Vector3 CalculatePointOnPlanet(Vector3 pointOnUnitSphere) { float elevation = 0; for (int i = 0; i < noiseFilters.Length; i++) { if (settings.LayerEnabled(i)) { elevation += noiseFilters[i].Evaluate(pointOnUnitSphere); } } return pointOnUnitSphere * settings.GetRadius * (elevation + 1f); } }
23.684211
73
0.602222
[ "MIT" ]
tomi901/Random-Unity-Stuff
Assets/Planet Generator/ShapeGenerator.cs
902
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; namespace Dynamo { public static class Extensions { public static void WriteAll (this ICodeElement elem, ICodeWriter writer) { object memento = elem.BeginWrite (writer); elem.Write (writer, memento); ICodeElementSet set = elem as ICodeElementSet; if (set != null) { foreach (ICodeElement sub in set.Elements) { sub.WriteAll (writer); } } elem.EndWrite (writer, memento); } public static void FireInReverse<T> (this EventHandler<T> handler, object sender, EventArgs args) where T : EventArgs { var dels = handler.GetInvocationList (); for (int i = dels.Length - 1; i >= 0; i--) { dels [i].DynamicInvoke (new object [] { sender, args }); } } public static IEnumerable<T> Interleave<T> (this IEnumerable<T> contents, T separator, bool includeSeparatorFirst = false) { bool first = true; foreach (T t in contents) { if (!first || includeSeparatorFirst) yield return separator; first = false; yield return t; } } public static IEnumerable<T> BracketInterleave<T> (this IEnumerable<T> contents, T start, T end, T separator, bool includeSeparatorFirst = false) { yield return start; foreach (T t in contents.Interleave (separator, includeSeparatorFirst)) yield return t; yield return end; } public static T AttachBefore<T> (this T attacher, ICodeElement attachTo) where T : ICodeElement { Exceptions.ThrowOnNull (attachTo, nameof (attachTo)); attachTo.Begin += (s, eventArgs) => { attacher.WriteAll (eventArgs.Writer); }; return attacher; } public static T AttachAfter<T> (this T attacher, ICodeElement attachTo) where T : ICodeElement { Exceptions.ThrowOnNull (attachTo, nameof (attachTo)); attachTo.End += (s, eventArgs) => { attacher.WriteAll (eventArgs.Writer); }; return attacher; } } }
28.536232
147
0.687151
[ "MIT" ]
a-churchill/binding-tools-for-swift
Dynamo/Extensions.cs
1,969
C#
using DSLink.Nodes; using DoubleRobotics; using DSLink.Nodes.Actions; using DSLink.Request; using Newtonsoft.Json.Linq; namespace DSAMobile.iOS.Modules { public class DoubleRobotModule : BaseModule { private DRDouble _robot; private Node _robotNode; public bool Supported => true; public bool RequestPermissions() { return true; } public void AddNodes(Node superRoot) { _robot = new DRDouble(); _robotNode = superRoot.CreateChild("robot") .SetDisplayName("Robot") .BuildNode(); _robotNode.CreateChild("setPark") .SetDisplayName("Set Park") .AddParameter(new Parameter("state", "bool")) .SetAction(new ActionHandler(Permission.Write, SetParkState)) .BuildNode(); _robotNode.CreateChild("poleDown") .SetDisplayName("Pole Down") .SetAction(new ActionHandler(Permission.Write, PoleDown)) .BuildNode(); _robotNode.CreateChild("poleUp") .SetDisplayName("Pole Up") .SetAction(new ActionHandler(Permission.Write, PoleUp)) .BuildNode(); _robotNode.CreateChild("poleStop") .SetDisplayName("Pole Stop") .SetAction(new ActionHandler(Permission.Write, PoleStop)) .BuildNode(); _robotNode.CreateChild("turnByDegrees") .SetDisplayName("Turn by degrees") .AddParameter(new Parameter("degrees", "number")) .SetAction(new ActionHandler(Permission.Write, TurnByDegrees)) .BuildNode(); _robotNode.CreateChild("drive") .SetDisplayName("Drive") .AddParameter(new Parameter("direction", "enum[forward,backward,stop]")) .AddParameter(new Parameter("leftRight", "number")) .SetAction(new ActionHandler(Permission.Write, Drive)) .BuildNode(); } public void Start() { } public void Stop() { } public async void SetParkState(InvokeRequest request) { JToken stateToken = request.Parameters["state"]; if (stateToken.Type == JTokenType.Boolean) { if (stateToken.Value<bool>()) { _robot.DeployKickstands(); } else { _robot.RetractKickstands(); } } await request.Close(); } public async void PoleDown(InvokeRequest request) { _robot.PoleDown(); await request.Close(); } public async void PoleUp(InvokeRequest request) { _robot.PoleUp(); await request.Close(); } public async void PoleStop(InvokeRequest request) { _robot.PoleStop(); await request.Close(); } public async void TurnByDegrees(InvokeRequest request) { var degreeToken = request.Parameters["degrees"]; if (degreeToken.Type == JTokenType.Float) { _robot.TurnByDegrees(degreeToken.Value<float>()); } await request.Close(); } public async void Drive(InvokeRequest request) { var directionToken = request.Parameters["direction"]; var leftRightToken = request.Parameters["leftRight"]; if (directionToken.Type == JTokenType.String && leftRightToken.Type == JTokenType.Float) { string direction = directionToken.Value<string>(); float leftRight = leftRightToken.Value<float>(); DRDriveDirection? actualDirection = null; switch (direction) { case "forward": actualDirection = DRDriveDirection.Forward; break; case "backward": actualDirection = DRDriveDirection.Backward; break; case "stop": actualDirection = DRDriveDirection.Stop; break; } if (actualDirection.HasValue) { _robot.Drive(actualDirection.Value, leftRight); } } await request.Close(); } public async void Stop(InvokeRequest request) { _robot.Drive(DRDriveDirection.Stop, 0.0f); await request.Close(); } } }
32.23871
94
0.495097
[ "Apache-2.0" ]
IOT-DSA/dslink-dotnet-mobile
DSA Mobile/DSAMobile.iOS/Modules/DoubleRobotModule.cs
4,999
C#
// ReSharper disable StringLiteralTypo // ReSharper disable IdentifierTypo // ReSharper disable InconsistentNaming // ReSharper disable UnusedType.Global namespace InControl.UnityDeviceProfiles { using System; // @cond nodoc [Preserve] [UnityInputDeviceProfile] public class EightBitdoSNES30WindowsUnityProfile : InputDeviceProfile { public override void Define() { base.Define(); DeviceName = "8Bitdo SNES30 Controller"; DeviceNotes = "8Bitdo SNES30 Controller on Windows"; // Link = "https://www.amazon.com/Wireless-Bluetooth-Controller-Classic-Joystick/dp/B014QP2H1E"; DeviceClass = InputDeviceClass.Controller; DeviceStyle = InputDeviceStyle.NintendoSNES; IncludePlatforms = new[] { "Windows" }; Matchers = new[] { new InputDeviceMatcher { NameLiteral = "SNES30 Joy " } }; ButtonMappings = new[] { new InputControlMapping { Name = "A", Target = InputControlType.Action2, Source = Button( 0 ), }, new InputControlMapping { Name = "B", Target = InputControlType.Action1, Source = Button( 1 ), }, new InputControlMapping { Name = "X", Target = InputControlType.Action4, Source = Button( 3 ), }, new InputControlMapping { Name = "Y", Target = InputControlType.Action3, Source = Button( 4 ), }, new InputControlMapping { Name = "L", Target = InputControlType.LeftTrigger, Source = Button( 6 ), }, new InputControlMapping { Name = "R", Target = InputControlType.RightTrigger, Source = Button( 7 ), }, new InputControlMapping { Name = "Select", Target = InputControlType.Select, Source = Button( 10 ), }, new InputControlMapping { Name = "Start", Target = InputControlType.Start, Source = Button( 11 ), }, }; AnalogMappings = new[] { new InputControlMapping { Name = "DPad Left", Target = InputControlType.DPadLeft, Source = Analog( 0 ), SourceRange = InputRangeType.ZeroToMinusOne, TargetRange = InputRangeType.ZeroToOne, }, new InputControlMapping { Name = "DPad Right", Target = InputControlType.DPadRight, Source = Analog( 0 ), SourceRange = InputRangeType.ZeroToOne, TargetRange = InputRangeType.ZeroToOne, }, new InputControlMapping { Name = "DPad Up", Target = InputControlType.DPadUp, Source = Analog( 1 ), SourceRange = InputRangeType.ZeroToMinusOne, TargetRange = InputRangeType.ZeroToOne, }, new InputControlMapping { Name = "DPad Down", Target = InputControlType.DPadDown, Source = Analog( 1 ), SourceRange = InputRangeType.ZeroToOne, TargetRange = InputRangeType.ZeroToOne, }, }; } } // @endcond }
22.975806
99
0.637417
[ "MIT" ]
EstasAnt/Estsoul
Assets/InControl/Source/Unity/DeviceProfiles/Windows/EightBitdoSNES30WindowsUnityProfile.cs
2,849
C#
using Silk.Data.Modelling; using Silk.Data.Modelling.Mapping; using Silk.Data.SQL.ORM.Schema; using Silk.Data.SQL.Queries; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace Silk.Data.SQL.ORM.Queries { public class MappingReader<T> : IResultReader<T> where T : class { private readonly IMapping<EntityModel, EntityField, TypeModel, PropertyInfoField> _mapping; public ITypeInstanceFactory TypeInstanceFactory { get; set; } = DefaultTypeInstanceFactory.Instance; public IReaderWriterFactory<TypeModel, PropertyInfoField> TypeReaderWriterFactory { get; set; } = DefaultReaderWriterFactory.Instance; public MappingReader(IMapping<EntityModel, EntityField, TypeModel, PropertyInfoField> mapping) { _mapping = mapping; } public T Read(QueryResult queryResult) { var graph = TypeInstanceFactory.CreateInstance<T>(); var outputWriter = TypeReaderWriterFactory.CreateGraphWriter<T>(graph); var inputReader = new QueryGraphReader(queryResult); _mapping.Map(inputReader, outputWriter); return graph; } } public class DefaultReaderWriterFactory : IReaderWriterFactory<TypeModel, PropertyInfoField> { public static DefaultReaderWriterFactory Instance { get; } = new DefaultReaderWriterFactory(); public IGraphReader<TypeModel, PropertyInfoField> CreateGraphReader<T>(T graph) => new ObjectGraphReader<T>(graph); public IGraphWriter<TypeModel, PropertyInfoField> CreateGraphWriter<T>(T graph) where T : class => new ObjectGraphReaderWriter<T>(graph); } public class DefaultTypeInstanceFactory : ITypeInstanceFactory { public static DefaultTypeInstanceFactory Instance { get; } = new DefaultTypeInstanceFactory(); public T CreateInstance<T>() { var factory = GetFactory<T>(); return factory(); } private static readonly Dictionary<Type, Delegate> _factories = new Dictionary<Type, Delegate>(); private static ConstructorInfo GetParameterlessConstructor(Type type) { return type .GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) .FirstOrDefault(ctor => ctor.GetParameters().Length == 0); } private static Func<T> GetFactory<T>() { var type = typeof(T); if (_factories.TryGetValue(type, out var factory)) return factory as Func<T>; lock (_factories) { if (_factories.TryGetValue(type, out factory)) return factory as Func<T>; factory = CreateFactory<T>(); _factories.Add(type, factory); return factory as Func<T>; } } private static Func<T> CreateFactory<T>() { var ctor = GetParameterlessConstructor(typeof(T)); if (ctor == null) throw new InvalidOperationException($"{typeof(T).FullName} doesn't have a parameterless constructor."); var lambda = Expression.Lambda<Func<T>>( Expression.New(ctor) ); return lambda.Compile(); } } }
29.25
108
0.715648
[ "MIT" ]
SilkStack/Silk.Data.SQL.ORM
Silk.Data.SQL.ORM/Queries/MappingReader.cs
3,044
C#
using System; using System.Collections; using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Prng.Drbg { /** * A SP800-90A Hash DRBG. */ public class HashSP800Drbg : ISP80090Drbg { private readonly static byte[] ONE = { 0x01 }; private readonly static long RESEED_MAX = 1L << (48 - 1); private readonly static int MAX_BITS_REQUEST = 1 << (19 - 1); private static readonly IDictionary seedlens = Platform.CreateHashtable(); static HashSP800Drbg() { seedlens.Add("SHA-1", 440); seedlens.Add("SHA-224", 440); seedlens.Add("SHA-256", 440); seedlens.Add("SHA-512/256", 440); seedlens.Add("SHA-512/224", 440); seedlens.Add("SHA-384", 888); seedlens.Add("SHA-512", 888); } private readonly IDigest mDigest; private readonly IEntropySource mEntropySource; private readonly int mSecurityStrength; private readonly int mSeedLength; private byte[] mV; private byte[] mC; private long mReseedCounter; /** * Construct a SP800-90A Hash DRBG. * <p> * Minimum entropy requirement is the security strength requested. * </p> * @param digest source digest to use for DRB stream. * @param securityStrength security strength required (in bits) * @param entropySource source of entropy to use for seeding/reseeding. * @param personalizationString personalization string to distinguish this DRBG (may be null). * @param nonce nonce to further distinguish this DRBG (may be null). */ public HashSP800Drbg(IDigest digest, int securityStrength, IEntropySource entropySource, byte[] personalizationString, byte[] nonce) { if (securityStrength > DrbgUtilities.GetMaxSecurityStrength(digest)) throw new ArgumentException("Requested security strength is not supported by the derivation function"); if (entropySource.EntropySize < securityStrength) throw new ArgumentException("Not enough entropy for security strength required"); mDigest = digest; mEntropySource = entropySource; mSecurityStrength = securityStrength; mSeedLength = (int)seedlens[digest.AlgorithmName]; // 1. seed_material = entropy_input || nonce || personalization_string. // 2. seed = Hash_df (seed_material, seedlen). // 3. V = seed. // 4. C = Hash_df ((0x00 || V), seedlen). Comment: Preceed V with a byte // of zeros. // 5. reseed_counter = 1. // 6. Return V, C, and reseed_counter as the initial_working_state byte[] entropy = GetEntropy(); byte[] seedMaterial = Arrays.ConcatenateAll(entropy, nonce, personalizationString); byte[] seed = DrbgUtilities.HashDF(mDigest, seedMaterial, mSeedLength); mV = seed; byte[] subV = new byte[mV.Length + 1]; Array.Copy(mV, 0, subV, 1, mV.Length); mC = DrbgUtilities.HashDF(mDigest, subV, mSeedLength); mReseedCounter = 1; } /** * Return the block size (in bits) of the DRBG. * * @return the number of bits produced on each internal round of the DRBG. */ public int BlockSize { get { return mDigest.GetDigestSize () * 8; } } /** * Populate a passed in array with random data. * * @param output output array for generated bits. * @param additionalInput additional input to be added to the DRBG in this step. * @param predictionResistant true if a reseed should be forced, false otherwise. * * @return number of bits generated, -1 if a reseed required. */ public int Generate(byte[] output, byte[] additionalInput, bool predictionResistant) { // 1. If reseed_counter > reseed_interval, then return an indication that a // reseed is required. // 2. If (additional_input != Null), then do // 2.1 w = Hash (0x02 || V || additional_input). // 2.2 V = (V + w) mod 2^seedlen // . // 3. (returned_bits) = Hashgen (requested_number_of_bits, V). // 4. H = Hash (0x03 || V). // 5. V = (V + H + C + reseed_counter) mod 2^seedlen // . // 6. reseed_counter = reseed_counter + 1. // 7. Return SUCCESS, returned_bits, and the new values of V, C, and // reseed_counter for the new_working_state. int numberOfBits = output.Length * 8; if (numberOfBits > MAX_BITS_REQUEST) throw new ArgumentException("Number of bits per request limited to " + MAX_BITS_REQUEST, "output"); if (mReseedCounter > RESEED_MAX) return -1; if (predictionResistant) { Reseed(additionalInput); additionalInput = null; } // 2. if (additionalInput != null) { byte[] newInput = new byte[1 + mV.Length + additionalInput.Length]; newInput[0] = 0x02; Array.Copy(mV, 0, newInput, 1, mV.Length); // TODO: inOff / inLength Array.Copy(additionalInput, 0, newInput, 1 + mV.Length, additionalInput.Length); byte[] w = Hash(newInput); AddTo(mV, w); } // 3. byte[] rv = hashgen(mV, numberOfBits); // 4. byte[] subH = new byte[mV.Length + 1]; Array.Copy(mV, 0, subH, 1, mV.Length); subH[0] = 0x03; byte[] H = Hash(subH); // 5. AddTo(mV, H); AddTo(mV, mC); byte[] c = new byte[4]; c[0] = (byte)(mReseedCounter >> 24); c[1] = (byte)(mReseedCounter >> 16); c[2] = (byte)(mReseedCounter >> 8); c[3] = (byte)mReseedCounter; AddTo(mV, c); mReseedCounter++; Array.Copy(rv, 0, output, 0, output.Length); return numberOfBits; } private byte[] GetEntropy() { byte[] entropy = mEntropySource.GetEntropy(); if (entropy.Length < (mSecurityStrength + 7) / 8) throw new InvalidOperationException("Insufficient entropy provided by entropy source"); return entropy; } // this will always add the shorter length byte array mathematically to the // longer length byte array. // be careful.... private void AddTo(byte[] longer, byte[] shorter) { int off = longer.Length - shorter.Length; uint carry = 0; int i = shorter.Length; while (--i >= 0) { carry += (uint)longer[off + i] + (uint)shorter[i]; longer[off + i] = (byte)carry; carry >>= 8; } i = off; while (--i >= 0) { carry += longer[i]; longer[i] = (byte)carry; carry >>= 8; } } /** * Reseed the DRBG. * * @param additionalInput additional input to be added to the DRBG in this step. */ public void Reseed(byte[] additionalInput) { // 1. seed_material = 0x01 || V || entropy_input || additional_input. // // 2. seed = Hash_df (seed_material, seedlen). // // 3. V = seed. // // 4. C = Hash_df ((0x00 || V), seedlen). // // 5. reseed_counter = 1. // // 6. Return V, C, and reseed_counter for the new_working_state. // // Comment: Precede with a byte of all zeros. byte[] entropy = GetEntropy(); byte[] seedMaterial = Arrays.ConcatenateAll(ONE, mV, entropy, additionalInput); byte[] seed = DrbgUtilities.HashDF(mDigest, seedMaterial, mSeedLength); mV = seed; byte[] subV = new byte[mV.Length + 1]; subV[0] = 0x00; Array.Copy(mV, 0, subV, 1, mV.Length); mC = DrbgUtilities.HashDF(mDigest, subV, mSeedLength); mReseedCounter = 1; } private byte[] Hash(byte[] input) { byte[] hash = new byte[mDigest.GetDigestSize()]; DoHash(input, hash); return hash; } private void DoHash(byte[] input, byte[] output) { mDigest.BlockUpdate(input, 0, input.Length); mDigest.DoFinal(output, 0); } // 1. m = [requested_number_of_bits / outlen] // 2. data = V. // 3. W = the Null string. // 4. For i = 1 to m // 4.1 wi = Hash (data). // 4.2 W = W || wi. // 4.3 data = (data + 1) mod 2^seedlen // . // 5. returned_bits = Leftmost (requested_no_of_bits) bits of W. private byte[] hashgen(byte[] input, int lengthInBits) { int digestSize = mDigest.GetDigestSize(); int m = (lengthInBits / 8) / digestSize; byte[] data = new byte[input.Length]; Array.Copy(input, 0, data, 0, input.Length); byte[] W = new byte[lengthInBits / 8]; byte[] dig = new byte[mDigest.GetDigestSize()]; for (int i = 0; i <= m; i++) { DoHash(data, dig); int bytesToCopy = ((W.Length - i * dig.Length) > dig.Length) ? dig.Length : (W.Length - i * dig.Length); Array.Copy(dig, 0, W, i * dig.Length, bytesToCopy); AddTo(data, ONE); } return W; } } }
33.381944
137
0.548783
[ "MIT" ]
0x070696E65/Symnity
Assets/Plugins/Symnity/Pulgins/crypto/src/crypto/prng/drbg/HashSP800Drbg.cs
9,614
C#
using LinCms.Cache; using LinCms.Cms.Users; using LinCms.Data.Options; using LinCms.Email; using LinCms.Entities; using LinCms.Exceptions; using LinCms.IRepositories; using Microsoft.Extensions.Options; using MimeKit; using System; using System.Threading.Tasks; namespace LinCms.Cms.Account { public class AccountService : IAccountService { private readonly IAuditBaseRepository<LinUser, long> _userRepository; private readonly IEmailSender _emailSender; private readonly MailKitOptions _mailKitOptions; private readonly IUserIdentityService _userIdentityService; private readonly SiteOption _siteOption; private readonly ICache _cacheHelp; public AccountService( IAuditBaseRepository<LinUser, long> userRepository, IEmailSender emailSender, IOptions<MailKitOptions> options, IUserIdentityService userIdentityService, IOptions<SiteOption> siteOption, ICache cache) { _userRepository = userRepository; _emailSender = emailSender; _mailKitOptions = options.Value; _userIdentityService = userIdentityService; _siteOption = siteOption.Value; _cacheHelp = cache; } public async Task<string> SendComfirmEmail(RegisterDto registerDto) { var message = new MimeMessage(); message.From.Add(new MailboxAddress(_mailKitOptions.UserName, _mailKitOptions.UserName)); message.To.Add(new MailboxAddress(registerDto.Nickname, registerDto.Email)); message.Subject = $"VVLOG-请点击这里激活您的账号"; string uuid = Guid.NewGuid().ToString(); await _cacheHelp.SetAsync("SendComfirmEmail-" + registerDto.Email, uuid, TimeSpan.FromMinutes(30)); message.Body = new TextPart("html") { Text = $@"{registerDto.Nickname},您好!</br> 感谢您在 vvlog 的注册,请点击这里激活您的账号:</br> {_siteOption.VVLogDomain}/accounts/confirm-email/{uuid}/ 祝您使用愉快,使用过程中您有任何问题请及时联系我们。</br>" }; await _emailSender.SendAsync(message); return ""; } public async Task SendEmailCode(RegisterDto registerDto) { var message = new MimeMessage(); message.From.Add(new MailboxAddress(_mailKitOptions.UserName, _mailKitOptions.UserName)); message.To.Add(new MailboxAddress(registerDto.Nickname, registerDto.Email)); message.Subject = $"VVLOG-你的验证码是"; string uuid = Guid.NewGuid().ToString(); await _cacheHelp.SetAsync("SendEmailCode-" + registerDto.Email, uuid, TimeSpan.FromMinutes(30)); int rand6Value = new Random().Next(100000, 999999); message.Body = new TextPart("html") { Text = $@"{registerDto.Nickname},您好!</br>你此次验证码如下,请在 30 分钟内输入验证码进行下一步操作。</br>如非你本人操作,请忽略此邮件。</br>{rand6Value}" }; await _emailSender.SendAsync(message); } public async Task<string> SendPasswordResetCode(SendEmailCodeInput sendEmailCode) { var user = await GetUserByChecking(sendEmailCode.Email); if (user.IsEmailConfirmed == false) { throw new LinCmsException("邮件未激活,无法通过此邮件找回密码!"); } user.SetNewPasswordResetCode(); int rand6Value = new Random().Next(100000, 999999); var message = new MimeMessage(); message.From.Add(new MailboxAddress(_mailKitOptions.UserName, _mailKitOptions.UserName)); message.To.Add(new MailboxAddress(user.Username, user.Email)); message.Subject = $"VVLOG-你此次重置密码的验证码是:{rand6Value}"; message.Body = new TextPart("html") { Text = $@"{user.Nickname},您好!</br>你此次重置密码的验证码如下,请在 30 分钟内输入验证码进行下一步操作。</br>如非你本人操作,请忽略此邮件。</br>{rand6Value}" }; await _userRepository.UpdateAsync(user); //await _emailSender.SendAsync(message); await _cacheHelp.SetAsync(user.Email, rand6Value, TimeSpan.FromMinutes(30)); return user.PasswordResetCode; } private async Task<LinUser> GetUserByChecking(string inputEmailAddress) { var user = await _userRepository.Select.Where(r => r.Email == inputEmailAddress).FirstAsync(); if (user == null) { throw new LinCmsException("InvalidEmailAddress"); } return user; } public async Task ResetPassword(ResetEmailPasswordDto resetPassword) { string resetCode = await _cacheHelp.GetAsync(resetPassword.Email); if (resetCode.IsNullOrEmpty()) { throw new LinCmsException("验证码已过期"); } if (resetPassword.ResetCode != resetCode) { throw new LinCmsException("验证码不正确");//InvalidEmailConfirmationCode } var user = await _userRepository.Select.Where(r => r.Email == resetPassword.Email).FirstAsync(); if (user == null || resetPassword.PasswordResetCode != user.PasswordResetCode) { throw new LinCmsException("该请求无效,请重新获取验证码"); } user.PasswordResetCode = null; await _userRepository.UpdateAsync(user); await _userIdentityService.ChangePasswordAsync(user.Id, resetPassword.Password, user.Salt); } } }
36.78
126
0.62534
[ "MIT" ]
rui-jiandan/cmsCore
src/LinCms.Application/Cms/Account/AccountService.cs
5,943
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using log4net; using Mail2Bug.Email; using Mail2Bug.TestHelpers; namespace Mail2BugUnitTests.Mocks.Email { public class IncomingEmailMessageMock : IIncomingEmailMessage { static IncomingEmailMessageMock() { _seed = (int) (DateTime.Now.Ticks%int.MaxValue); Logger.InfoFormat("IncomingEmailMessageMock: Using Seed {0}", _seed); Rand = new Random(_seed); } public static IncomingEmailMessageMock CreateWithRandomData() { return CreateWithRandomData(false); } public static IncomingEmailMessageMock CreateWithRandomData(bool withAttachments) { int numAttachments = withAttachments ? Rand.Next(0, 10) : 0; return CreateWithRandomData(numAttachments); } public static IncomingEmailMessageMock CreateWithRandomData(int numAttachments) { var mock = new IncomingEmailMessageMock { Subject = RandomDataHelper.GetSubject(_seed++), RawBody = RandomDataHelper.GetBody(_seed++), PlainTextBody = RandomDataHelper.GetBody(_seed++), ConversationId = RandomDataHelper.GetConversationId(_seed++), ConversationTopic = RandomDataHelper.GetSubject(_seed++), SenderName = RandomDataHelper.GetName(_seed++), SenderAlias = RandomDataHelper.GetAlias(_seed++) }; mock.SenderAddress = mock.SenderAlias + "@blah.com"; mock.ToAddresses = GetRandomAliasList(Rand.Next(1, 30)); mock.CcAddresses = GetRandomAliasList(Rand.Next(0, 30)); mock.ToNames = GetRandomNamesList(mock.ToAddresses.Count()); mock.CcNames = GetRandomNamesList(mock.CcAddresses.Count()); mock.SentOn = new DateTime(Rand.Next(2012, 2525), Rand.Next(1, 12), Rand.Next(1, 28)); mock.ReceivedOn = new DateTime(Rand.Next(2012, 2525), Rand.Next(1, 12), Rand.Next(1, 28)); mock.IsHtmlBody = Rand.Next(0, 1) == 0; var attachments = new List<IIncomingEmailAttachment>(numAttachments); for (var i = 0; i < numAttachments; i++) { attachments.Add(new IncomingAttachmentMock(Rand.Next(1, 100000))); } mock.Attachments = attachments; return mock; } public string Subject { get; set; } public string RawBody { get; set; } public string PlainTextBody { get; set; } public string ConversationId { get; set; } public string ConversationTopic { get; set; } public string SenderName { get; set; } public string SenderAlias { get; set; } public string SenderAddress { get; private set; } public IEnumerable<string> ToAddresses { get; set; } public IEnumerable<string> CcAddresses { get; set; } public IEnumerable<string> ToNames { get; set; } public IEnumerable<string> CcNames { get; set; } public DateTime SentOn { get; set; } public DateTime ReceivedOn { get; set; } public bool IsHtmlBody { get; set; } public string Location { get; set; } public DateTime? StartTime { get; set; } public DateTime? EndTime { get; set; } public string SaveToFile() { return SaveToFile(Path.GetTempFileName()); } public string SaveToFile(string filename) { if (ExceptionToThrow != null) { throw ExceptionToThrow; } using (var sw = new StreamWriter(new FileStream(filename, FileMode.Create, FileAccess.Write))) { sw.WriteLine("Subject: " + Subject); sw.WriteLine(); sw.WriteLine(RawBody); } return filename; } public string GetLastMessageText() { return EmailBodyProcessingUtils.GetLastMessageText(this); } public void CopyToFolder(string destinationFolder) { CopyToFolders.Add(destinationFolder); } public void Delete() {} public void MoveToFolder(string destinationFolder) { MoveToFolders.Add(destinationFolder); } public IEnumerable<IIncomingEmailAttachment> Attachments { get; set; } public readonly List<string> MoveToFolders = new List<string>(); public readonly List<string> CopyToFolders = new List<string>(); public Exception ExceptionToThrow { get; set; } #region Random Generation private static readonly Random Rand; private static int _seed; private const string EmailSuffix = "@blah.com"; private static IEnumerable<string> GetRandomAliasList(int numAliases) { if (numAliases == 0) { return new List<string>(); } var aliases = new List<string>(numAliases); for (var i = 0; i < numAliases; ++i ) { aliases.Add(RandomDataHelper.GetAlias(_seed++) + EmailSuffix); } return aliases; } private static IEnumerable<string> GetRandomNamesList(int numNames) { if (numNames == 0) { return new List<string>(); } var names = new List<string>(numNames); for (var i = 0; i < numNames; ++i) { names.Add(RandomDataHelper.GetName(_seed++)); } return names; } #endregion private static readonly ILog Logger = LogManager.GetLogger(typeof (IncomingEmailMessageMock)); } }
33.873563
106
0.580251
[ "MIT" ]
Arodriguez81/mail2bug
Mail2BugUnitTests/Mocks/Email/IncomingEmailMessageMock.cs
5,896
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Vod.V20180717.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class TimeRange : AbstractModel { /// <summary> /// <li>大于等于此时间(起始时间)。</li> /// <li>格式按照 ISO 8601标准表示,详见 [ISO 日期格式说明](https://cloud.tencent.com/document/product/266/11732#I)。</li> /// </summary> [JsonProperty("After")] public string After{ get; set; } /// <summary> /// <li>小于此时间(结束时间)。</li> /// <li>格式按照 ISO 8601标准表示,详见 [ISO 日期格式说明](https://cloud.tencent.com/document/product/266/11732#I)。</li> /// </summary> [JsonProperty("Before")] public string Before{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "After", this.After); this.SetParamSimple(map, prefix + "Before", this.Before); } } }
32.660377
111
0.630849
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Vod/V20180717/Models/TimeRange.cs
1,855
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using KeyVault.Acmebot.Options; using Newtonsoft.Json; namespace KeyVault.Acmebot.Providers { public class LiquidWebProvider : IDnsProvider { #region Private Members private readonly LiquidWebDnsClient _liquidWebDnsClient; #endregion #region Constructor public LiquidWebProvider(LiquidWebOptions options) { _liquidWebDnsClient = new LiquidWebDnsClient(options.Username, options.Password); } #endregion #region Implement Interface public int PropagationSeconds => 60; public async Task CreateTxtRecordAsync(DnsZone zone, string relativeRecordName, IEnumerable<string> values) => await _liquidWebDnsClient.CreateTxtRecordAsync(zone_name: zone.Name, zone_id: zone.Id, relativeRecordName: relativeRecordName, values: values); public async Task DeleteTxtRecordAsync(DnsZone zone, string relativeRecordName) => await _liquidWebDnsClient.DeleteTxtRecordAsync(zone_name: zone.Name, zone_id: zone.Id, relativeRecordName); public async Task<IReadOnlyList<DnsZone>> ListZonesAsync() { var zones = await _liquidWebDnsClient.ListZonesAsync(); return zones.Select(z => new DnsZone { Id = z.Id, Name = z.Name, NameServers = new List<string>() }).ToArray(); } #endregion #region Api Client private class LiquidWebDnsClient { #region Private Members private readonly string _authHeaderValue; private readonly HttpClient _httpClient; #endregion #region Constructor public LiquidWebDnsClient(string username, string password) { _authHeaderValue = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{username}:{password}")); _httpClient = new HttpClient { BaseAddress = new Uri("https://api.liquidweb.com") }; _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html")); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _authHeaderValue); } #endregion #region Private Methods private async Task<IReadOnlyList<Model.Record>> GetAllRecordsAsync(string zone_id) { var records = new List<Model.Record>(); var result = new Model.Result<Model.Record> { PageNumber = 0 }; do { result = await GetRecordsAsync(zone_id, result.PageNumber + 1); records.AddRange(result.Items); } while (result.PageNumber < result.PageTotal); return records; } private async Task<Model.Result<Model.Record>> GetRecordsAsync(string zone_id, int page_num) { var url = $"/v1/Network/DNS/Record/list?zone_id={zone_id}&page_size=50&page_num={page_num}"; var response = await _httpClient.GetAsync(url); response.EnsureSuccessStatusCode(); var serializedResponse = await response.Content.ReadAsStringAsync(); var deserializedResponse = JsonConvert.DeserializeObject<Model.Result<Model.Record>>(serializedResponse); return deserializedResponse; } private async Task<Model.Result<Model.Zone>> GetZonesAsync(int page_num) { var url = $"/v1/Network/DNS/Zone/list?page_size=50&page_num={page_num}"; var response = await _httpClient.GetAsync(url); response.EnsureSuccessStatusCode(); var serializedResponse = await response.Content.ReadAsStringAsync(); var deserializedResponse = JsonConvert.DeserializeObject<Model.Result<Model.Zone>>(serializedResponse); return deserializedResponse; } private async Task CreateRecordAsync(string zone_name, string zone_id, string relativeRecordName, string content, string recordType = "TXT") { var recordName = $"{relativeRecordName}.{zone_name}"; var url = $"https://api.liquidweb.com/v1/Network/DNS/Record/create" + $"?zone_id={zone_id}" + $"&name={recordName}" + $"&rdata=\"{content}\"" + $"&type={recordType}"; var response = await _httpClient.GetAsync(url); response.EnsureSuccessStatusCode(); } private async Task DeleteRecord(string record_id) { var url = $"https://api.liquidweb.com/v1/Network/DNS/Record/delete?id={record_id}"; await _httpClient.GetAsync(url); } #endregion #region Public Methods public async Task<IReadOnlyList<Model.Zone>> ListZonesAsync() { var zones = new List<Model.Zone>(); var result = new Model.Result<Model.Zone> { PageNumber = 0 }; do { result = await GetZonesAsync(result.PageNumber + 1); zones.AddRange(result.Items); } while (result.PageNumber < result.PageTotal); return zones; } public async Task CreateTxtRecordAsync(string zone_name, string zone_id, string relativeRecordName, IEnumerable<string> values) { foreach (var value in values) { await CreateRecordAsync(zone_name, zone_id, relativeRecordName, value, "TXT"); } } public async Task DeleteTxtRecordAsync(string zone_name, string zone_id, string relativeRecordName) { var records = await GetAllRecordsAsync(zone_id); var matches = records.Where(r => r.IsAcme && r.GetRelativeRecordName(zone_name) == relativeRecordName); foreach (var match in matches) { await DeleteRecord(match.Id); } } #endregion #region Private Api Models public class Model { public class Result<T> { [JsonProperty("item_count")] public int Count { get; set; } [JsonProperty("item_total")] public int Total { get; set; } [JsonProperty("items")] public List<T> Items { get; set; } [JsonProperty("page_num")] public int PageNumber { get; set; } [JsonProperty("page_size")] public int PageSize { get; set; } [JsonProperty("page_total")] public int PageTotal { get; set; } } public class Zone { [JsonProperty("active")] public bool Active { get; set; } [JsonProperty("id")] public string Id { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("delegation_status")] public string DelegationStatus { get; set; } public bool GoodNameServers => this.DelegationStatus.Equals("CORRECT"); } public class Record { [JsonProperty("created")] public string Created { get; set; } [JsonProperty("id")] public string Id { get; set; } [JsonProperty("last_updated")] public string LastUpdated { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("prio")] public string Priority { get; set; } [JsonProperty("rdata")] public string RData { get; set; } [JsonProperty("ttl")] public int TTL { get; set; } [JsonProperty("type")] public string Type { get; set; } [JsonProperty("zone_id")] public int ZoneId { get; set; } public bool IsTxt => Type == "TXT"; public bool IsAcme => IsTxt && Name.StartsWith("_acme-challenge."); public string GetRelativeRecordName(string zoneName) => Name.Length == zoneName.Length ? Name : Name.Substring(0, Name.Length - zoneName.Length - 1); } } #endregion } #endregion } }
36.672
155
0.543739
[ "Apache-2.0" ]
Virtual-Desktop-Service/keyvault-acmebot
KeyVault.Acmebot/Providers/LiquidWebProvider.cs
9,170
C#
// Copyright (c) Arctium. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Arctium.WoW.Launcher.Patches; static class Windows { #if x64 public static byte[] Integrity = { 0xC2, 0x00, 0x00 }; public static byte[] CertBundle = { 0x90, 0x90 }; public static byte[] CertCommonName = { 0xB0, 0x01 }; public static byte[] ShortJump = { 0xEB }; public static byte[] NoJump = { 0x00, 0x00, 0x00, 0x00 }; #elif ARM64 public static byte[] Integrity = { }; public static byte[] Branch = { 0xB5 }; public static byte[] CertCommonName = { 0x20 }; #endif // Registry entry used for -launcherlogin. public static byte[] LauncherLogin = Encoding.UTF8.GetBytes(@"Software\Custom Game Server Dev\Battle.net\Launch Options\"); }
36.434783
128
0.669451
[ "MIT" ]
Arctium/WoW-Launcher
src/Patches/Windows.cs
838
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.WafV2.Inputs { public sealed class WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementAndStatementStatementByteMatchStatementFieldToMatchUriPathGetArgs : Pulumi.ResourceArgs { public WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementAndStatementStatementByteMatchStatementFieldToMatchUriPathGetArgs() { } } }
36.55
186
0.80301
[ "ECL-2.0", "Apache-2.0" ]
Otanikotani/pulumi-aws
sdk/dotnet/WafV2/Inputs/WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementAndStatementStatementByteMatchStatementFieldToMatchUriPathGetArgs.cs
731
C#
/*************************************************************************** * NecroRegion.cs * ----------------------------- * begin : July 10, 2011 * copyright : (C) Scriptiz * email : maeliguul@hotmail.com * version : 2011-07-20 * ***************************************************************************/ /*************************************************************************** * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * ***************************************************************************/ using System; using System.Xml; using Server; using Server.Mobiles; using Server.Gumps; using Server.Spells; using Server.Items; using Server.Spells.Seventh; using Server.Spells.Fourth; using Server.Spells.Third; using Server.Spells.Sixth; using Server.Spells.Chivalry; using Server.Spells.Ninjitsu; using Server.ServerSeasons; using Server.Misc; using Server.Multis; namespace Server.Regions { public class NecroRegion : BaseRegion, ISeasons { public override Season Season { get { return ServerSeasons.Season.Desolation; } set { base.Season = ServerSeasons.Season.Desolation; } } private Point3D m_EntranceLocation; private Map m_EntranceMap; public Point3D EntranceLocation { get { return m_EntranceLocation; } set { m_EntranceLocation = value; } } public Map EntranceMap { get { return m_EntranceMap; } set { m_EntranceMap = value; } } public NecroRegion(XmlElement xml, Map map, Region parent) : base(xml, map, parent) { XmlElement entrEl = xml["entrance"]; Map entrMap = map; ReadMap(entrEl, "map", ref entrMap, false); if (ReadPoint3D(entrEl, entrMap, ref m_EntranceLocation, false)) m_EntranceMap = entrMap; } public override bool AllowHousing(Mobile from, Point3D p) { return false; } public override void OnEnter(Mobile m) { if (m is PlayerMobile && ((PlayerMobile)m).Young) ((PlayerMobile)m).Young = false; int deleted = ScrollDeleter.DeleteNecroScrolls(m); if (deleted > 0) m.SendMessage(ScrollDeleter.Message); base.OnEnter(m); } public override void OnExit(Mobile m) { int deleted = ScrollDeleter.DeleteNecroScrolls(m); if (deleted > 0) m.SendMessage(ScrollDeleter.Message); base.OnExit(m); } public override void AlterLightLevel(Mobile m, ref int global, ref int personal) { global = LightCycle.DungeonLevel; if(m == null || m.AccessLevel <= AccessLevel.Counselor) personal = 0; } public override bool CanUseStuckMenu(Mobile m) { return false; } public override bool CheckAccessibility(Item item, Mobile from) { // Scriptiz : pour empêcher de monter sur un bateau (teleport et recall déjà coupés) if (item is Plank && from.AccessLevel == AccessLevel.Player) { from.SendMessage("Il serait plus sage de ne pas faire cela."); return false; } return base.CheckAccessibility(item, from); } public override bool OnBeginSpellCast(Mobile m, ISpell s) { if ((s is GateTravelSpell || s is RecallSpell || s is MarkSpell || s is SacredJourneySpell || s is TeleportSpell || s is Shadowjump) && m.AccessLevel == AccessLevel.Player) { m.SendMessage("You cannot cast that spell here."); return false; } // Pour limiter blade spirit à certains endroits if (s is BladeSpirits) { if (this.Name == "Ilot vaseux") { m.SendMessage("Les lames s'enfonceraient dans la vase, ce serait bête de jeter ce sort ici."); return false; } } return base.OnBeginSpellCast(m, s); } public override bool OnSkillUse(Mobile from, int Skill) { if (from.AccessLevel == AccessLevel.Player && Skill == (int)SkillName.Chivalry) { from.SendMessage("Une ombre passe au dessus de vous et absorbe la force magique que vous essayez d'invoquer"); return false; ; } return true; } } }
32.946667
184
0.525496
[ "BSD-2-Clause" ]
greeduomacro/vivre-uo
Scripts/Vivre/NecroTemple/NecroRegion.cs
4,950
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=391641 namespace DynamicVsStaticCode.WinPhone { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Xamarin.Forms.Platform.WinRT.WindowsPhonePage { public MainPage() { this.InitializeComponent(); this.NavigationCacheMode = NavigationCacheMode.Required; LoadApplication(new DynamicVsStaticCode.App()); } /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. /// This parameter is typically used to configure the page.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { // TODO: Prepare page for display here. // TODO: If your application contains multiple pages, ensure that you are // handling the hardware Back button by registering for the // Windows.Phone.UI.Input.HardwareButtons.BackPressed event. // If you are using the NavigationHelper provided by some templates, // this event is handled for you. } } }
34.72549
94
0.68323
[ "Apache-2.0" ]
aliozgur/xamarin-forms-book-samples
Chapter11/DynamicVsStaticCode/DynamicVsStaticCode/DynamicVsStaticCode.WinPhone/MainPage.xaml.cs
1,771
C#
// WARNING // // This file has been generated automatically by Visual Studio from the outlets and // actions declared in your storyboard file. // Manual changes to this file will not be maintained. // using Foundation; using System; using System.CodeDom.Compiler; namespace PodcastRadio.iOS.Views.Main.Cells { [Register ("PodcastCell")] partial class PodcastCell { [Outlet] UIKit.UILabel _categoryLabel { get; set; } [Outlet] UIKit.UIImageView _contentTypeImage { get; set; } [Outlet] UIKit.UILabel _dayDateLabel { get; set; } [Outlet] UIKit.UIImageView _flagImage { get; set; } [Outlet] UIKit.UIImageView _logoImage { get; set; } [Outlet] UIKit.UILabel _monthDateLabel { get; set; } [Outlet] UIKit.UILabel _nameLabel { get; set; } [Outlet] UIKit.UIButton _openPCButton { get; set; } [Outlet] UIKit.UILabel _titleLabel { get; set; } [Outlet] UIKit.UILabel _tracksLabel { get; set; } void ReleaseDesignerOutlets () { if (_categoryLabel != null) { _categoryLabel.Dispose (); _categoryLabel = null; } if (_contentTypeImage != null) { _contentTypeImage.Dispose (); _contentTypeImage = null; } if (_dayDateLabel != null) { _dayDateLabel.Dispose (); _dayDateLabel = null; } if (_flagImage != null) { _flagImage.Dispose (); _flagImage = null; } if (_logoImage != null) { _logoImage.Dispose (); _logoImage = null; } if (_monthDateLabel != null) { _monthDateLabel.Dispose (); _monthDateLabel = null; } if (_nameLabel != null) { _nameLabel.Dispose (); _nameLabel = null; } if (_titleLabel != null) { _titleLabel.Dispose (); _titleLabel = null; } if (_tracksLabel != null) { _tracksLabel.Dispose (); _tracksLabel = null; } } } }
23.796117
84
0.480212
[ "MIT" ]
joaowd/PodcastRadio
PodcastRadio.iOS/Views/Main/Cells/PodcastCell.designer.cs
2,451
C#
using UnityEngine; using System.Collections; public class Trader : MonoBehaviour, IBuilding { public TradeList possibleTrades; public int currentTradeAmount = 0; public TradeItem currentTradeItem { get {return currTradeItem;} set {currTradeItem = value;} } private TradeItem currTradeItem; public int currentTradeValue { get { return currentTradeItem.TransactionValue(currentTradeAmount); } } void Start () { Data.AddBuilding(this); currTradeItem = possibleTrades.tradeList[0]; } public void Work() { if(currentTradeAmount > 0) { Data.PayMoney(currentTradeValue); if(currentTradeItem.isFinishedGoods) { Data.AddGoods(currentTradeItem.item, currentTradeAmount); } else { Data.AddResource(currentTradeItem.item, currentTradeAmount); } } else { if(currentTradeItem.isFinishedGoods) { if(Data.ConsumeGoods(currentTradeItem.item, -currentTradeAmount)) Data.GetMoney(currentTradeValue); } else { if(Data.ConsumeResource(currentTradeItem.item, -currentTradeAmount)) Data.GetMoney(currentTradeValue); } } } void OnDestroy() { Data.RemoveBuilding(this); } public void ShowTradeWindow() { UserInterface.ShowTradeWindow(this); } }
23.307692
72
0.740099
[ "Apache-2.0" ]
Aggrathon/LudumDare33
Assets/Scripts/Trade/Trader.cs
1,214
C#
using System; using System.Globalization; using System.Threading; using System.Windows; using HandyControl.Controls; using HandyControl.Data; using HandyControl.Tools; using HandyControlDemo.Data; using HandyControlDemo.Tools; namespace HandyControlDemo { /// <summary> /// App.xaml 的交互逻辑 /// </summary> public partial class App { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); GlobalData.Init(); Thread.CurrentThread.CurrentUICulture = new CultureInfo(GlobalData.Config.Lang); if (GlobalData.Config.Skin != SkinType.Default) { UpdateSkin(GlobalData.Config.Skin); } #if !Core BlurWindow.SystemVersionInfo = CommonHelper.GetSystemVersionInfo(); #endif } protected override void OnExit(ExitEventArgs e) { base.OnExit(e); GlobalData.Save(); } internal void UpdateSkin(SkinType skin) { var skins0 = Resources.MergedDictionaries[0]; skins0.MergedDictionaries.Clear(); skins0.MergedDictionaries.Add(ResourceHelper.GetSkin(skin)); skins0.MergedDictionaries.Add(ResourceHelper.GetSkin(typeof(App).Assembly, "Resources/Themes", skin)); var skins1 = Resources.MergedDictionaries[1]; skins1.MergedDictionaries.Clear(); skins1.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri("pack://application:,,,/HandyControl;component/Themes/Theme.xaml") }); skins1.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri("pack://application:,,,/HandyControlDemo;component/Resources/Themes/Theme.xaml") }); Current.MainWindow?.OnApplyTemplate(); } } }
30.596774
114
0.622035
[ "MIT" ]
ihehe616/HandyControl
HandyControlDemo/App.xaml.cs
1,909
C#
using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; using System.Linq; using Microsoft.Azure.Mobile.Server; using Microsoft.Azure.Mobile.Server.Tables; using MobileAppsFileSampleService.DataObjects; namespace MobileAppsFileSampleService.Models { public class MobileAppsFileSampleContext : DbContext { // You can add custom code to this file. Changes will not be overwritten. // // If you want Entity Framework to alter your database // automatically whenever you change your model schema, please use data migrations. // For more information refer to the documentation: // http://msdn.microsoft.com/en-us/data/jj591621.aspx private const string connectionStringName = "Name=MS_TableConnectionString"; public MobileAppsFileSampleContext() : base(connectionStringName) { } public DbSet<TodoItem> TodoItems { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Add( new AttributeToColumnAnnotationConvention<TableColumnAttribute, string>( "ServiceTableColumn", (property, attributes) => attributes.Single().ColumnType.ToString())); } } }
36.166667
112
0.702765
[ "MIT" ]
Azure-Samples/app-service-mobile-dotnet-todo-list-files
src/service/MobileAppsFileSampleService/Models/MobileAppsFileSampleContext.cs
1,304
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.DBforPostgreSQL.V20171201Preview.Outputs { [OutputType] public sealed class PrivateEndpointPropertyResponse { /// <summary> /// Resource id of the private endpoint. /// </summary> public readonly string? Id; [OutputConstructor] private PrivateEndpointPropertyResponse(string? id) { Id = id; } } }
25.678571
81
0.667594
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/DBforPostgreSQL/V20171201Preview/Outputs/PrivateEndpointPropertyResponse.cs
719
C#