text
stringlengths
3
1.02M
//----------------------------------------------------------------------- // <copyright file="XmlObjectExtension.cs" company="NJsonSchema"> // Copyright (c) Rico Suter. All rights reserved. // </copyright> // <license>https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md</license> // <author>Rico Suter, [email protected]</author> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace NJsonSchema.Infrastructure { /// <summary>Extension methods to help out generating XMLObject structure to schema.</summary> public static class XmlObjectExtension { /// <summary>Generate XML object for a JSON Schema definition.</summary> /// <param name="schema">The JSON Schema.</param> /// <param name="type">The type of the JSON Schema.</param> public static void GenerateXmlObjectForType(this JsonSchema4 schema, Type type) { var attributes = type.GetTypeInfo().GetCustomAttributes().ToList(); if (attributes.Any()) { dynamic xmlTypeAttribute = attributes.TryGetIfAssignableTo("System.Xml.Serialization.XmlTypeAttribute"); if (xmlTypeAttribute != null) GenerateXmlObject(xmlTypeAttribute.TypeName, xmlTypeAttribute.Namespace, false, false, schema); } } /// <summary>Generates an XML object for a JSON Schema definition.</summary> /// <param name="schema">The JSON Schema</param> /// <param name="type">The array type</param> public static void GenerateXmlObjectForArrayType(this JsonSchema4 schema, Type type) { if (schema.IsArray && schema.ParentSchema == null) { GenerateXmlObject($@"ArrayOf{schema.Item.Xml.Name}", null, true, false, schema); } } /// <summary>Generates XMLObject structure for an array with primitive types</summary> /// <param name="schema">The JSON Schema of the item.</param> /// <param name="type">The item type.</param> public static void GenerateXmlObjectForItemType(this JsonSchema4 schema, Type type) { // Is done all the time for XML to be able to get type name as the element name if not there was an attribute defined since earlier var attributes = type.GetTypeInfo().GetCustomAttributes().ToList(); dynamic xmlTypeAttribute = attributes.TryGetIfAssignableTo("System.Xml.Serialization.XmlTypeAttribute"); var itemName = GetXmlItemName(type); if (xmlTypeAttribute != null) itemName = xmlTypeAttribute.TypeName; GenerateXmlObject(itemName, null, false, false, schema); } /// <summary>Generates XMLObject structure for a property.</summary> /// <param name="propertySchema">The JSON Schema for the property</param> /// <param name="type">The type.</param> /// <param name="propertyName">The property name.</param> /// <param name="attributes">The attributes that exists for the property.</param> public static void GenerateXmlObjectForProperty(this JsonProperty propertySchema, Type type, string propertyName, IEnumerable<Attribute> attributes) { string xmlName = null; string xmlNamespace = null; bool xmlWrapped = false; if (propertySchema.IsArray) { dynamic xmlArrayAttribute = attributes.TryGetIfAssignableTo("System.Xml.Serialization.XmlArrayAttribute"); if (xmlArrayAttribute != null) { xmlName = xmlArrayAttribute.ElementName; xmlNamespace = xmlArrayAttribute.Namespace; } dynamic xmlArrayItemsAttribute = attributes.TryGetIfAssignableTo("System.Xml.Serialization.XmlArrayItemAttribute"); if (xmlArrayItemsAttribute != null) { var xmlItemName = xmlArrayItemsAttribute.ElementName; var xmlItemNamespace = xmlArrayItemsAttribute.Namespace; GenerateXmlObject(xmlItemName, xmlItemNamespace, true, false, propertySchema.Item); } xmlWrapped = true; } dynamic xmlElementAttribute = attributes.TryGetIfAssignableTo("System.Xml.Serialization.XmlElementAttribute"); if (xmlElementAttribute != null) { xmlName = xmlElementAttribute.ElementName; xmlNamespace = xmlElementAttribute.Namespace; } dynamic xmlAttribute = attributes.TryGetIfAssignableTo("System.Xml.Serialization.XmlAttributeAttribute"); if (xmlAttribute != null) { if (!string.IsNullOrEmpty(xmlAttribute.AttributeName)) xmlName = xmlAttribute.AttributeName; if (!string.IsNullOrEmpty(xmlAttribute.Namespace)) xmlNamespace = xmlAttribute.Namespace; } // Due to that the JSON Reference is used, the xml name from the referenced type will be copied to the property. // We need to ensure that the property name is preserved if (string.IsNullOrEmpty(xmlName) && propertySchema.Type == JsonObjectType.None) { var referencedTypeAttributes = type.GetTypeInfo().GetCustomAttributes(); dynamic xmlReferenceTypeAttribute = referencedTypeAttributes.TryGetIfAssignableTo("System.Xml.Serialization.XmlTypeAttribute"); if (xmlReferenceTypeAttribute != null) { xmlName = propertyName; } } if (!string.IsNullOrEmpty(xmlName) || xmlWrapped) GenerateXmlObject(xmlName, xmlNamespace, xmlWrapped, xmlAttribute != null ? true : false, propertySchema); } private static void GenerateXmlObject(string name, string @namespace, bool wrapped, bool isAttribute, JsonSchema4 schema) { schema.Xml = new JsonXmlObject { Name = name, Wrapped = wrapped, Namespace = @namespace, ParentSchema = schema, Attribute = isAttribute }; } /// <summary>type.Name is used int will return Int32, string will return String etc. /// These are not valid with how the XMLSerializer performs.</summary> private static string GetXmlItemName(Type type) { if (type == typeof(int)) return "int"; else if (type == typeof(string)) return "string"; else if (type == typeof(double)) return "double"; else if (type == typeof(decimal)) return "decimal"; else return type.Name; } } }
using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; using System.ComponentModel; using System.IO; using System.Text.RegularExpressions; namespace GRebind { public class HttpData { public WebHeaderCollection Headers; public string Html; } public class WebReq { public Uri URI; private Socket socket; private Random rnd = new Random(); public ReqState State = ReqState.Ready; public WebHeaderCollection Headers = new WebHeaderCollection(); private WebHeaderCollection outHeaders = new WebHeaderCollection(); private string Filename = ""; private string Postdata = ""; private string ConMode = "GET"; private string tmpPath = ""; private bool ReturnStr = false; public bool isReady = true; public string ResponseCode = ""; public string Response = ""; public string SentPacket = ""; public int cSize = 1024; private int iTimeout = -1; private long cLength; public double Progress; public double dSpeed; private double[] daSpeed = new double[2]; private long lSpdLastTick; private long lSpdPacketCnt; public enum ReqState { Ready, Connecting, Requesting, Downloading, Completed, Failed }; public void Request(Uri Url, WebHeaderCollection cHeaders, string sPostdata, string sFilename, bool bReturnStr) { isReady = false; State = ReqState.Connecting; URI = Url; Filename = sFilename; ReturnStr = bReturnStr; Headers = new WebHeaderCollection(); outHeaders["Host"] = URI.Host; outHeaders["Keep-Alive"] = "close"; for (int a = 0; a < cHeaders.Count; a++) { outHeaders.Add(cHeaders.GetKey(a) + ": " + cHeaders.Get(a)); } if (sPostdata != "") { ConMode = "POST"; Postdata = sPostdata; outHeaders.Add("Content-Length: " + Postdata.Length); } BackgroundWorker bw = new BackgroundWorker(); bw.DoWork += new DoWorkEventHandler(bw_DoWork); bw.RunWorkerAsync(); } private void bw_DoWork(object sender, DoWorkEventArgs e) { try { // ~~~ Create socket, set timeout ~~~ \\ socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint RHost = new IPEndPoint(Dns.GetHostEntry(URI.Host).AddressList[0], URI.Port); if (iTimeout != -1) { socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, iTimeout); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, iTimeout); BackgroundWorker bwTimeout = new BackgroundWorker(); bwTimeout.DoWork += new DoWorkEventHandler(bwTimeout_DoWork); bwTimeout.RunWorkerAsync(); } // ~~~ Create request, send request ~~~ \\ State = ReqState.Connecting; try { socket.Connect(RHost); } catch { throw new Exception("#02-0002"); } State = ReqState.Requesting; if (ConMode == "POST") outHeaders.Add("Content-Type: application/x-www-form-urlencoded"); string ReqStr = ConMode + " " + URI.PathAndQuery + " HTTP/1.0\r\n" + outHeaders; if (ConMode == "POST") ReqStr += Postdata; SentPacket = ReqStr + "\r\n\r\n>"; byte[] bPck = System.Text.Encoding.ASCII.GetBytes(ReqStr); foreach (byte btPck in bPck) SentPacket += btPck + " "; socket.Send(System.Text.Encoding.ASCII.GetBytes(ReqStr)); if (!ParseHeader()) { if (ResponseCode != "") throw new Exception("#02-0004_" + ResponseCode); throw new Exception("#02-0003"); } // ~~~ Find filename ~~~ \\ string tFName = ""; do tFName = tmpPath + "wanr_" + RandomChars(12) + ".tmp"; while (File.Exists(tFName)); // ~~~ Download file ~~~ \\ lSpdLastTick = Tick(); FileStream streamOut = File.Open(tFName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); BinaryWriter writer = new BinaryWriter(streamOut); byte[] RecvBuffer = new byte[cSize]; int nBytes, nTotalBytes = 0; while ((nBytes = socket.Receive(RecvBuffer, 0, cSize, SocketFlags.None)) > 0) { nTotalBytes += nBytes; State = ReqState.Downloading; lSpdPacketCnt++; cSpeed(); Progress = Math.Round(((double)100 - ((double)cLength - (double)nTotalBytes) * (double)100 / (double)cLength), 1); writer.Write(RecvBuffer, 0, nBytes); if (ReturnStr) Response += Encoding.ASCII.GetString(RecvBuffer, 0, nBytes); } streamOut.Flush(); streamOut.Close(); streamOut.Dispose(); socket.Close(); // ~~~ Verify download, return text ~~~ \\ long tStart = Tick(); if (!File.Exists(tFName)) wrErrlog("Poll1 false"); while (!File.Exists(tFName)) { System.Threading.Thread.Sleep(10); if (Tick() > tStart + 2000) break; } if (!File.Exists(tFName)) wrErrlog("Poll2 false"); if (File.Exists(tFName)) { if (ReturnStr) { System.IO.StreamReader strmIn = new System.IO.StreamReader(tFName, Encoding.GetEncoding("iso-8859-1")); Response = strmIn.ReadToEnd(); strmIn.Close(); strmIn.Dispose(); } if (Filename != "") { File.Delete(Filename); File.Move(tFName, Filename); } else File.Delete(tFName); } else { throw new Exception("#02-0001"); } State = ReqState.Completed; Progress = 100; isReady = true; } catch (Exception ex) { wrExThrow(ex.Message, ex.StackTrace); } } public void Request(String sURL, WebHeaderCollection cHeaders, string sPostdata, string sFilename, bool bReturnStr) { if (!sURL.ToLower().StartsWith("http://")) sURL = "http://" + sURL; Request(new Uri(sURL), cHeaders, sPostdata, sFilename, bReturnStr); } public void Request(String sURL, string sPostdata, string sFilename, bool bReturnStr) { Request(sURL, new WebHeaderCollection(), sPostdata, sFilename, bReturnStr); } public void Request(String sURL, string sFilename, bool bReturnStr) { Request(sURL, new WebHeaderCollection(), "", sFilename, bReturnStr); } public void Request(String sURL) { Request(sURL, new WebHeaderCollection(), "", "", true); } private bool ParseHeader() { try { byte[] bytes = new byte[10]; string Header = ""; while (socket.Receive(bytes, 0, 1, SocketFlags.None) > 0) { Header += Encoding.ASCII.GetString(bytes, 0, 1); if (bytes[0] == '\n' && Header.EndsWith("\r\n\r\n")) break; } MatchCollection matches = new Regex("[^\r\n]+").Matches(Header.TrimEnd('\r', '\n')); for (int n = 1; n < matches.Count; n++) { string[] strItem = matches[n].Value.Split(new char[] { ':' }, 2); if (strItem.Length > 0) Headers[strItem[0].Trim()] = strItem[1].Trim(); } if (matches.Count > 0) { if (matches[0].Value.Contains(" 404 ")) ResponseCode = "404"; } if (Headers["Content-Length"] != null) cLength = int.Parse(Headers["Content-Length"]); if (ResponseCode != "") return false; return true; } catch { //wrExThrow("Header parse error"); return false; } } public void SetTimeout(int Timeout) { iTimeout = Timeout; } private void bwTimeout_DoWork(object sender, DoWorkEventArgs e) { System.Threading.Thread.Sleep(iTimeout); if (State != ReqState.Connecting) return; wrExThrow("#02-0005"); } public long Tick() { return System.DateTime.Now.Ticks / 10000; } private void cSpeed() { long ltDiff = Tick() - lSpdLastTick; if (ltDiff > 500) { lSpdLastTick = Tick(); for (int a = daSpeed.Length - 2; a > 0; a--) { daSpeed[a + 1] = daSpeed[a]; } daSpeed[0] = ((double)lSpdPacketCnt / ((double)ltDiff/1000)) * ((double)cSize / 1024); lSpdPacketCnt = 0; double dcSpeed = 0; int iLogCnt = 0; for (int a = 0; a < daSpeed.Length; a++) { if (daSpeed[a] != 0) { iLogCnt++; dcSpeed += daSpeed[a]; } } dSpeed = dcSpeed / (double)iLogCnt; } } private string RandomChars(int Count) { string ret = ""; for (int a = 0; a < Count; a++) { int ThisRnd = rnd.Next(1, 63); if (ThisRnd >= 1 && ThisRnd <= 26) ThisRnd += 64; else if (ThisRnd >= 27 && ThisRnd <= 52) ThisRnd += 97 - 27; else if (ThisRnd >= 53 && ThisRnd <= 62) ThisRnd += 48 - 53; ret += (char)ThisRnd; } return ret; } private static String Byte2Str(byte[] Value) { int len = 0; for (len = Value.Length; len > 0; len--) if (Value[len - 1] != 0) break; string ret = ""; for (int a = 0; a < len; a++) ret += (char)Value[a]; //byte[] buf = new byte[a]; for (a = 0; a < buf.Length; a++) buf[a] = Value[a]; return ret; //System.Text.Encoding.ASCII.GetString(buf); } private void wrErrlog(string msg) { //string errMessage = System.DateTime.Now.ToShortDateString() + " - " + // System.DateTime.Now.ToLongTimeString() + "\r\n" + // msg + "\r\n\r\n"; //FileStream fs = new FileStream("errors_browser.txt", FileMode.Append); //fs.Write(System.Text.Encoding.ASCII.GetBytes(errMessage), 0, errMessage.Length); //fs.Close(); fs.Dispose(); } private void wrExThrow(string msg, string trace) { string exMessage = msg; Response = "<WebReq_Error>" + msg + "</WebReq_Error>"; //if (Filename != "") //{ // FileStream fs = new FileStream(Filename, FileMode.Create); // fs.Write(System.Text.Encoding.ASCII.GetBytes(Response), 0, Response.Length); // fs.Flush(); fs.Close(); fs.Dispose(); //} if (trace.Contains(":line ")) trace = trace.Substring(trace.IndexOf(":line ") + 6); else trace = ""; if (trace != "") exMessage += "\r\nSTACK TRACING --> " + trace; wrErrlog(exMessage); socket.Close(); State = ReqState.Failed; Progress = 0; isReady = true; } private void wrExThrow(string msg) { wrExThrow(msg, ""); } } }
using System; using System.Collections.Generic; using System.Linq; namespace _01.CountCharsInAString { class Program { static void Main(string[] args) { string[] text = Console.ReadLine() .Split(" ",StringSplitOptions.RemoveEmptyEntries) .ToArray(); Dictionary<string, int> count = new Dictionary<string, int>(); for (int i = 0; i < text.Length; i++) { string word = text[i]; for (int j = 0; j < text[i].Length; j++) { if (count.ContainsKey(word[j].ToString())) { count[word[j].ToString()]++; } else { count.Add(word[j].ToString(), 1); } } } foreach (var item in count) { Console.WriteLine($"{item.Key} -> {item.Value}"); } } } }
using System; using NetOffice; namespace NetOffice.MSHTMLApi.Enums { /// <summary> /// SupportByVersion MSHTML 4 /// </summary> [SupportByVersionAttribute("MSHTML", 4)] [EntityTypeAttribute(EntityType.IsEnum)] public enum _htmlZOrder { /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <remarks>0</remarks> [SupportByVersionAttribute("MSHTML", 4)] htmlZOrderFront = 0, /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <remarks>1</remarks> [SupportByVersionAttribute("MSHTML", 4)] htmlZOrderBack = 1, /// <summary> /// SupportByVersion MSHTML 4 /// </summary> /// <remarks>2147483647</remarks> [SupportByVersionAttribute("MSHTML", 4)] htmlZOrder_Max = 2147483647 } }
/* * 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.Collections.Generic; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.rtc.Transform; using Aliyun.Acs.rtc.Transform.V20180111; namespace Aliyun.Acs.rtc.Model.V20180111 { public class DescribeMAURuleRequest : RpcAcsRequest<DescribeMAURuleResponse> { public DescribeMAURuleRequest() : base("rtc", "2018-01-11", "DescribeMAURule", "rtc", "openAPI") { if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null) { this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Endpoint.endpointMap, null); this.GetType().GetProperty("ProductEndpointType").SetValue(this, Endpoint.endpointRegionalType, null); } } private long? ownerId; private string appId; public long? OwnerId { get { return ownerId; } set { ownerId = value; DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString()); } } public string AppId { get { return appId; } set { appId = value; DictionaryUtil.Add(QueryParameters, "AppId", value); } } public override bool CheckShowJsonItemName() { return false; } public override DescribeMAURuleResponse GetResponse(UnmarshallerContext unmarshallerContext) { return DescribeMAURuleResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
using Rakor.Blazor.ECharts.Option.Enum; namespace Rakor.Blazor.ECharts.Option { public class LineStyle : AreaStyle { /// <summary> /// 线宽。 /// </summary> public double? Width { set; get; } /// <summary> /// 线的类型。 /// </summary> public LineStyleType? Type { set; get; } } }
//------------------- // Copyright 2019 // Reachable Games, LLC //------------------- using System; using System.Collections; using UnityEngine; using UnityEngine.Networking; using UnityEditor; namespace ReachableGames { namespace SmoothTrails { public class AssetsPopup : EditorWindow { static string kNextCheckTime = "ReachableGames_AssetPopup_NextCheckTime"; static string kHashOfWebPage = "ReachableGames_AssetPopup_Hash"; static string kAssetsURL = "https://reachablegames.com/unity-asset-updates/"; static private AssetsPopup _instance = null; [MenuItem("Tools/ReachableGames/Check for Updates")] static void CheckForUpdatesMenu() { EditorPrefs.SetString(kHashOfWebPage, ""); // someone asked for the window, give it to them WaitForWebRequest(CheckContent()); } static void Init() { if (_instance==null) _instance = EditorWindow.CreateInstance<AssetsPopup>(); _instance.ShowUtility(); } [InitializeOnLoadMethod] static void CheckForUpdates() { long nextCheckTime = long.Parse(EditorPrefs.GetString(kNextCheckTime, "0")); if (DateTime.UtcNow.Ticks > nextCheckTime) { // Do a daily check for updated web page, unless we're told not to check for 3 months. long nextCheck = DateTime.UtcNow.Ticks + TimeSpan.FromDays(1.0).Ticks; EditorPrefs.SetString(kNextCheckTime, nextCheck.ToString()); WaitForWebRequest(CheckContent()); } } static private string ComputeHash(string text) { #if UNITY_2018_1_OR_NEWER return Hash128.Compute(text).ToString(); #else // Unity 2017 didn't have a compute function, so we fall back to a crappier hash that is quick to write. long value = 0; for (int i=0; i<text.Length; i++) { char c = text[i]; value += (((long)c) << (i % 5)) + (((long)c) << (i % 11)); } return value.ToString(); #endif } static private IEnumerator CheckContent() { using (UnityWebRequest w = UnityWebRequest.Get(kAssetsURL)) { yield return w.SendWebRequest(); while (!w.isDone) yield return null; if (!w.isNetworkError && !w.isHttpError && w.downloadProgress==1.0f) { string hashOfWebPage = ComputeHash(w.downloadHandler.text); if (EditorPrefs.GetString(kHashOfWebPage, "")!=hashOfWebPage) { EditorPrefs.SetString(kHashOfWebPage, hashOfWebPage); Init(); // pop up the window, something's new } } } } static private void WaitForWebRequest(IEnumerator update) { EditorApplication.CallbackFunction cb = null; cb = () => { try { if (!update.MoveNext()) EditorApplication.update -= cb; } catch (Exception ex) { Debug.LogException(ex); EditorApplication.update -= cb; } }; EditorApplication.update += cb; } //------------------- private WebViewHook _webHook = null; void OnEnable() { if (_webHook==null) _webHook = CreateInstance<WebViewHook>(); _webHook.AllowRightClickMenu(false); minSize = new Vector2(840, 800); titleContent = new GUIContent("Check for Updates"); } void OnDestroy() { if (_webHook!=null) { DestroyImmediate(_webHook); } } Rect bottomBarRect; void OnGUI() { // Put web block here if (_webHook.Hook(this)) { _webHook.LoadURL(kAssetsURL); } if (Event.current.type==EventType.Repaint) _webHook.OnGUI(new Rect(0, 0, position.width, bottomBarRect.height)); GUILayout.FlexibleSpace(); if (Event.current.type==EventType.Repaint) bottomBarRect = GUILayoutUtility.GetLastRect(); var bigTextArea = new GUIStyle(GUI.skin.textArea); bigTextArea.fontSize = 15; EditorGUILayout.TextArea("Thank you for using our assets. We sincerely hope they are making dev life better for you. If so, please help us keep working on them by giving each a great 5* review and recommend them to your friends. It really does make a difference!", bigTextArea); using (new EditorGUILayout.HorizontalScope()) { if (GUILayout.Button(new GUIContent("Check for updates in 3 months", "You can always check manually at Tools->ReachableGames."), GUILayout.Width(200))) { long nextCheck = DateTime.UtcNow.Ticks + TimeSpan.FromDays(90.0).Ticks; EditorPrefs.SetString(kNextCheckTime, nextCheck.ToString()); } GUILayout.FlexibleSpace(); GUIStyle blueLabel = new GUIStyle(EditorStyles.whiteMiniLabel); blueLabel.normal.textColor = EditorGUIUtility.isProSkin ? Color.white : Color.blue; blueLabel.fontSize = 12; if (GUILayout.Button("[email protected]", blueLabel)) { Application.OpenURL("mailto:[email protected]?Subject=Support Request"); } GUILayout.FlexibleSpace(); var blueTextButton = new GUIStyle(GUI.skin.button); blueTextButton.normal.textColor = EditorGUIUtility.isProSkin ? Color.white : Color.blue; if (GUILayout.Button(new GUIContent("Check for updates regularly", "As a service, this will let you know as soon as bugs are fixed or features are added to one of our assets. Generally this is not more than once a month."), blueTextButton, GUILayout.Width(200))) { long nextCheck = DateTime.UtcNow.Ticks + TimeSpan.FromDays(1.0).Ticks; EditorPrefs.SetString(kNextCheckTime, nextCheck.ToString()); } } } } } }
/* This file is part of the iText (R) project. Copyright (c) 1998-2022 iText Group NV Authors: iText Software. This program is offered under a commercial and under the AGPL license. For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below. AGPL licensing: This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ using System; using System.Collections.Generic; using iText.Commons.Actions.Processors; using iText.Commons.Actions.Sequence; namespace iText.Commons.Actions { /// <summary>Abstract class which represents system configuration events.</summary> /// <remarks>Abstract class which represents system configuration events. Only for internal usage.</remarks> public abstract class AbstractITextConfigurationEvent : AbstractITextEvent { /// <summary> /// Adds a new /// <see cref="iText.Commons.Actions.Processors.ITextProductEventProcessor"/> /// for a product. /// </summary> /// <param name="processor">is a new processor</param> /// <returns>a replaced processor for the product</returns> protected internal virtual ITextProductEventProcessor AddProcessor(ITextProductEventProcessor processor) { return ProductEventHandler.INSTANCE.AddProcessor(processor); } /// <summary>Removes a processor registered for a product.</summary> /// <param name="productName">is a product for which processor is removed</param> /// <returns>removed processor</returns> protected internal virtual ITextProductEventProcessor RemoveProcessor(String productName) { return ProductEventHandler.INSTANCE.RemoveProcessor(productName); } /// <summary>Gets a processor registered for a product.</summary> /// <remarks> /// Gets a processor registered for a product. /// <para /> /// If processor isn't registered and product supports AGPL mode /// <see cref="iText.Commons.Actions.Processors.DefaultITextProductEventProcessor"/> /// will be obtained otherwise null will be returned. /// </remarks> /// <param name="productName">is a product for which processor is obtained</param> /// <returns>processor for the product</returns> protected internal virtual ITextProductEventProcessor GetActiveProcessor(String productName) { return ProductEventHandler.INSTANCE.GetActiveProcessor(productName); } /// <summary>Gets an unmodifiable map of registered processors.</summary> /// <returns>all processors</returns> protected internal virtual IDictionary<String, ITextProductEventProcessor> GetProcessors() { return ProductEventHandler.INSTANCE.GetProcessors(); } /// <summary>Gets events registered for provided identifier.</summary> /// <param name="id">is the identifier</param> /// <returns>the list of event for identifier</returns> protected internal virtual IList<AbstractProductProcessITextEvent> GetEvents(SequenceId id) { return ProductEventHandler.INSTANCE.GetEvents(id); } /// <summary>Registers a new event for provided identifier.</summary> /// <param name="id">is the identifier</param> /// <param name="event">is the event to register</param> protected internal virtual void AddEvent(SequenceId id, AbstractProductProcessITextEvent @event) { ProductEventHandler.INSTANCE.AddEvent(id, @event); } /// <summary>Registers internal namespace.</summary> /// <param name="namespace">is the namespace to register</param> protected internal virtual void RegisterInternalNamespace(String @namespace) { AbstractITextEvent.RegisterNamespace(@namespace); } /// <summary>Method defines the logic of action processing.</summary> protected internal abstract void DoAction(); } }
using UnityEngine; using UnityEngine.UI; public class MoleculeText : MonoBehaviour { public int option; public Image line; private void OnEnable() { ContentAdaptationManager.NextMolecule += SetText; } private void OnDisable() { ContentAdaptationManager.NextMolecule -= SetText; } public void Start() { SetText(); } private void SetText() //sets the text for the molecule name and enables the line if constructed or named. { //stands for the naming quiz if (option == 1 && GameManager.currentLevel == GameManager.Levels.moleculeNaming) { if (GameManager.instance.IsMoleculeNamed(GameManager.chosenMolecule.Name)) { line.enabled = true; } else{ line.enabled = false; } gameObject.GetComponent<Text>().text = GameManager.chosenMolecule.Name; } else if(option == 1 && GameManager.currentLevel == GameManager.Levels.moleculeConstruction) { if (GameManager.instance.IsMoleculeConstructed(GameManager.chosenMolecule.Name)) { line.enabled = true; } else { line.enabled = false; } gameObject.GetComponent<Text>().text = GameManager.chosenMolecule.Name; } else // for the formula in construction scene. { gameObject.GetComponent<Text>().text = GameManager.chosenMolecule.Formula; } } }
@using Syncfusion.EJ2.PivotView @section Meta{ <meta name="description" content="This demo for Essential JS2 ASP.NET MVC Pivot Table control demonstrate the cell selection feature" /> } @section ControlsSection{ <div class="col-lg-8 control-section" style="overflow:auto"> <div class="content-wrapper"> @Html.EJS().PivotView("pivotview").Width("100%").Height("300").DataSource(dataSource => dataSource.Data((IEnumerable<object> )ViewBag.Data).ExpandAll(true).EnableSorting(true) .Rows(rows => { rows.Name("Country").Add(); rows.Name("Products").Add(); }) .Columns(columns => { columns.Name("Year").Add(); columns.Name("Order_Source").Caption("Order Source").Add(); }) .Values(values => { values.Name("Sold").Caption("Units Sold").Add(); values.Name("Amount").Caption("Sold Amount").Add(); }) .FormatSettings(formatsettings => { formatsettings.Name("Amount").Format("C0").MaximumSignificantDigits(10).MinimumSignificantDigits(1).UseGrouping(true).Add(); }) .Filters(filters => { filters.Name("Product_Categories").Caption("Product Categories").Add(); })).GridSettings(new PivotViewGridSettings { ColumnWidth = 120, AllowSelection = true}).Load("onLoad").CellSelected("onCellSelected").Render() </div> </div> <div class="col-lg-4 property-section pivotgrid-property-section"> <table id="property" title="Properties" style="width: 100%"> <tbody> <tr style="height: 50px"> <td> <div> Selection Modes: </div> </td> <td> <div> <select id="mode" name="ddl-view-mode"> <option value='Cell' selected>Cell</option> <option value='Row'>Row Only</option> <option value='Column'>Column Only</option> <option value='Both'>Both</option> </select> </div> </td> </tr> <tr style="height: 50px"> <td> <div> Selection Types: </div> </td> <td> <div> <select id="type" name="ddl-view-mode"> <option value='Single'>Single</option> <option value='Multiple' selected>Multiple</option> </select> </div> </td> </tr> <tr> <td colspan="2"> <div> <b> <hr>Event Trace: </b> </div> </td> </tr> <tr> <td colspan="2"> <div class="eventarea" style="height: 230px;overflow: auto"> <span class="EventLog" id="selection-EventLog" style="word-break: normal;"></span> </div> </td> </tr> </tbody> </table> </div> <style> .pivotgrid-property-section hr { margin: 1px 10px 0px 0px; border-top: 1px solid #eee; } </style> <script> function onLoad(args) { var pivotGridObj = document.getElementById('pivotview').ej2_instances[0]; pivotGridObj.gridSettings.selectionSettings = { mode: 'Cell', type: 'Multiple', cellSelectionMode: 'Box' }; } function onCellSelected(args) { document.getElementById('selection-EventLog').innerHTML = ''; if (args.selectedCellsInfo.length > 0) { for (var cnt = 0; cnt < args.selectedCellsInfo.length; cnt++) { var cell = args.selectedCellsInfo[cnt]; var summMeasure = this.engineModule.fieldList[cell.measure] ? this.engineModule.fieldList[cell.measure].aggregateType + ' of ' + this.engineModule.fieldList[cell.measure].caption : ''; appendElement( (cell.columnHeaders == '' ? '' : 'Column Headers: ' + '<b>' + cell.columnHeaders.split('.').join(' - ') + '</b></br>') + (cell.rowHeaders == '' ? '' : 'Row Headers: ' + '<b>' + cell.rowHeaders.split('.').join(' - ') + '</b></br>') + (summMeasure == '' ? '' : 'Measure: ' + '<b>' + summMeasure + '</b></br>') + 'Value: ' + '<b>' + cell.currentCell.formattedText + '</b><hr></br>'); } } } function appendElement(html) { var span = document.createElement('span'); span.innerHTML = html; var log = document.getElementById('selection-EventLog'); log.appendChild(span); } var modeddl = new ej.dropdowns.DropDownList({ floatLabelType: 'Auto', width: 150, change: function (args) { var pivotGridObj = document.getElementById('pivotview').ej2_instances[0]; pivotGridObj.gridSettings.selectionSettings.mode = args.value; pivotGridObj.renderModule.updateGridSettings(); } }); modeddl.appendTo('#mode'); var typeddl = new ej.dropdowns.DropDownList({ floatLabelType: 'Auto', width: 150, change: function (args) { var pivotGridObj = document.getElementById('pivotview').ej2_instances[0]; pivotGridObj.gridSettings.selectionSettings.type = args.value; pivotGridObj.renderModule.updateGridSettings(); } }); typeddl.appendTo('#type'); </script> } @section PreScripts { <script> ej.base.enableRipple(false); </script> } @section ActionDescription{ <div id="action-description"> <p> This sample demonstrates different types of grid cell selection options and an event to get complete information about the same. </p> </div> } @section Description{ <div id="description"> <p> This feature provides interactive support to highlight rows, columns, values, and summary cells that you select. Selection can be done through either mouse or keyboard interaction. To enable selection, set <code> allowSelection </code> as true. </p> <p> PivotGrid supports two types of selection that can be set using <code>selectionSettings.type</code> property. They are, </p> <ul> <li> <code>Single</code> - Enabled by default. Allows user to select a single row, column, or cell at a time. </li> <li><code>Multiple</code> - Allows the user to select more than one row, column, or cell at the same time.</li> </ul> <p> Also, there are three modes of selection that can be set using <code>selectionSettings.mode</code> property. They are, </p> <ul> <li><code>Row</code> - Enabled by default. Enables the complete row selection in a pivot grid.</li> <li><code>Column</code> - Enables the complete column selection in a pivot grid.</li> <li><code>Cell</code> - Enables only value and summary cell selection in a pivot grid.</li> <li><code>Both</code> - Enables both row and column selection in a pivot grid.</li> </ul> <p> To perform multiselection, hold the <strong>CTRL</strong> key and click the desired cells. To select a range of cells, hold the <strong>SHIFT</strong> key and click the cells. </p> <p> While using Pivot Grid in a touch device, double-tap over a row, column, or other cells. This results in a pop-up with a multiselect icon. Now tap the icon to proceed with multiselection. </p> <p> In this demo, pick the selection type and selection mode from the properties panel in order to perform the desired selection process. The selected cell information can be seen in the Event Trace part with the help of the <code>cellSelected</code> event. </p> </div> }
using System; using System.Collections.Generic; using System.Text; using FlubuCore.Context; using FlubuCore.Tasks; using FlubuCore.Tasks.Process; namespace FlubuCore.Azure.Tasks.Sf { public partial class AzureSfClusterClientCertificateTask : ExternalProcessTaskBase<AzureSfClusterClientCertificateTask> { /// <summary> /// Manage the client certificate of a cluster. /// </summary> public AzureSfClusterClientCertificateTask() { WithArguments("az sf cluster client-certificate"); } protected override string Description { get; set; } } }
namespace _07.RawData { public class Car { public string Model { get; set; } public Engine Engine { get; private set; } public Cargo Cargo { get; private set; } public Tire[] Tires { get; private set; } public Car(string model, Engine engine, Cargo cargo, Tire[] tires) { this.Model = model; this.Engine = engine; this.Cargo = cargo; this.Tires = tires; } } }
// *** 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.RecoveryServices.V20210301.Inputs { /// <summary> /// HyperV Replica Blue policy input. /// </summary> public sealed class HyperVReplicaBluePolicyInputArgs : Pulumi.ResourceArgs { /// <summary> /// A value indicating the authentication type. /// </summary> [Input("allowedAuthenticationType")] public Input<int>? AllowedAuthenticationType { get; set; } /// <summary> /// A value indicating the application consistent frequency. /// </summary> [Input("applicationConsistentSnapshotFrequencyInHours")] public Input<int>? ApplicationConsistentSnapshotFrequencyInHours { get; set; } /// <summary> /// A value indicating whether compression has to be enabled. /// </summary> [Input("compression")] public Input<string>? Compression { get; set; } /// <summary> /// A value indicating whether IR is online. /// </summary> [Input("initialReplicationMethod")] public Input<string>? InitialReplicationMethod { get; set; } /// <summary> /// The class type. /// Expected value is 'HyperVReplica2012R2'. /// </summary> [Input("instanceType")] public Input<string>? InstanceType { get; set; } /// <summary> /// A value indicating the offline IR export path. /// </summary> [Input("offlineReplicationExportPath")] public Input<string>? OfflineReplicationExportPath { get; set; } /// <summary> /// A value indicating the offline IR import path. /// </summary> [Input("offlineReplicationImportPath")] public Input<string>? OfflineReplicationImportPath { get; set; } /// <summary> /// A value indicating the online IR start time. /// </summary> [Input("onlineReplicationStartTime")] public Input<string>? OnlineReplicationStartTime { get; set; } /// <summary> /// A value indicating the number of recovery points. /// </summary> [Input("recoveryPoints")] public Input<int>? RecoveryPoints { get; set; } /// <summary> /// A value indicating whether the VM has to be auto deleted. /// </summary> [Input("replicaDeletion")] public Input<string>? ReplicaDeletion { get; set; } /// <summary> /// A value indicating the replication interval. /// </summary> [Input("replicationFrequencyInSeconds")] public Input<int>? ReplicationFrequencyInSeconds { get; set; } /// <summary> /// A value indicating the recovery HTTPS port. /// </summary> [Input("replicationPort")] public Input<int>? ReplicationPort { get; set; } public HyperVReplicaBluePolicyInputArgs() { } } }
using System; using System.IO; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; namespace Myrtille.Fleck { public class SocketWrapper : ISocket { private readonly Socket _socket; private Stream _stream; private CancellationTokenSource _tokenSource; private TaskFactory _taskFactory; public string RemoteIpAddress { get { var endpoint = _socket.RemoteEndPoint as IPEndPoint; return endpoint != null ? endpoint.Address.ToString() : null; } } public int RemotePort { get { var endpoint = _socket.RemoteEndPoint as IPEndPoint; return endpoint != null ? endpoint.Port : -1; } } public SocketWrapper(Socket socket) { _tokenSource = new CancellationTokenSource(); _taskFactory = new TaskFactory(_tokenSource.Token); _socket = socket; if (_socket.Connected) _stream = new NetworkStream(_socket); } public Task Authenticate(X509Certificate2 certificate, SslProtocols enabledSslProtocols, Action callback, Action<Exception> error) { var ssl = new SslStream(_stream, false); _stream = new QueuedStream(ssl); Func<AsyncCallback, object, IAsyncResult> begin = (cb, s) => ssl.BeginAuthenticateAsServer(certificate, false, enabledSslProtocols, false, cb, s); Task task = Task.Factory.FromAsync(begin, ssl.EndAuthenticateAsServer, null); task.ContinueWith(t => callback(), TaskContinuationOptions.NotOnFaulted) .ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted); task.ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted); return task; } public void Listen(int backlog) { _socket.Listen(backlog); } public void Bind(EndPoint endPoint) { _socket.Bind(endPoint); } public bool Connected { get { return _socket.Connected; } } public Stream Stream { get { return _stream; } } public bool NoDelay { get { return _socket.NoDelay; } set { _socket.NoDelay = value; } } public EndPoint LocalEndPoint { get { return _socket.LocalEndPoint; } } public Task<int> Receive(byte[] buffer, Action<int> callback, Action<Exception> error, int offset) { try { Func<AsyncCallback, object, IAsyncResult> begin = (cb, s) => _stream.BeginRead(buffer, offset, buffer.Length, cb, s); Task<int> task = Task.Factory.FromAsync<int>(begin, _stream.EndRead, null); task.ContinueWith(t => callback(t.Result), TaskContinuationOptions.NotOnFaulted) .ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted); task.ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted); return task; } catch (Exception e) { error(e); return null; } } public Task<ISocket> Accept(Action<ISocket> callback, Action<Exception> error) { Func<IAsyncResult, ISocket> end = r => _tokenSource.Token.IsCancellationRequested ? null : new SocketWrapper(_socket.EndAccept(r)); var task = _taskFactory.FromAsync(_socket.BeginAccept, end, null); task.ContinueWith(t => callback(t.Result), TaskContinuationOptions.OnlyOnRanToCompletion) .ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted); task.ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted); return task; } public void Dispose() { _tokenSource.Cancel(); if (_stream != null) _stream.Dispose(); if (_socket != null) _socket.Dispose(); } public void Close() { _tokenSource.Cancel(); if (_stream != null) _stream.Close(); if (_socket != null) _socket.Close(); } public int EndSend(IAsyncResult asyncResult) { _stream.EndWrite(asyncResult); return 0; } public Task Send(byte[] buffer, Action callback, Action<Exception> error) { if (_tokenSource.IsCancellationRequested) return null; try { Func<AsyncCallback, object, IAsyncResult> begin = (cb, s) => _stream.BeginWrite(buffer, 0, buffer.Length, cb, s); Task task = Task.Factory.FromAsync(begin, _stream.EndWrite, null); task.ContinueWith(t => callback(), TaskContinuationOptions.NotOnFaulted) .ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted); task.ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted); return task; } catch (Exception e) { error(e); return null; } } } }
// Copyright 2015-2018 The NATS Authors // 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.Threading; using System.Diagnostics; #if NET45 using System.Reflection; #endif using NATS.Client; using System.IO; namespace STAN.Client.UnitTests { class RunnableServer : IDisposable { Process p; string executablePath; public void init(string exeName, string args) { UnitTestUtilities.CleanupExistingServers(exeName); executablePath = exeName + ".exe"; ProcessStartInfo psInfo = createProcessStartInfo(args); try { p = Process.Start(psInfo); for (int i = 1; i <= 20; i++) { Thread.Sleep(100 * i); if (IsRunning()) break; } if (p.HasExited) { throw new Exception("Unable to start process."); } Thread.Sleep(1000); } catch (Exception ex) { p = null; throw new Exception(string.Format("{0} {1} failure with error: {2}", psInfo.FileName, psInfo.Arguments, ex.Message)); } } public RunnableServer(string exeName) { init(exeName, null); } public RunnableServer(string exeName, string args) { init(exeName, args); } private ProcessStartInfo createProcessStartInfo(string args) { ProcessStartInfo ps = new ProcessStartInfo(executablePath); ps.Arguments = args; ps.WorkingDirectory = UnitTestUtilities.GetConfigDir(); #if NET45 ps.WindowStyle = ProcessWindowStyle.Hidden; #else ps.CreateNoWindow = false; ps.RedirectStandardError = true; #endif return ps; } public bool IsRunning() { try { new ConnectionFactory().CreateConnection().Close(); return true; } catch (Exception) { return false; } } public void Shutdown() { if (p == null) return; try { p.Kill(); p.WaitForExit(60000); } catch (Exception) { } p = null; } void IDisposable.Dispose() { Shutdown(); } } class NatsServer : RunnableServer { public NatsServer() : base("gnatsd") { } public NatsServer(string args) : base("gnatsd", args) { } } class NatsStreamingServer : RunnableServer { public NatsStreamingServer() : base("nats-streaming-server") { } public NatsStreamingServer(string args) : base("nats-streaming-server", args) { } } class UnitTestUtilities { object mu = new object(); static internal string GetConfigDir() { #if NET45 string baseDir = Assembly.GetExecutingAssembly().CodeBase; return baseDir + "\\NATSUnitTests\\config"; #else return AppContext.BaseDirectory + string.Format("{0}..{0}..{0}..{0}", Path.DirectorySeparatorChar); #endif } internal static void CleanupExistingServers(string procname) { bool hadProc = false; try { Process[] procs = Process.GetProcessesByName(procname); foreach (Process proc in procs) { proc.Kill(); } } catch (Exception) { } // ignore if (hadProc) Thread.Sleep(500); } } }
namespace HuaweiMobileServices.IAP { public class OrderStatusCode { public const int ORDER_STATE_SUCCESS = 0; public const int ORDER_STATE_FAILED = -1; public const int ORDER_STATE_CANCEL = 60000; public const int ORDER_STATE_PARAM_ERROR = 60001; public const int ORDER_STATE_NET_ERROR = 60005; public const int ORDER_VR_UNINSTALL_ERROR = 60020; public const int ORDER_HWID_NOT_LOGIN = 60050; public const int ORDER_PRODUCT_OWNED = 60051; public const int ORDER_PRODUCT_NOT_OWNED = 60052; public const int ORDER_PRODUCT_CONSUMED = 60053; public const int ORDER_ACCOUNT_AREA_NOT_SUPPORTED = 60054; public const int ORDER_NOT_ACCEPT_AGREEMENT = 60055; } }
using System; using System.IO; using System.Linq; namespace AdventOfCode { class Program { static void Main (string[] args) { string[] dimensions = File.ReadLines(@"input.txt").ToArray(); ulong lengthOfRibbon = 0; foreach (var dim in dimensions) { lengthOfRibbon += calculateTotalLength(dim); } Console.WriteLine(lengthOfRibbon); } private static ulong calculateTotalLength(string dim) { ulong[] dims = dim.Split('x').Select(ulong.Parse).ToArray(); ulong len = calculateLength(dims); return len + (dims[0] * dims[1] * dims[2]); } private static ulong calculateLength(ulong[] dims) { return 2 * dims[0] + 2 * dims[1] + 2 * dims[2] - 2 * Math.Max(Math.Max(dims[0], dims[1]), dims[2]); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Antlr.Runtime; using Compiler.SemanticStructures; using Compiler.Errors; using Compiler.CodeGenerators; using System.Reflection; using System.Reflection.Emit; namespace Compiler.AST { public class RecordDotAccessNode : AccessNode { public RecordDotAccessNode(IToken token) : base(token) { } /// <summary> /// Expresion a la que se le hace punto /// </summary> public ExpressionNode DotedExpression { get { return GetChild(0) as ExpressionNode; } } /// <summary> /// Representa el id que se usa para acceder a un campo del record. /// </summary> public string ID { get { return GetChild(1).Text; } } public string RecordName { get; set; } public override void CheckSemantic(SymbolTable symbolTable, List<CompileError> errors) { //se manda a chequear semanticamente la expresion a la que se le hizo punto DotedExpression.CheckSemantic(symbolTable, errors); //si DotedExpression evalua de error este tambien evalua de error if (Object.Equals(DotedExpression.NodeInfo, SemanticInfo.SemanticError)) { ///el nodo evalúa de error NodeInfo = SemanticInfo.SemanticError; return; } //la expresion tiene que ser compatible con record if (!DotedExpression.NodeInfo.BuiltInType.IsCompatibleWith(BuiltInType.Record)) { errors.Add(new CompileError { Line = GetChild(1).Line, Column = GetChild(1).CharPositionInLine, ErrorMessage = "Dot notation can only be applied to 'record' types", Kind = ErrorKind.Semantic }); ///el nodo evalúa de error NodeInfo = SemanticInfo.SemanticError; } ///si este nodo evaluó de error if (Object.Equals(NodeInfo, SemanticInfo.SemanticError)) { ///terminamos de chequear la semántica de este nodo return; } //verificamos que el record tenga un campo con el nombre ID bool existField = false; foreach (var field in DotedExpression.NodeInfo.Fields) { if (field.Key.Equals(ID)) { existField = true; NodeInfo.Type = field.Value.Type; NodeInfo.BuiltInType = field.Value.BuiltInType; NodeInfo.ElementsType = field.Value.ElementsType; NodeInfo.Fields = field.Value.Fields; break; } } if (!existField) { errors.Add(new CompileError { Line = GetChild(1).Line, Column = GetChild(1).CharPositionInLine, ErrorMessage = string.Format("Type '{0}' does not contain a definition for '{1}'", DotedExpression.NodeInfo.Type.Name, ID), Kind = ErrorKind.Semantic }); ///el nodo evalúa de error NodeInfo = SemanticInfo.SemanticError; } RecordName = DotedExpression.NodeInfo.Type.Name; } public override void GenerateCode(ILCodeGenerator cg) { DotedExpression.GenerateCode(cg); if (LoadVariableInTheStack) { ILElementInfo ile = cg.ILContextTable.GetDefinedType(RecordName); FieldInfo fi = ile.TypeBuilder.GetField(ID); cg.ILGenerator.Emit(OpCodes.Ldfld, fi); } } } }
/* *************************************************************************** * This file is part of SharpNEAT - Evolution of Neural Networks. * * Copyright 2004-2016 Colin Green ([email protected]) * * SharpNEAT is free software; you can redistribute it and/or modify * it under the terms of The MIT License (MIT). * * You should have received a copy of the MIT License * along with SharpNEAT; if not, see https://opensource.org/licenses/MIT. */ using System.Diagnostics; namespace SharpNeat.Domains.FunctionRegression { /// <summary> /// Parameter sampling info. Describes the value range to sample, the number of samples within /// that range and the increment between samples. /// </summary> public struct ParamSamplingInfo { /// <summary>Sample range minimum.</summary> public readonly double _min; /// <summary>Sample range maximum.</summary> public readonly double _max; /// <summary>Intra sample increment.</summary> public readonly double _incr; /// <summary>Sample count.</summary> public readonly int _sampleCount; /// <summary>X positions of the sample points.</summary> public readonly double[] _xArr; /// <summary>X positions of the sample points in the neural net input space (i.e. scaled from 0 to 1)</summary> public readonly double[] _xArrNetwork; /// <summary> /// Construct with the provided parameter info. /// </summary> public ParamSamplingInfo(double min, double max, int sampleCount) { Debug.Assert(sampleCount>=3, "Sample count must be >= 3"); _min = min; _max = max; _incr = (max-min) / (sampleCount-1); _sampleCount = sampleCount; double incrNet = 1.0 / (sampleCount-1); double x = min; double xNet = 0; _xArr = new double[sampleCount]; _xArrNetwork = new double[sampleCount]; for(int i=0; i<sampleCount; i++, x += _incr, xNet += incrNet) { _xArr[i] = x; _xArrNetwork[i] = xNet; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using RimWorld; using Verse; using AbilityUser; using AbilityUserAI; using Verse.AI; using UnityEngine; using CompDeflector; namespace TorannMagic { [CompilerGenerated] [Serializable] [StaticConstructorOnStartup] public class CompAbilityUserMight : CompAbilityUser { public string LabelKey = "TM_Might"; public int customIndex = -2; public TMDefs.TM_CustomClass customClass = null; public bool mightPowersInitialized = false; public bool firstMightTick = false; private int age = -1; private int fortitudeMitigationDelay = 0; private int mightXPRate = 900; private int lastMightXPGain = 0; private int autocastTick = 0; private int nextAICastAttemptTick = 0; private int nextSSTend = 0; public bool canDeathRetaliate = false; private bool deathRetaliating = false; private int ticksTillRetaliation = 600; private List<IntVec3> deathRing = new List<IntVec3>(); public float weaponDamage = 1f; public float weaponCritChance = 0f; public bool shouldDrawPsionicShield = false; private float G_Sprint_eff = 0.20f; private float G_Grapple_eff = 0.10f; private float G_Cleave_eff = 0.10f; private float G_Whirlwind_eff = 0.10f; private float S_Headshot_eff = 0.10f; private float S_DisablingShot_eff = 0.10f; private float S_AntiArmor_eff = .10f; private float B_SeismicSlash_eff = 0.10f; private float B_BladeSpin_eff = 0.10f; private float B_PhaseStrike_eff = 0.08f; private float R_AnimalFriend_eff = 0.15f; private float R_ArrowStorm_eff = 0.08f; private float F_Disguise_eff = 0.10f; private float F_Mimic_eff = 0.08f; private float F_Reversal_eff = 0.10f; private float F_Transpose_eff = 0.08f; private float F_Possess_eff = 0.06f; private float P_PsionicBarrier_eff = 0.10f; private float P_PsionicBlast_eff = 0.08f; private float P_PsionicDash_eff = 0.10f; private float P_PsionicStorm_eff = 0.10f; private float DK_WaveOfFear_eff = 0.10f; private float DK_Spite_eff = 0.10f; private float DK_GraveBlade_eff = .08f; private float M_TigerStrike_eff = .1f; private float M_DragonStrike_eff = .1f; private float M_ThunderStrike_eff = .1f; private float C_CommanderAura_eff = .1f; private float C_TaskMasterAura_eff = .1f; private float C_ProvisionerAura_eff = .1f; private float C_StayAlert_eff = .1f; private float C_MoveOut_eff = .1f; private float C_HoldTheLine_eff = .1f; private float SS_PistolWhip_eff = .1f; private float SS_SuppressingFire_eff = .08f; private float SS_Mk203GL_eff = .08f; private float SS_Buckshot_eff = .08f; private float SS_BreachingCharge_eff = .08f; private float SS_CQC_eff = .1f; private float SS_FirstAid_eff = .1f; private float SS_60mmMortar_eff = .08f; private float global_seff = 0.03f; public bool skill_Sprint = false; public bool skill_GearRepair = false; public bool skill_InnerHealing = false; public bool skill_HeavyBlow = false; public bool skill_StrongBack = false; public bool skill_ThickSkin = false; public bool skill_FightersFocus = false; public bool skill_Teach = false; public bool skill_ThrowingKnife = false; public bool skill_BurningFury = false; public bool skill_PommelStrike = false; public bool skill_Legion = false; public bool skill_TempestStrike = false; public bool skill_PistolWhip = false; public bool skill_SuppressingFire = false; public bool skill_Mk203GL = false; public bool skill_Buckshot = false; public bool skill_BreachingCharge = false; public float maxSP = 1; public float spRegenRate = 1; public float coolDown = 1; public float spCost = 1; public float xpGain = 1; public float arcaneRes = 1; public float mightPwr = 1; private int resMitigationDelay = 0; private float totalApparelWeight = 0; public float arcalleumCooldown = 0f; public bool animalBondingDisabled = false; public bool usePsionicAugmentationToggle = true; public bool usePsionicMindAttackToggle = true; public bool useCleaveToggle = true; public bool useCQCToggle = true; public List<Thing> combatItems = new List<Thing>(); public int allowMeditateTick = 0; public ThingOwner<ThingWithComps> equipmentContainer = new ThingOwner<ThingWithComps>(); public int specWpnRegNum = -1; public Verb_Deflected deflectVerb; DamageInfo reversal_dinfo; Thing reversalTarget = null; public Pawn bondedPet = null; public Verb_UseAbility lastVerbUsed = null; public int lastTickVerbUsed = 0; public TMAbilityDef mimicAbility = null; private MightData mightData = null; public MightData MightData { get { bool flag = this.mightData == null && this.IsMightUser; if (flag) { this.mightData = new MightData(this); } return this.mightData; } } public bool shouldDraw = true; public override void PostDraw() { if (shouldDraw) { base.PostDraw(); if (this.Pawn.health.hediffSet.HasHediff(TorannMagicDefOf.TM_PossessionHD, false) || this.Pawn.health.hediffSet.HasHediff(TorannMagicDefOf.TM_PossessionHD_I, false) || this.Pawn.health.hediffSet.HasHediff(TorannMagicDefOf.TM_PossessionHD_II, false) || this.Pawn.health.hediffSet.HasHediff(TorannMagicDefOf.TM_PossessionHD_III, false) || this.Pawn.health.hediffSet.HasHediff(TorannMagicDefOf.TM_CoOpPossessionHD, false) || this.Pawn.health.hediffSet.HasHediff(TorannMagicDefOf.TM_CoOpPossessionHD_I, false) || this.Pawn.health.hediffSet.HasHediff(TorannMagicDefOf.TM_CoOpPossessionHD_II, false) || this.Pawn.health.hediffSet.HasHediff(TorannMagicDefOf.TM_CoOpPossessionHD_III, false)) { DrawDeceptionTicker(true); } else if (this.Pawn.health.hediffSet.HasHediff(TorannMagicDefOf.TM_DisguiseHD, false) || this.Pawn.health.hediffSet.HasHediff(TorannMagicDefOf.TM_DisguiseHD_I, false) || this.Pawn.health.hediffSet.HasHediff(TorannMagicDefOf.TM_DisguiseHD_II, false) || this.Pawn.health.hediffSet.HasHediff(TorannMagicDefOf.TM_DisguiseHD_III, false)) { DrawDeceptionTicker(false); } ModOptions.SettingsRef settingsRef = new ModOptions.SettingsRef(); if (settingsRef.AIFriendlyMarking && this.AbilityUser != null && this.AbilityUser.IsColonist && this.IsMightUser) { DrawFighterMark(); } if (settingsRef.AIMarking && base.AbilityUser != null && !base.AbilityUser.IsColonist && this.IsMightUser) { DrawFighterMark(); } if (this.Pawn.health.hediffSet.HasHediff(TorannMagicDefOf.TM_BurningFuryHD, false)) { Vector3 vector = this.Pawn.Drawer.DrawPos; vector.y = Altitudes.AltitudeFor(AltitudeLayer.MoteOverhead); float angle = (float)Rand.Range(0, 360); Vector3 s = new Vector3(1.7f, 1f, 1.7f); Matrix4x4 matrix = default(Matrix4x4); matrix.SetTRS(vector, Quaternion.AngleAxis(angle, Vector3.up), s); if (this.Pawn.health.hediffSet.HasHediff(TorannMagicDefOf.TM_BurningFuryHD)) { Graphics.DrawMesh(MeshPool.plane10, matrix, TM_RenderQueue.burningFuryMat, 0); } } if (shouldDrawPsionicShield) { float radius = 2.5f + (.75f * TM_Calc.GetMightSkillLevel(this.Pawn, this.MightData.MightPowerSkill_PsionicBarrier, "TM_PsionicBarrier", "_ver", true)); float drawRadius = radius * .23f; float num = Mathf.Lerp(drawRadius, 9.5f, drawRadius); Vector3 vector = this.Pawn.CurJob.targetA.CenterVector3; vector.y = Altitudes.AltitudeFor(AltitudeLayer.VisEffects); Vector3 s = new Vector3(num, 9.5f, num); Matrix4x4 matrix = default(Matrix4x4); matrix.SetTRS(vector, Quaternion.AngleAxis(Rand.Range(0, 360), Vector3.up), s); Graphics.DrawMesh(MeshPool.plane10, matrix, TM_MatPool.PsionicBarrier, 0); } } } public void DrawFighterMark() { Vector3 vector = this.AbilityUser.Drawer.DrawPos; vector.x = vector.x + .45f; vector.z = vector.z + .45f; vector.y = Altitudes.AltitudeFor(AltitudeLayer.MoteOverhead); float angle = 0f; Vector3 s = new Vector3(.28f, 1f, .28f); Matrix4x4 matrix = default(Matrix4x4); matrix.SetTRS(vector, Quaternion.AngleAxis(angle, Vector3.up), s); if (this.customClass != null) { CompAbilityUserMagic mComp = this.Pawn.TryGetComp<CompAbilityUserMagic>(); bool shouldDraw = true; if (mComp != null) { if (mComp.customClass != null) { shouldDraw = false; } } if (shouldDraw) { Material mat = TM_RenderQueue.fighterMarkMat; if (this.customClass.classIconPath != "") { mat = MaterialPool.MatFrom("Other/" + this.customClass.classIconPath.ToString()); } if (this.customClass.classIconColor != null) { mat.color = this.customClass.classIconColor; } Graphics.DrawMesh(MeshPool.plane10, matrix, mat, 0); } } else { if (this.AbilityUser.story.traits.HasTrait(TorannMagicDefOf.Gladiator)) { Graphics.DrawMesh(MeshPool.plane10, matrix, TM_RenderQueue.gladiatorMarkMat, 0); } else if (this.AbilityUser.story.traits.HasTrait(TorannMagicDefOf.TM_Sniper)) { Graphics.DrawMesh(MeshPool.plane10, matrix, TM_RenderQueue.sniperMarkMat, 0); } else if (this.AbilityUser.story.traits.HasTrait(TorannMagicDefOf.Bladedancer)) { Graphics.DrawMesh(MeshPool.plane10, matrix, TM_RenderQueue.bladedancerMarkMat, 0); } else if (this.AbilityUser.story.traits.HasTrait(TorannMagicDefOf.Ranger)) { Graphics.DrawMesh(MeshPool.plane10, matrix, TM_RenderQueue.rangerMarkMat, 0); } else if (this.AbilityUser.story.traits.HasTrait(TorannMagicDefOf.Faceless)) { Graphics.DrawMesh(MeshPool.plane10, matrix, TM_RenderQueue.facelessMarkMat, 0); } else if (this.AbilityUser.story.traits.HasTrait(TorannMagicDefOf.TM_Psionic)) { Graphics.DrawMesh(MeshPool.plane10, matrix, TM_RenderQueue.psionicMarkMat, 0); } else if (this.AbilityUser.story.traits.HasTrait(TorannMagicDefOf.DeathKnight)) { Graphics.DrawMesh(MeshPool.plane10, matrix, TM_RenderQueue.deathknightMarkMat, 0); } else if (this.AbilityUser.story.traits.HasTrait(TorannMagicDefOf.TM_Monk)) { Graphics.DrawMesh(MeshPool.plane10, matrix, TM_RenderQueue.monkMarkMat, 0); } else if (this.AbilityUser.story.traits.HasTrait(TorannMagicDefOf.TM_Commander)) { Graphics.DrawMesh(MeshPool.plane10, matrix, TM_RenderQueue.commanderMarkMat, 0); } else if (this.AbilityUser.story.traits.HasTrait(TorannMagicDefOf.TM_SuperSoldier)) { Graphics.DrawMesh(MeshPool.plane10, matrix, TM_RenderQueue.supersoldierMarkMat, 0); } else if (TM_Calc.IsWayfarer(this.AbilityUser)) { Graphics.DrawMesh(MeshPool.plane10, matrix, TM_RenderQueue.wayfarerMarkMat, 0); } else { Graphics.DrawMesh(MeshPool.plane10, matrix, TM_RenderQueue.fighterMarkMat, 0); } } } public void DrawDeceptionTicker(bool possessed) { if (possessed) { Vector3 vector = this.AbilityUser.Drawer.DrawPos; vector.x = vector.x - .25f; vector.z = vector.z + .8f; vector.y = Altitudes.AltitudeFor(AltitudeLayer.MoteOverhead); float angle = 0f; Vector3 s = new Vector3(.45f, 1f, .4f); Matrix4x4 matrix = default(Matrix4x4); matrix.SetTRS(vector, Quaternion.AngleAxis(angle, Vector3.up), s); Graphics.DrawMesh(MeshPool.plane10, matrix, TM_RenderQueue.possessionMask, 0); if (this.Pawn.health.hediffSet.HasHediff(TorannMagicDefOf.TM_DisguiseHD, false) || this.Pawn.health.hediffSet.HasHediff(TorannMagicDefOf.TM_DisguiseHD_I, false) || this.Pawn.health.hediffSet.HasHediff(TorannMagicDefOf.TM_DisguiseHD_II, false) || this.Pawn.health.hediffSet.HasHediff(TorannMagicDefOf.TM_DisguiseHD_III, false)) { vector.z = vector.z + .35f; matrix.SetTRS(vector, Quaternion.AngleAxis(angle, Vector3.up), s); Graphics.DrawMesh(MeshPool.plane10, matrix, TM_RenderQueue.deceptionEye, 0); } } else { Vector3 vector = this.AbilityUser.Drawer.DrawPos; vector.x = vector.x - .25f; vector.z = vector.z + .8f; vector.y = Altitudes.AltitudeFor(AltitudeLayer.MoteOverhead); float angle = 0f; Vector3 s = new Vector3(.45f, 1f, .4f); Matrix4x4 matrix = default(Matrix4x4); matrix.SetTRS(vector, Quaternion.AngleAxis(angle, Vector3.up), s); Graphics.DrawMesh(MeshPool.plane10, matrix, TM_RenderQueue.deceptionEye, 0); } } public static List<TMAbilityDef> MightAbilities = null; public int LevelUpSkill_global_refresh(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_global_refresh.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_global_seff(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_global_seff.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_global_strength(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_global_strength.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_global_endurance(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_global_endurance.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_Sprint(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_Sprint.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_Fortitude(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_Fortitude.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_Grapple(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_Grapple.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_Cleave(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_Cleave.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_Whirlwind(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_Whirlwind.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_SniperFocus(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_SniperFocus.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_Headshot(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_Headshot.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_DisablingShot(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_DisablingShot.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_AntiArmor(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_AntiArmor.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_BladeFocus(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_BladeFocus.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_BladeArt(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_BladeArt.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_SeismicSlash(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_SeismicSlash.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_BladeSpin(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_BladeSpin.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_PhaseStrike(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_PhaseStrike.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_RangerTraining(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_RangerTraining.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_BowTraining(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_BowTraining.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_PoisonTrap(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_PoisonTrap.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_AnimalFriend(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_AnimalFriend.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_ArrowStorm(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_ArrowStorm.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_Disguise(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_Disguise.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_Mimic(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_Mimic.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_Reversal(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_Reversal.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_Transpose(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_Transpose.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_Possess(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_Possess.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_PsionicAugmentation(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_PsionicAugmentation.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_PsionicBarrier(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_PsionicBarrier.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_PsionicBlast(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_PsionicBlast.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_PsionicDash(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_PsionicDash.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_PsionicStorm(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_PsionicStorm.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_Shroud(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_Shroud.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_WaveOfFear(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_WaveOfFear.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_Spite(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_Spite.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_LifeSteal(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_LifeSteal.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_GraveBlade(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_GraveBlade.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_Chi(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_Chi.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_MindOverBody(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_MindOverBody.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_Meditate(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_Meditate.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_TigerStrike(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_TigerStrike.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_DragonStrike(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_DragonStrike.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_ThunderStrike(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_ThunderStrike.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_WayfarerCraft(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_WayfarerCraft.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_FieldTraining(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_FieldTraining.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_Provisioner(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_ProvisionerAura.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_TaskMaster(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_TaskMasterAura.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_Commander(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_CommanderAura.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_StayAlert(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_StayAlert.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_MoveOut(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_MoveOut.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_HoldTheLine(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_HoldTheLine.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_PistolSpec(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_PistolSpec.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_RifleSpec(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_RifleSpec.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_ShotgunSpec(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_ShotgunSpec.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_CQC(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_CQC.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_FirstAid(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_FirstAid.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public int LevelUpSkill_60mmMortar(string skillName) { int result = 0; MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_60mmMortar.FirstOrDefault((MightPowerSkill x) => x.label == skillName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } return result; } public override void CompTick() { bool flag = base.AbilityUser != null; if (flag) { bool spawned = base.AbilityUser.Spawned; if (spawned) { bool isMightUser = this.IsMightUser && !this.Pawn.NonHumanlikeOrWildMan(); if (isMightUser) { bool flag3 = !this.MightData.Initialized; if (flag3) { this.PostInitializeTick(); } base.CompTick(); this.age++; if (Find.TickManager.TicksGame % 20 == 0) { ResolveSustainedSkills(); if (reversalTarget != null) { ResolveReversalDamage(); } } if (Find.TickManager.TicksGame % 60 == 0) { ResolveClassSkills(); //ResolveClassPassions(); currently disabled } ModOptions.SettingsRef settingsRef = new ModOptions.SettingsRef(); if (this.autocastTick < Find.TickManager.TicksGame) //180 default { if (!this.Pawn.Dead && !this.Pawn.Downed && this.Pawn.Map != null && this.Pawn.story != null && this.Pawn.story.traits != null && this.MightData != null && this.AbilityData != null && !this.Pawn.InMentalState) { if (this.Pawn.IsColonist) { this.autocastTick = Find.TickManager.TicksGame + (int)Rand.Range(.8f * settingsRef.autocastEvaluationFrequency, 1.2f * settingsRef.autocastEvaluationFrequency); ResolveAutoCast(); } else if (settingsRef.AICasting && (!this.Pawn.IsPrisoner || this.Pawn.IsFighting())) { float tickMult = settingsRef.AIAggressiveCasting ? 1f : 2f; this.autocastTick = Find.TickManager.TicksGame + (int)(Rand.Range(.8f * settingsRef.autocastEvaluationFrequency, 1.2f * settingsRef.autocastEvaluationFrequency) * tickMult); ResolveAIAutoCast(); } } } if (!this.Pawn.IsColonist && settingsRef.AICasting && settingsRef.AIAggressiveCasting && Find.TickManager.TicksGame > this.nextAICastAttemptTick) //Aggressive AI Casting { this.nextAICastAttemptTick = Find.TickManager.TicksGame + Rand.Range(300, 500); if (this.Pawn.jobs != null && this.Pawn.CurJobDef != TorannMagicDefOf.TMCastAbilitySelf && this.Pawn.CurJobDef != TorannMagicDefOf.TMCastAbilityVerb) { IEnumerable<AbilityUserAIProfileDef> enumerable = this.Pawn.EligibleAIProfiles(); if (enumerable != null && enumerable.Count() > 0) { foreach (AbilityUserAIProfileDef item in enumerable) { if (item != null) { AbilityAIDef useThisAbility = null; if (item.decisionTree != null) { useThisAbility = item.decisionTree.RecursivelyGetAbility(this.Pawn); } if (useThisAbility != null) { ThingComp val = this.Pawn.AllComps.First((ThingComp comp) => ((object)comp).GetType() == item.compAbilityUserClass); CompAbilityUser compAbilityUser = val as CompAbilityUser; if (compAbilityUser != null) { PawnAbility pawnAbility = compAbilityUser.AbilityData.AllPowers.First((PawnAbility ability) => ability.Def == useThisAbility.ability); string reason = ""; if (pawnAbility.CanCastPowerCheck(AbilityContext.AI, out reason)) { LocalTargetInfo target = useThisAbility.Worker.TargetAbilityFor(useThisAbility, this.Pawn); if (target.IsValid) { pawnAbility.UseAbility(AbilityContext.Player, target); } } } } } } } } } if (this.Pawn.needs.AllNeeds.Contains(this.Stamina) && this.Stamina.CurLevel > (.99f * this.Stamina.MaxLevel)) { if (this.age > (lastMightXPGain + mightXPRate)) { MightData.MightUserXP++; lastMightXPGain = this.age; } } bool flag4 = Find.TickManager.TicksGame % 30 == 0; if (flag4) { bool flag5 = this.MightUserXP > this.MightUserXPTillNextLevel; if (flag5) { this.LevelUp(false); } } if (Find.TickManager.TicksGame % 30 == 0) { bool flag6 = this.Pawn.TargetCurrentlyAimingAt != null; if (flag6) { if (this.Pawn.TargetCurrentlyAimingAt.Thing is Pawn) { Pawn targetPawn = this.Pawn.TargetCurrentlyAimingAt.Thing as Pawn; if (targetPawn.RaceProps.Humanlike) { bool flag7 = this.Pawn.health.hediffSet.HasHediff(HediffDef.Named("TM_DisguiseHD")) || this.Pawn.health.hediffSet.HasHediff(HediffDef.Named("TM_DisguiseHD_I")) || this.Pawn.health.hediffSet.HasHediff(HediffDef.Named("TM_DisguiseHD_II")) || this.Pawn.health.hediffSet.HasHediff(HediffDef.Named("TM_DisguiseHD_III")); if (targetPawn.Faction != this.Pawn.Faction && flag7) { using (IEnumerator<Hediff> enumerator = this.Pawn.health.hediffSet.GetHediffs<Hediff>().GetEnumerator()) { while (enumerator.MoveNext()) { Hediff rec = enumerator.Current; if (rec.def == TorannMagicDefOf.TM_DisguiseHD || rec.def == TorannMagicDefOf.TM_DisguiseHD_I || rec.def == TorannMagicDefOf.TM_DisguiseHD_II || rec.def == TorannMagicDefOf.TM_DisguiseHD_III) { this.Pawn.health.RemoveHediff(rec); } } } } } } } } if (deathRetaliating) { DoDeathRetaliation(); } else if (Find.TickManager.TicksGame % 67 == 0 && !this.Pawn.IsColonist && this.Pawn.Downed) { DoDeathRetaliation(); } if (Find.TickManager.TicksGame % 301 == 0) //cache weapon damage for tooltip and damage calculations { this.weaponDamage = TM_Calc.GetSkillDamage(this.Pawn); } } } else { if (Find.TickManager.TicksGame % 600 == 0) { if (this.Pawn.Map == null) { if (this.IsMightUser) { int num; if (AbilityData?.AllPowers != null) { AbilityData obj = AbilityData; num = (obj != null && obj.AllPowers.Count > 0) ? 1 : 0; } else { num = 0; } if (num != 0) { foreach (PawnAbility allPower in AbilityData.AllPowers) { allPower.CooldownTicksLeft -= 600; if (allPower.CooldownTicksLeft <= 0) { allPower.CooldownTicksLeft = 0; } } } } } } } } if (IsInitialized) { //custom code } } public void DoDeathRetaliation() { if (!this.Pawn.Downed || this.Pawn.Map == null || this.Pawn.IsPrisoner || this.Pawn.Faction == null || !this.Pawn.Faction.HostileTo(Faction.OfPlayerSilentFail)) { this.deathRetaliating = false; this.canDeathRetaliate = false; } if (this.canDeathRetaliate && this.deathRetaliating) { this.ticksTillRetaliation--; if (this.deathRing == null || this.deathRing.Count < 1) { this.deathRing = TM_Calc.GetOuterRing(this.Pawn.Position, 1f, 2f); } if (Find.TickManager.TicksGame % 7 == 0) { Vector3 moteVec = this.deathRing.RandomElement().ToVector3Shifted(); moteVec.x += Rand.Range(-.4f, .4f); moteVec.z += Rand.Range(-.4f, .4f); float angle = (Quaternion.AngleAxis(90, Vector3.up) * TM_Calc.GetVector(moteVec, this.Pawn.DrawPos)).ToAngleFlat(); ThingDef mote = TorannMagicDefOf.Mote_Psi_Grayscale; mote.graphicData.color = Color.white; TM_MoteMaker.ThrowGenericMote(TorannMagicDefOf.Mote_Psi_Grayscale, moteVec, this.Pawn.Map, Rand.Range(.25f, .6f), .1f, .05f, .05f, 0, Rand.Range(4f, 6f), angle, angle); } if (this.ticksTillRetaliation <= 0) { this.canDeathRetaliate = false; this.deathRetaliating = false; TM_Action.CreateMightDeathEffect(this.Pawn, this.Pawn.Position); } } else if (this.canDeathRetaliate && Rand.Value < .04f) { ModOptions.SettingsRef settingsRef = new ModOptions.SettingsRef(); this.deathRetaliating = true; this.ticksTillRetaliation = Mathf.RoundToInt(Rand.Range(400, 1200) * settingsRef.deathRetaliationDelayFactor); this.deathRing = TM_Calc.GetOuterRing(this.Pawn.Position, 1f, 2f); } } public void PostInitializeTick() { bool flag = base.AbilityUser != null; if (flag) { bool spawned = base.AbilityUser.Spawned; if (spawned) { bool flag2 = base.AbilityUser.story != null; if (flag2) { //this.MightData.Initialized = true; this.Initialize(); this.ResolveMightTab(); this.ResolveMightPowers(); this.ResolveStamina(); } } } } public bool IsMightUser { get { bool flag = base.AbilityUser != null; if (flag) { bool flag3 = base.AbilityUser.story != null; if (flag3) { if (this.customClass != null) { return true; } if (this.customClass == null && this.customIndex == -2) { this.customIndex = TM_ClassUtility.IsCustomClassIndex(this.AbilityUser.story.traits.allTraits); if (this.customIndex >= 0) { if (!TM_ClassUtility.CustomClasses()[this.customIndex].isFighter) { this.customIndex = -1; return false; } else { this.customClass = TM_ClassUtility.CustomClasses()[this.customIndex]; return true; } } } bool flag4 = base.AbilityUser.story.traits.HasTrait(TorannMagicDefOf.TM_Monk) || base.AbilityUser.story.traits.HasTrait(TorannMagicDefOf.DeathKnight) || base.AbilityUser.story.traits.HasTrait(TorannMagicDefOf.TM_Psionic) || base.AbilityUser.story.traits.HasTrait(TorannMagicDefOf.Gladiator) || base.AbilityUser.story.traits.HasTrait(TorannMagicDefOf.TM_Sniper) || base.AbilityUser.story.traits.HasTrait(TorannMagicDefOf.Bladedancer) || base.AbilityUser.story.traits.HasTrait(TorannMagicDefOf.Ranger) || base.AbilityUser.story.traits.HasTrait(TorannMagicDefOf.Faceless) || TM_Calc.IsWayfarer(base.AbilityUser) || base.AbilityUser.story.traits.HasTrait(TorannMagicDefOf.TM_Commander) || base.AbilityUser.story.traits.HasTrait(TorannMagicDefOf.TM_SuperSoldier); if (flag4) { return true; } } } return false; } } public int MightUserLevel { get { if (this.MightData != null) { return this.MightData.MightUserLevel; } return 0; } set { bool flag = value > this.MightData.MightUserLevel; if (flag) { this.MightData.MightAbilityPoints++; bool flag2 = this.MightData.MightUserXP < GetXPForLevel(value - 1); if (flag2) { this.MightData.MightUserXP = GetXPForLevel(value - 1); } } this.MightData.MightUserLevel = value; } } private Dictionary<int, int> cacheXPFL = new Dictionary<int, int>(); public int GetXPForLevel(int lvl) { if (!cacheXPFL.ContainsKey(lvl)) { IntVec2 c1 = new IntVec2(0, 50); IntVec2 c2 = new IntVec2(5, 40); IntVec2 c3 = new IntVec2(15, 20); IntVec2 c4 = new IntVec2(30, 10); IntVec2 c5 = new IntVec2(200, 0); int val = 0; for (int i = 0; i < lvl + 1; i++) { val += (Mathf.Clamp(i, c1.x, c2.x - 1) * c1.z) + c1.z; if (i >= c2.x) { val += (Mathf.Clamp(i, c2.x, c3.x - 1) * c2.z) + c2.z; } if (i >= c3.x) { val += (Mathf.Clamp(i, c3.x, c4.x - 1) * c3.z) + c3.z; } if (i >= c4.x) { val += (Mathf.Clamp(i, c4.x, c5.x - 1) * c4.z) + c4.z; } } cacheXPFL.Add(lvl, val); } if (cacheXPFL.TryGetValue(lvl, out var value)) { return value; } else { return 0; } } public int MightUserXP { get { return this.MightData.MightUserXP; } set { this.MightData.MightUserXP = value; } } public float XPLastLevel { get { bool flag = this.MightUserLevel > 0; if (flag) { return GetXPForLevel(this.MightUserLevel - 1); } return 0f; } } public float XPTillNextLevelPercent { get { return ((float)this.MightData.MightUserXP - this.XPLastLevel) / ((float)this.MightUserXPTillNextLevel - this.XPLastLevel); } } public int MightUserXPTillNextLevel { get { if (MightUserXP < XPLastLevel) { MightUserXP = (int)XPLastLevel; } return GetXPForLevel(this.MightUserLevel); } } public void LevelUp(bool hideNotification = false) { if (!this.Pawn.story.traits.HasTrait(TorannMagicDefOf.TM_Wanderer)) { if (this.MightUserLevel < (this.customClass?.maxFighterLevel ?? 200)) { this.MightUserLevel++; bool flag = !hideNotification; if (flag) { ModOptions.SettingsRef settingsRef = new ModOptions.SettingsRef(); if (Pawn.IsColonist && settingsRef.showLevelUpMessage) { Messages.Message("TM_MightLevelUp".Translate( this.parent.Label ), Pawn, MessageTypeDefOf.PositiveEvent); } } } } else { this.MightUserXP = (int)this.XPLastLevel; } } public void LevelUpPower(MightPower power) { foreach (AbilityUser.AbilityDef current in power.TMabilityDefs) { base.RemovePawnAbility(current); } power.level++; base.AddPawnAbility(power.TMabilityDefs[power.level], true, -1f); this.UpdateAbilities(); } public Need_Stamina Stamina { get { if (!base.AbilityUser.DestroyedOrNull() && base.abilityUserSave.needs != null) { return base.AbilityUser.needs.TryGetNeed<Need_Stamina>(); } return null; } } public override void PostInitialize() { base.PostInitialize(); bool flag = CompAbilityUserMight.MightAbilities == null; if (flag) { if (this.mightPowersInitialized == false && MightData != null) { AssignAbilities(); } //this.UpdateAbilities(); //base.UpdateAbilities(); } } public void AssignAbilities() { Pawn abilityUser = base.AbilityUser; bool flag2; MightData.MightUserLevel = 0; MightData.MightAbilityPoints = 0; if (this.customClass != null) { for (int z = 0; z < this.MightData.AllMightPowers.Count; z++) { if (this.customClass.classFighterAbilities.Contains(this.MightData.AllMightPowers[z].abilityDef)) { this.MightData.AllMightPowers[z].learned = true; } TMAbilityDef ability = (TMAbilityDef)this.MightData.AllMightPowers[z].abilityDef; if (this.MightData.AllMightPowers[z].learned) { if (ability.shouldInitialize) { this.AddPawnAbility(ability); } if (ability.childAbilities != null && ability.childAbilities.Count > 0) { for (int c = 0; c < ability.childAbilities.Count; c++) { if (ability.childAbilities[c].shouldInitialize) { this.AddPawnAbility(ability.childAbilities[c]); } } } } } //for (int j = 0; j < this.customClass.classFighterAbilities.Count; j++) //{ //} if (this.customClass.classHediff != null) { HealthUtility.AdjustSeverity(abilityUser, this.customClass.classHediff, this.customClass.hediffSeverity); } } else { flag2 = TM_Calc.IsWayfarer(abilityUser); if (flag2) { //Log.Message("Initializing Wayfarer Abilities"); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_WayfarerCraft).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_FieldTraining).learned = true; if (!abilityUser.IsColonist) { this.skill_ThrowingKnife = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_ThrowingKnife).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_ThrowingKnife); } for (int i = 0; i < 2; i++) { MightPower mp = this.MightData.MightPowersStandalone.RandomElement(); if (mp.abilityDef == TorannMagicDefOf.TM_GearRepair) { mp.learned = true; skill_GearRepair = true; } else if (mp.abilityDef == TorannMagicDefOf.TM_InnerHealing) { mp.learned = true; skill_InnerHealing = true; } else if (mp.abilityDef == TorannMagicDefOf.TM_HeavyBlow) { mp.learned = true; skill_HeavyBlow = true; } else if (mp.abilityDef == TorannMagicDefOf.TM_ThickSkin) { mp.learned = true; skill_ThickSkin = true; } else if (mp.abilityDef == TorannMagicDefOf.TM_FightersFocus) { mp.learned = true; skill_FightersFocus = true; } else if (mp.abilityDef == TorannMagicDefOf.TM_StrongBack) { mp.learned = true; skill_StrongBack = true; } else if (mp.abilityDef == TorannMagicDefOf.TM_ThrowingKnife) { mp.learned = true; skill_ThrowingKnife = true; } else if (mp.abilityDef == TorannMagicDefOf.TM_PommelStrike) { mp.learned = true; skill_PommelStrike = true; } } InitializeSkill(); } flag2 = abilityUser.story.traits.HasTrait(TorannMagicDefOf.Gladiator); if (flag2) { //Log.Message("Initializing Gladiator Abilities"); this.AddPawnAbility(TorannMagicDefOf.TM_Sprint); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_Sprint).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_Sprint_I).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_Sprint_II).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_Sprint_III).learned = true; //this.AddPawnAbility(TorannMagicDefOf.TM_Fortitude); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_Fortitude).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_Grapple); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_Grapple).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_Grapple_I).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_Grapple_II).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_Grapple_III).learned = true; //this.AddPawnAbility(TorannMagicDefOf.TM_Cleave); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_Cleave).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_Whirlwind); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_Whirlwind).learned = true; } flag2 = abilityUser.story.traits.HasTrait(TorannMagicDefOf.TM_Sniper); if (flag2) { //Log.Message("Initializing Sniper Abilities"); //this.AddPawnAbility(TorannMagicDefOf.TM_SniperFocus); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_SniperFocus).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_Headshot); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_Headshot).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_DisablingShot); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_DisablingShot).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_DisablingShot_I).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_DisablingShot_II).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_DisablingShot_III).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_AntiArmor); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_AntiArmor).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_ShadowSlayer); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_ShadowSlayer).learned = true; } flag2 = abilityUser.story.traits.HasTrait(TorannMagicDefOf.Bladedancer); if (flag2) { // Log.Message("Initializing Bladedancer Abilities"); // this.AddPawnAbility(TorannMagicDefOf.TM_BladeFocus); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_BladeFocus).learned = true; //this.AddPawnAbility(TorannMagicDefOf.TM_BladeArt); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_BladeArt).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_SeismicSlash); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_SeismicSlash).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_BladeSpin); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_BladeSpin).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_PhaseStrike); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_PhaseStrike).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_PhaseStrike_I).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_PhaseStrike_II).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_PhaseStrike_III).learned = true; } flag2 = abilityUser.story.traits.HasTrait(TorannMagicDefOf.Ranger); if (flag2) { //Log.Message("Initializing Ranger Abilities"); //this.AddPawnAbility(TorannMagicDefOf.TM_RangerTraining); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_RangerTraining).learned = true; // this.AddPawnAbility(TorannMagicDefOf.TM_BowTraining); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_BowTraining).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_PoisonTrap); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_PoisonTrap).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_AnimalFriend); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_AnimalFriend).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_ArrowStorm); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_ArrowStorm).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_ArrowStorm_I).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_ArrowStorm_II).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_ArrowStorm_III).learned = true; } flag2 = abilityUser.story.traits.HasTrait(TorannMagicDefOf.Faceless); if (flag2) { //Log.Message("Initializing Faceless Abilities"); this.AddPawnAbility(TorannMagicDefOf.TM_Disguise); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_Disguise).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_Mimic); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_Mimic).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_Reversal); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_Reversal).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_Transpose); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_Transpose).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_Transpose_I).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_Transpose_II).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_Transpose_III).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_Possess); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_Possess).learned = true; } flag2 = abilityUser.story.traits.HasTrait(TorannMagicDefOf.TM_Psionic); if (flag2) { //Log.Message("Initializing Psionic Abilities"); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_PsionicAugmentation).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_PsionicBarrier); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_PsionicBarrier).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_PsionicBarrier_Projected).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_PsionicBlast); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_PsionicBlast).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_PsionicBlast_I).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_PsionicBlast_II).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_PsionicBlast_III).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_PsionicDash); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_PsionicDash).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_PsionicStorm); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_PsionicStorm).learned = true; } flag2 = abilityUser.story.traits.HasTrait(TorannMagicDefOf.DeathKnight); if (flag2) { //Log.Message("Initializing Death Knight Abilities"); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_Shroud).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_WaveOfFear); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_WaveOfFear).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_Spite); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_Spite).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_Spite_I).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_Spite_II).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_Spite_III).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_LifeSteal).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_GraveBlade); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_GraveBlade).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_GraveBlade_I).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_GraveBlade_II).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_GraveBlade_III).learned = true; } flag2 = abilityUser.story.traits.HasTrait(TorannMagicDefOf.TM_Monk); if (flag2) { //Log.Message("Initializing Monk Abilities"); //this.AddPawnAbility(TorannMagicDefOf.TM_Chi); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_Chi).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_ChiBurst); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_MindOverBody).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_Meditate); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_Meditate).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_TigerStrike); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_TigerStrike).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_DragonStrike); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_DragonStrike).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_ThunderStrike); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_ThunderStrike).learned = true; } flag2 = abilityUser.story.traits.HasTrait(TorannMagicDefOf.TM_Commander); if (flag2) { //Log.Message("Initializing Commander Abilities"); this.AddPawnAbility(TorannMagicDefOf.TM_ProvisionerAura); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_ProvisionerAura).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_TaskMasterAura); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_TaskMasterAura).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_CommanderAura); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_CommanderAura).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_StayAlert); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_StayAlert).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_StayAlert_I).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_StayAlert_II).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_StayAlert_III).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_MoveOut); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_MoveOut).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_MoveOut_I).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_MoveOut_II).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_MoveOut_III).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_HoldTheLine); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_HoldTheLine).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_HoldTheLine_I).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_HoldTheLine_II).learned = true; this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_HoldTheLine_III).learned = true; } flag2 = abilityUser.story.traits.HasTrait(TorannMagicDefOf.TM_SuperSoldier); if (flag2) { //Log.Message("Initializing Super Soldier Abilities"); this.MightData.MightPowersSS.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_PistolSpec).learned = false; this.MightData.MightPowersSS.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_RifleSpec).learned = false; this.MightData.MightPowersSS.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_ShotgunSpec).learned = false; //this.MightData.MightPowersSS.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_PistolWhip).learned = false; //this.MightData.MightPowersSS.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_SuppressingFire).learned = false; //this.MightData.MightPowersSS.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_Mk203GL).learned = false; //this.MightData.MightPowersSS.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_Buckshot).learned = false; //this.MightData.MightPowersSS.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_BreachingCharge).learned = false; //this.AddPawnAbility(TorannMagicDefOf.TM_CQC); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_CQC).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_FirstAid); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_FirstAid).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_60mmMortar); this.MightData.ReturnMatchingMightPower(TorannMagicDefOf.TM_60mmMortar).learned = true; } } this.mightPowersInitialized = true; //base.UpdateAbilities(); } public void InitializeSkill() //used for class independant skills { Pawn abilityUser = base.AbilityUser; if (this.mimicAbility != null) { this.RemovePawnAbility(mimicAbility); this.AddPawnAbility(mimicAbility); } if (this.customClass != null) { //for (int j = 0; j < this.MightData.AllMightPowersWithSkills.Count; j++) //{ // if (this.MightData.AllMightPowersWithSkills[j].learned && !this.customClass.classFighterAbilities.Contains(this.MightData.AllMightPowersWithSkills[j].abilityDef)) // { // this.MightData.AllMightPowersWithSkills[j].learned = false; // this.RemovePawnAbility(this.MightData.AllMightPowersWithSkills[j].abilityDef); // } //} for (int j = 0; j < this.MightData.AllMightPowers.Count; j++) { if (this.MightData.AllMightPowers[j].learned && !this.customClass.classFighterAbilities.Contains(this.MightData.AllMightPowers[j].abilityDef)) { this.RemovePawnAbility(this.MightData.AllMightPowers[j].abilityDef); this.AddPawnAbility(this.MightData.AllMightPowers[j].abilityDef); } } } else { if (this.skill_Sprint == true && !abilityUser.story.traits.HasTrait(TorannMagicDefOf.Gladiator)) { this.RemovePawnAbility(TorannMagicDefOf.TM_Sprint); this.AddPawnAbility(TorannMagicDefOf.TM_Sprint); } if (this.skill_GearRepair == true) { this.RemovePawnAbility(TorannMagicDefOf.TM_GearRepair); this.AddPawnAbility(TorannMagicDefOf.TM_GearRepair); } if (this.skill_InnerHealing == true) { this.RemovePawnAbility(TorannMagicDefOf.TM_InnerHealing); this.AddPawnAbility(TorannMagicDefOf.TM_InnerHealing); } if (this.skill_StrongBack == true) { this.RemovePawnAbility(TorannMagicDefOf.TM_StrongBack); this.AddPawnAbility(TorannMagicDefOf.TM_StrongBack); } if (this.skill_HeavyBlow == true) { this.RemovePawnAbility(TorannMagicDefOf.TM_HeavyBlow); this.AddPawnAbility(TorannMagicDefOf.TM_HeavyBlow); } if (this.skill_ThickSkin == true) { this.RemovePawnAbility(TorannMagicDefOf.TM_ThickSkin); this.AddPawnAbility(TorannMagicDefOf.TM_ThickSkin); } if (this.skill_FightersFocus == true) { this.RemovePawnAbility(TorannMagicDefOf.TM_FightersFocus); this.AddPawnAbility(TorannMagicDefOf.TM_FightersFocus); } if (this.skill_Teach == true) { this.RemovePawnAbility(TorannMagicDefOf.TM_TeachMight); this.AddPawnAbility(TorannMagicDefOf.TM_TeachMight); } if (this.skill_ThrowingKnife == true) { this.RemovePawnAbility(TorannMagicDefOf.TM_ThrowingKnife); this.AddPawnAbility(TorannMagicDefOf.TM_ThrowingKnife); } if (this.skill_BurningFury == true) { this.RemovePawnAbility(TorannMagicDefOf.TM_BurningFury); this.AddPawnAbility(TorannMagicDefOf.TM_BurningFury); } if (this.skill_PommelStrike == true) { this.RemovePawnAbility(TorannMagicDefOf.TM_PommelStrike); this.AddPawnAbility(TorannMagicDefOf.TM_PommelStrike); } if (this.skill_TempestStrike == true) { this.RemovePawnAbility(TorannMagicDefOf.TM_TempestStrike); this.AddPawnAbility(TorannMagicDefOf.TM_TempestStrike); } if (this.skill_Legion == true) { this.RemovePawnAbility(TorannMagicDefOf.TM_Legion); this.AddPawnAbility(TorannMagicDefOf.TM_Legion); } if (this.skill_PistolWhip) { this.RemovePawnAbility(TorannMagicDefOf.TM_PistolWhip); this.AddPawnAbility(TorannMagicDefOf.TM_PistolWhip); } if (this.skill_SuppressingFire) { this.RemovePawnAbility(TorannMagicDefOf.TM_SuppressingFire); this.AddPawnAbility(TorannMagicDefOf.TM_SuppressingFire); } if (this.skill_Mk203GL) { this.RemovePawnAbility(TorannMagicDefOf.TM_Mk203GL); this.AddPawnAbility(TorannMagicDefOf.TM_Mk203GL); } if (this.skill_Buckshot) { this.RemovePawnAbility(TorannMagicDefOf.TM_Buckshot); this.AddPawnAbility(TorannMagicDefOf.TM_Buckshot); } if (this.skill_BreachingCharge) { this.RemovePawnAbility(TorannMagicDefOf.TM_BreachingCharge); this.AddPawnAbility(TorannMagicDefOf.TM_BreachingCharge); } if (this.IsMightUser && this.MightData.MightPowersCustom != null && this.MightData.MightPowersCustom.Count > 0) { for (int j = 0; j < this.MightData.MightPowersCustom.Count; j++) { if (this.MightData.MightPowersCustom[j].learned) { this.RemovePawnAbility(this.MightData.MightPowersCustom[j].abilityDef); this.AddPawnAbility(this.MightData.MightPowersCustom[j].abilityDef); } } } } } public void FixPowers() { Pawn abilityUser = base.AbilityUser; if (this.mightPowersInitialized == true) { bool flag2; flag2 = abilityUser.story.traits.HasTrait(TorannMagicDefOf.Gladiator); if (flag2) { Log.Message("Fixing Gladiator Abilities"); foreach (MightPower currentG in this.MightData.MightPowersG) { if (currentG.abilityDef.defName == "TM_Sprint" || currentG.abilityDef.defName == "TM_Sprint_I" || currentG.abilityDef.defName == "TM_Sprint_II" || currentG.abilityDef.defName == "TM_Sprint_III") { if (currentG.level == 0) { this.RemovePawnAbility(TorannMagicDefOf.TM_Sprint_I); this.RemovePawnAbility(TorannMagicDefOf.TM_Sprint_II); this.RemovePawnAbility(TorannMagicDefOf.TM_Sprint_III); } else if (currentG.level == 1) { this.RemovePawnAbility(TorannMagicDefOf.TM_Sprint); this.RemovePawnAbility(TorannMagicDefOf.TM_Sprint_II); this.RemovePawnAbility(TorannMagicDefOf.TM_Sprint_III); } else if (currentG.level == 2) { this.RemovePawnAbility(TorannMagicDefOf.TM_Sprint); this.RemovePawnAbility(TorannMagicDefOf.TM_Sprint_I); this.RemovePawnAbility(TorannMagicDefOf.TM_Sprint_III); } else if (currentG.level == 3) { this.RemovePawnAbility(TorannMagicDefOf.TM_Sprint); this.RemovePawnAbility(TorannMagicDefOf.TM_Sprint_II); this.RemovePawnAbility(TorannMagicDefOf.TM_Sprint_I); } else { Log.Message("Ability level not found to fix"); } } if (currentG.abilityDef.defName == "TM_Grapple" || currentG.abilityDef.defName == "TM_Grapple_I" || currentG.abilityDef.defName == "TM_Grapple_II" || currentG.abilityDef.defName == "TM_Grapple_III") { if (currentG.level == 0) { this.RemovePawnAbility(TorannMagicDefOf.TM_Grapple_I); this.RemovePawnAbility(TorannMagicDefOf.TM_Grapple_II); this.RemovePawnAbility(TorannMagicDefOf.TM_Grapple_III); } else if (currentG.level == 1) { this.RemovePawnAbility(TorannMagicDefOf.TM_Grapple); this.RemovePawnAbility(TorannMagicDefOf.TM_Grapple_II); this.RemovePawnAbility(TorannMagicDefOf.TM_Grapple_III); } else if (currentG.level == 2) { this.RemovePawnAbility(TorannMagicDefOf.TM_Grapple); this.RemovePawnAbility(TorannMagicDefOf.TM_Grapple_I); this.RemovePawnAbility(TorannMagicDefOf.TM_Grapple_III); } else if (currentG.level == 3) { this.RemovePawnAbility(TorannMagicDefOf.TM_Grapple); this.RemovePawnAbility(TorannMagicDefOf.TM_Grapple_II); this.RemovePawnAbility(TorannMagicDefOf.TM_Grapple_I); } else { Log.Message("Ability level not found to fix"); } } } } } //this.UpdateAbilities(); //base.UpdateAbilities(); } public override bool TryTransformPawn() { return this.IsMightUser; } public bool TryAddPawnAbility(TMAbilityDef ability) { base.AddPawnAbility(ability, true, -1f); //add check to verify no ability is already added bool result = true; return result; } public void RemovePowers(bool clearStandalone = false) { if (this.mightPowersInitialized == true && MightData != null) { bool flag2 = true; if (this.customClass != null) { for (int i = 0; i < this.MightData.AllMightPowers.Count; i++) { MightPower mp = this.MightData.AllMightPowers[i]; for (int j = 0; j < mp.TMabilityDefs.Count; j++) { TMAbilityDef tmad = mp.TMabilityDefs[j] as TMAbilityDef; if (tmad.childAbilities != null && tmad.childAbilities.Count > 0) { for (int k = 0; k < tmad.childAbilities.Count; k++) { this.RemovePawnAbility(tmad.childAbilities[k]); } } this.RemovePawnAbility(mp.TMabilityDefs[j]); } mp.learned = false; } } if (clearStandalone) { this.skill_BurningFury = false; this.skill_FightersFocus = false; this.skill_GearRepair = false; this.skill_HeavyBlow = false; this.skill_InnerHealing = false; this.skill_Legion = false; this.skill_PommelStrike = false; this.skill_Sprint = false; this.skill_StrongBack = false; this.skill_Teach = false; this.skill_TempestStrike = false; this.skill_ThickSkin = false; this.skill_ThrowingKnife = false; } foreach (MightPower current in this.MightData.MightPowersStandalone) { this.RemovePawnAbility(current.abilityDef); } foreach (MightPower current in this.MightData.AllMightPowers) { this.RemovePawnAbility(current.abilityDef); } if (TM_Calc.IsWayfarer(this.AbilityUser)) { this.skill_ThrowingKnife = false; this.RemovePawnAbility(TorannMagicDefOf.TM_ThrowingKnife); } //flag2 = abilityUser.story.traits.HasTrait(TorannMagicDefOf.Gladiator); if (flag2) { foreach (MightPower current in this.MightData.MightPowersG) { current.learned = false; this.RemovePawnAbility(current.abilityDef); } this.RemovePawnAbility(TorannMagicDefOf.TM_Sprint_I); this.RemovePawnAbility(TorannMagicDefOf.TM_Sprint_II); this.RemovePawnAbility(TorannMagicDefOf.TM_Sprint_III); this.RemovePawnAbility(TorannMagicDefOf.TM_Grapple_I); this.RemovePawnAbility(TorannMagicDefOf.TM_Grapple_II); this.RemovePawnAbility(TorannMagicDefOf.TM_Grapple_III); } //flag2 = abilityUser.story.traits.HasTrait(TorannMagicDefOf.TM_Sniper); if (flag2) { foreach (MightPower current in this.MightData.MightPowersS) { current.learned = false; this.RemovePawnAbility(current.abilityDef); } this.RemovePawnAbility(TorannMagicDefOf.TM_DisablingShot_I); this.RemovePawnAbility(TorannMagicDefOf.TM_DisablingShot_II); this.RemovePawnAbility(TorannMagicDefOf.TM_DisablingShot_III); } //flag2 = abilityUser.story.traits.HasTrait(TorannMagicDefOf.Bladedancer); if (flag2) { foreach (MightPower current in this.MightData.MightPowersB) { current.learned = false; this.RemovePawnAbility(current.abilityDef); } this.RemovePawnAbility(TorannMagicDefOf.TM_PhaseStrike_I); this.RemovePawnAbility(TorannMagicDefOf.TM_PhaseStrike_II); this.RemovePawnAbility(TorannMagicDefOf.TM_PhaseStrike_III); } //flag2 = abilityUser.story.traits.HasTrait(TorannMagicDefOf.Ranger); if (flag2) { foreach (MightPower current in this.MightData.MightPowersR) { current.learned = false; this.RemovePawnAbility(current.abilityDef); } this.RemovePawnAbility(TorannMagicDefOf.TM_ArrowStorm_I); this.RemovePawnAbility(TorannMagicDefOf.TM_ArrowStorm_II); this.RemovePawnAbility(TorannMagicDefOf.TM_ArrowStorm_III); } //flag2 = abilityUser.story.traits.HasTrait(TorannMagicDefOf.Faceless); if (flag2) { foreach (MightPower current in this.MightData.MightPowersF) { current.learned = false; this.RemovePawnAbility(current.abilityDef); } this.RemovePawnAbility(TorannMagicDefOf.TM_Transpose_I); this.RemovePawnAbility(TorannMagicDefOf.TM_Transpose_II); this.RemovePawnAbility(TorannMagicDefOf.TM_Transpose_III); } //flag2 = abilityUser.story.traits.HasTrait(TorannMagicDefOf.TM_Psionic); if (flag2) { foreach (MightPower current in this.MightData.MightPowersP) { current.learned = false; this.RemovePawnAbility(current.abilityDef); } this.RemovePawnAbility(TorannMagicDefOf.TM_PsionicBarrier_Projected); this.RemovePawnAbility(TorannMagicDefOf.TM_PsionicBlast_I); this.RemovePawnAbility(TorannMagicDefOf.TM_PsionicBlast_II); this.RemovePawnAbility(TorannMagicDefOf.TM_PsionicBlast_III); } //flag2 = abilityUser.story.traits.HasTrait(TorannMagicDefOf.DeathKnight); if (flag2) { foreach (MightPower current in this.MightData.MightPowersDK) { current.learned = false; this.RemovePawnAbility(current.abilityDef); } this.RemovePawnAbility(TorannMagicDefOf.TM_Spite_I); this.RemovePawnAbility(TorannMagicDefOf.TM_Spite_II); this.RemovePawnAbility(TorannMagicDefOf.TM_Spite_III); this.RemovePawnAbility(TorannMagicDefOf.TM_GraveBlade_I); this.RemovePawnAbility(TorannMagicDefOf.TM_GraveBlade_II); this.RemovePawnAbility(TorannMagicDefOf.TM_GraveBlade_III); } //flag2 = abilityUser.story.traits.HasTrait(TorannMagicDefOf.TM_Monk); if (flag2) { foreach (MightPower current in this.MightData.MightPowersM) { current.learned = false; this.RemovePawnAbility(current.abilityDef); } this.RemovePawnAbility(TorannMagicDefOf.TM_ChiBurst); } //flag2 = abilityUser.story.traits.HasTrait(TorannMagicDefOf.TM_Commander); if (flag2) { foreach (MightPower current in this.MightData.MightPowersC) { current.learned = false; this.RemovePawnAbility(current.abilityDef); } this.RemovePawnAbility(TorannMagicDefOf.TM_StayAlert_I); this.RemovePawnAbility(TorannMagicDefOf.TM_StayAlert_II); this.RemovePawnAbility(TorannMagicDefOf.TM_StayAlert_III); this.RemovePawnAbility(TorannMagicDefOf.TM_MoveOut_I); this.RemovePawnAbility(TorannMagicDefOf.TM_MoveOut_II); this.RemovePawnAbility(TorannMagicDefOf.TM_MoveOut_III); this.RemovePawnAbility(TorannMagicDefOf.TM_HoldTheLine_I); this.RemovePawnAbility(TorannMagicDefOf.TM_HoldTheLine_II); this.RemovePawnAbility(TorannMagicDefOf.TM_HoldTheLine_III); } //flag2 = abilityUser.story.traits.HasTrait(TorannMagicDefOf.TM_SuperSoldier); if (flag2) { foreach (MightPower current in this.MightData.MightPowersSS) { current.learned = false; this.RemovePawnAbility(current.abilityDef); } this.RemovePawnAbility(TorannMagicDefOf.TM_PistolWhip); this.skill_PistolWhip = false; this.RemovePawnAbility(TorannMagicDefOf.TM_SuppressingFire); this.skill_SuppressingFire = false; this.RemovePawnAbility(TorannMagicDefOf.TM_Mk203GL); this.skill_Mk203GL = false; this.RemovePawnAbility(TorannMagicDefOf.TM_Buckshot); this.skill_Buckshot = false; this.RemovePawnAbility(TorannMagicDefOf.TM_BreachingCharge); this.skill_BreachingCharge = false; } } } public void ResetSkills() { this.MightData.MightPowerSkill_global_endurance.FirstOrDefault((MightPowerSkill x) => x.label == "TM_global_endurance_pwr").level = 0; this.MightData.MightPowerSkill_global_refresh.FirstOrDefault((MightPowerSkill x) => x.label == "TM_global_refresh_pwr").level = 0; this.MightData.MightPowerSkill_global_seff.FirstOrDefault((MightPowerSkill x) => x.label == "TM_global_seff_pwr").level = 0; this.MightData.MightPowerSkill_global_strength.FirstOrDefault((MightPowerSkill x) => x.label == "TM_global_strength_pwr").level = 0; for (int i = 0; i < this.MightData.AllMightPowersWithSkills.Count; i++) { this.MightData.AllMightPowersWithSkills[i].level = 0; this.MightData.AllMightPowersWithSkills[i].learned = false; this.MightData.AllMightPowersWithSkills[i].autocast = false; TMAbilityDef ability = (TMAbilityDef)this.MightData.AllMightPowersWithSkills[i].abilityDef; MightPowerSkill mps = this.MightData.GetSkill_Efficiency(ability); if (mps != null) { mps.level = 0; } mps = this.MightData.GetSkill_Power(ability); if (mps != null) { mps.level = 0; } mps = this.MightData.GetSkill_Versatility(ability); if (mps != null) { mps.level = 0; } } for (int i = 0; i < this.MightData.AllMightPowers.Count; i++) { for (int j = 0; j < this.MightData.AllMightPowers[i].TMabilityDefs.Count; j++) { TMAbilityDef ability = (TMAbilityDef)this.MightData.AllMightPowers[i].TMabilityDefs[j]; this.RemovePawnAbility(ability); } this.MightData.AllMightPowers[i].learned = false; this.MightData.AllMightPowers[i].autocast = false; } this.MightUserLevel = 0; this.MightUserXP = 0; this.MightData.MightAbilityPoints = 0; //this.MightPowersInitialized = false; //base.IsInitialized = false; //CompAbilityUserMight.MightAbilities = null; //this.MightData = null; this.AssignAbilities(); } public void RemoveTMagicHediffs() { IEnumerable<Hediff> allHediffs = this.Pawn.health.hediffSet.GetHediffs<Hediff>(); foreach (Hediff hediff in allHediffs) { if (hediff.def.defName.Contains("TM_")) { this.Pawn.health.RemoveHediff(hediff); } } } public void RemoveAbilityUser() { this.RemovePowers(); this.RemoveTMagicHediffs(); this.RemoveTraits(); this.mightData = null; base.IsInitialized = false; } public void RemoveTraits() { List<Trait> traits = this.AbilityUser.story.traits.allTraits; for (int i = 0; i < traits.Count; i++) { if (traits[i].def == TorannMagicDefOf.Gladiator || traits[i].def == TorannMagicDefOf.Bladedancer || traits[i].def == TorannMagicDefOf.Ranger || traits[i].def == TorannMagicDefOf.Faceless || traits[i].def == TorannMagicDefOf.DeathKnight || traits[i].def == TorannMagicDefOf.TM_Psionic || traits[i].def == TorannMagicDefOf.TM_Sniper || traits[i].def == TorannMagicDefOf.TM_Monk || traits[i].def == TorannMagicDefOf.TM_Wayfarer || traits[i].def == TorannMagicDefOf.TM_Commander || traits[i].def == TorannMagicDefOf.TM_SuperSoldier) { Log.Message("Removing trait " + traits[i].Label); traits.Remove(traits[i]); i--; } } } public int MightAttributeEffeciencyLevel(string attributeName) { int result = 0; if (this.mightData != null && attributeName != null) { if (attributeName == "TM_Sprint_eff") { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_Sprint.FirstOrDefault((MightPowerSkill x) => x.label == attributeName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } } if (attributeName == "TM_Fortitude_eff") { MightPowerSkill magicPowerSkill = this.MightData.MightPowerSkill_Fortitude.FirstOrDefault((MightPowerSkill x) => x.label == attributeName); bool flag = magicPowerSkill != null; if (flag) { result = magicPowerSkill.level; } } if (attributeName == "TM_Grapple_eff") { MightPowerSkill magicPowerSkill = this.MightData.MightPowerSkill_Grapple.FirstOrDefault((MightPowerSkill x) => x.label == attributeName); bool flag = magicPowerSkill != null; if (flag) { result = magicPowerSkill.level; } } if (attributeName == "TM_Cleave_eff") { MightPowerSkill magicPowerSkill = this.MightData.MightPowerSkill_Cleave.FirstOrDefault((MightPowerSkill x) => x.label == attributeName); bool flag = magicPowerSkill != null; if (flag) { result = magicPowerSkill.level; } } if (attributeName == "TM_Whirlwind_eff") { MightPowerSkill magicPowerSkill = this.MightData.MightPowerSkill_Whirlwind.FirstOrDefault((MightPowerSkill x) => x.label == attributeName); bool flag = magicPowerSkill != null; if (flag) { result = magicPowerSkill.level; } } if (attributeName == "TM_Headshot_eff") { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_Headshot.FirstOrDefault((MightPowerSkill x) => x.label == attributeName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } } if (attributeName == "TM_DisablingShot_eff") { MightPowerSkill magicPowerSkill = this.MightData.MightPowerSkill_DisablingShot.FirstOrDefault((MightPowerSkill x) => x.label == attributeName); bool flag = magicPowerSkill != null; if (flag) { result = magicPowerSkill.level; } } if (attributeName == "TM_AntiArmor_eff") { MightPowerSkill magicPowerSkill = this.MightData.MightPowerSkill_AntiArmor.FirstOrDefault((MightPowerSkill x) => x.label == attributeName); bool flag = magicPowerSkill != null; if (flag) { result = magicPowerSkill.level; } } if (attributeName == "TM_SeismicSlash_eff") { MightPowerSkill magicPowerSkill = this.MightData.MightPowerSkill_SeismicSlash.FirstOrDefault((MightPowerSkill x) => x.label == attributeName); bool flag = magicPowerSkill != null; if (flag) { result = magicPowerSkill.level; } } if (attributeName == "TM_BladeSpin_eff") { MightPowerSkill magicPowerSkill = this.MightData.MightPowerSkill_BladeSpin.FirstOrDefault((MightPowerSkill x) => x.label == attributeName); bool flag = magicPowerSkill != null; if (flag) { result = magicPowerSkill.level; } } if (attributeName == "TM_PhaseStrike_eff") { MightPowerSkill magicPowerSkill = this.MightData.MightPowerSkill_PhaseStrike.FirstOrDefault((MightPowerSkill x) => x.label == attributeName); bool flag = magicPowerSkill != null; if (flag) { result = magicPowerSkill.level; } } if (attributeName == "TM_AnimalFriend_eff") { MightPowerSkill magicPowerSkill = this.MightData.MightPowerSkill_AnimalFriend.FirstOrDefault((MightPowerSkill x) => x.label == attributeName); bool flag = magicPowerSkill != null; if (flag) { result = magicPowerSkill.level; } } if (attributeName == "TM_ArrowStorm_eff") { MightPowerSkill magicPowerSkill = this.MightData.MightPowerSkill_ArrowStorm.FirstOrDefault((MightPowerSkill x) => x.label == attributeName); bool flag = magicPowerSkill != null; if (flag) { result = magicPowerSkill.level; } } if (attributeName == "TM_Disguise_eff") { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_Disguise.FirstOrDefault((MightPowerSkill x) => x.label == attributeName); bool flag = mightPowerSkill != null; if (flag) { result = mightPowerSkill.level; } } if (attributeName == "TM_Mimic_eff") { MightPowerSkill magicPowerSkill = this.MightData.MightPowerSkill_Mimic.FirstOrDefault((MightPowerSkill x) => x.label == attributeName); bool flag = magicPowerSkill != null; if (flag) { result = magicPowerSkill.level; } } if (attributeName == "TM_Reversal_eff") { MightPowerSkill magicPowerSkill = this.MightData.MightPowerSkill_Reversal.FirstOrDefault((MightPowerSkill x) => x.label == attributeName); bool flag = magicPowerSkill != null; if (flag) { result = magicPowerSkill.level; } } if (attributeName == "TM_Transpose_eff") { MightPowerSkill magicPowerSkill = this.MightData.MightPowerSkill_Transpose.FirstOrDefault((MightPowerSkill x) => x.label == attributeName); bool flag = magicPowerSkill != null; if (flag) { result = magicPowerSkill.level; } } if (attributeName == "TM_Possess_eff") { MightPowerSkill magicPowerSkill = this.MightData.MightPowerSkill_Possess.FirstOrDefault((MightPowerSkill x) => x.label == attributeName); bool flag = magicPowerSkill != null; if (flag) { result = magicPowerSkill.level; } } if (attributeName == "TM_PsionicBarrier_eff") { MightPowerSkill magicPowerSkill = this.MightData.MightPowerSkill_PsionicBarrier.FirstOrDefault((MightPowerSkill x) => x.label == attributeName); bool flag = magicPowerSkill != null; if (flag) { result = magicPowerSkill.level; } } if (attributeName == "TM_PsionicBlast_eff") { MightPowerSkill magicPowerSkill = this.MightData.MightPowerSkill_PsionicBlast.FirstOrDefault((MightPowerSkill x) => x.label == attributeName); bool flag = magicPowerSkill != null; if (flag) { result = magicPowerSkill.level; } } if (attributeName == "TM_PsionicDash_eff") { MightPowerSkill magicPowerSkill = this.MightData.MightPowerSkill_PsionicDash.FirstOrDefault((MightPowerSkill x) => x.label == attributeName); bool flag = magicPowerSkill != null; if (flag) { result = magicPowerSkill.level; } } if (attributeName == "TM_PsionicStorm_eff") { MightPowerSkill magicPowerSkill = this.MightData.MightPowerSkill_PsionicStorm.FirstOrDefault((MightPowerSkill x) => x.label == attributeName); bool flag = magicPowerSkill != null; if (flag) { result = magicPowerSkill.level; } } if (attributeName == "TM_WaveOfFear_eff") { MightPowerSkill magicPowerSkill = this.MightData.MightPowerSkill_WaveOfFear.FirstOrDefault((MightPowerSkill x) => x.label == attributeName); bool flag = magicPowerSkill != null; if (flag) { result = magicPowerSkill.level; } } if (attributeName == "TM_Spite_eff") { MightPowerSkill magicPowerSkill = this.MightData.MightPowerSkill_Spite.FirstOrDefault((MightPowerSkill x) => x.label == attributeName); bool flag = magicPowerSkill != null; if (flag) { result = magicPowerSkill.level; } } if (attributeName == "TM_GraveBlade_eff") { MightPowerSkill magicPowerSkill = this.MightData.MightPowerSkill_GraveBlade.FirstOrDefault((MightPowerSkill x) => x.label == attributeName); bool flag = magicPowerSkill != null; if (flag) { result = magicPowerSkill.level; } } if (attributeName == "TM_TigerStrike_eff") { MightPowerSkill magicPowerSkill = this.MightData.MightPowerSkill_TigerStrike.FirstOrDefault((MightPowerSkill x) => x.label == attributeName); bool flag = magicPowerSkill != null; if (flag) { result = magicPowerSkill.level; } } if (attributeName == "TM_DragonStrike_eff") { MightPowerSkill magicPowerSkill = this.MightData.MightPowerSkill_DragonStrike.FirstOrDefault((MightPowerSkill x) => x.label == attributeName); bool flag = magicPowerSkill != null; if (flag) { result = magicPowerSkill.level; } } if (attributeName == "TM_ThunderStrike_eff") { MightPowerSkill magicPowerSkill = this.MightData.MightPowerSkill_ThunderStrike.FirstOrDefault((MightPowerSkill x) => x.label == attributeName); bool flag = magicPowerSkill != null; if (flag) { result = magicPowerSkill.level; } } if (attributeName == "TM_FieldTraining_eff") { MightPowerSkill magicPowerSkill = this.MightData.MightPowerSkill_FieldTraining.FirstOrDefault((MightPowerSkill x) => x.label == attributeName); bool flag = magicPowerSkill != null; if (flag) { result = magicPowerSkill.level; } } if (attributeName == "TM_WayfarerCraft_eff") { MightPowerSkill magicPowerSkill = this.MightData.MightPowerSkill_WayfarerCraft.FirstOrDefault((MightPowerSkill x) => x.label == attributeName); bool flag = magicPowerSkill != null; if (flag) { result = magicPowerSkill.level; } } if (attributeName == "TM_StayAlert_eff") { MightPowerSkill magicPowerSkill = this.MightData.MightPowerSkill_StayAlert.FirstOrDefault((MightPowerSkill x) => x.label == attributeName); bool flag = magicPowerSkill != null; if (flag) { result = magicPowerSkill.level; } } if (attributeName == "TM_MoveOut_eff") { MightPowerSkill magicPowerSkill = this.MightData.MightPowerSkill_MoveOut.FirstOrDefault((MightPowerSkill x) => x.label == attributeName); bool flag = magicPowerSkill != null; if (flag) { result = magicPowerSkill.level; } } if (attributeName == "TM_HoldTheLine_eff") { MightPowerSkill magicPowerSkill = this.MightData.MightPowerSkill_HoldTheLine.FirstOrDefault((MightPowerSkill x) => x.label == attributeName); bool flag = magicPowerSkill != null; if (flag) { result = magicPowerSkill.level; } } } return result; } public float ActualChiCost(TMAbilityDef mightDef) { float num = mightDef.chiCost; num *= 1 - (.06f * this.MightData.MightPowerSkill_Chi.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Chi_eff").level); MightPowerSkill mps = this.MightData.GetSkill_Efficiency(mightDef); if (mps != null) { num *= 1 - (mightDef.efficiencyReductionPercent * mps.level); } return num; } public float ActualStaminaCost(TMAbilityDef mightDef) { float adjustedStaminaCost = mightDef.staminaCost; if (mightDef.efficiencyReductionPercent != 0) { if (mightDef == TorannMagicDefOf.TM_PistolWhip) { adjustedStaminaCost *= 1f - (mightDef.efficiencyReductionPercent * this.MightData.GetSkill_Versatility(TorannMagicDefOf.TM_PistolSpec).level); } else if (mightDef == TorannMagicDefOf.TM_SuppressingFire) { adjustedStaminaCost *= 1f - (mightDef.efficiencyReductionPercent * this.MightData.GetSkill_Efficiency(TorannMagicDefOf.TM_RifleSpec).level); } else if (mightDef == TorannMagicDefOf.TM_Mk203GL) { adjustedStaminaCost *= 1f - (mightDef.efficiencyReductionPercent * this.MightData.GetSkill_Versatility(TorannMagicDefOf.TM_RifleSpec).level); } else if (mightDef == TorannMagicDefOf.TM_Buckshot) { adjustedStaminaCost *= 1f - (mightDef.efficiencyReductionPercent * this.MightData.GetSkill_Efficiency(TorannMagicDefOf.TM_ShotgunSpec).level); } else if (mightDef == TorannMagicDefOf.TM_BreachingCharge) { adjustedStaminaCost *= 1f - (mightDef.efficiencyReductionPercent * this.MightData.GetSkill_Versatility(TorannMagicDefOf.TM_ShotgunSpec).level); } else if (this.Pawn.story.traits.HasTrait(TorannMagicDefOf.Faceless) && mightDef != TorannMagicDefOf.TM_Possess && mightDef != TorannMagicDefOf.TM_Disguise && mightDef != TorannMagicDefOf.TM_Transpose && mightDef != TorannMagicDefOf.TM_Transpose_I && mightDef != TorannMagicDefOf.TM_Transpose_II && mightDef != TorannMagicDefOf.TM_Transpose_III && mightDef != TorannMagicDefOf.TM_Mimic && mightDef != TorannMagicDefOf.TM_Reversal) { adjustedStaminaCost *= 1f - (mightDef.efficiencyReductionPercent * this.mightData.GetSkill_Efficiency(TorannMagicDefOf.TM_Mimic).level); } else if (mightDef == TorannMagicDefOf.TM_AnimalFriend) { return .5f * mightDef.staminaCost; } else if (mightDef == TorannMagicDefOf.TM_ProvisionerAura && this.Pawn.health.hediffSet.HasHediff(TorannMagicDefOf.TM_ProvisionerAuraHD)) { return 0f; } else if (mightDef == TorannMagicDefOf.TM_TaskMasterAura && this.Pawn.health.hediffSet.HasHediff(TorannMagicDefOf.TM_TaskMasterAuraHD)) { return 0f; } else if (mightDef == TorannMagicDefOf.TM_CommanderAura && this.Pawn.health.hediffSet.HasHediff(TorannMagicDefOf.TM_CommanderAuraHD)) { return 0f; } else { MightPowerSkill mps = this.MightData.GetSkill_Efficiency(mightDef); if (mps != null) { adjustedStaminaCost *= 1f - (mightDef.efficiencyReductionPercent * mps.level); } } } else { if (mightDef == TorannMagicDefOf.TM_Sprint || mightDef == TorannMagicDefOf.TM_Sprint_I || mightDef == TorannMagicDefOf.TM_Sprint_II || mightDef == TorannMagicDefOf.TM_Sprint_III) { adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.G_Sprint_eff * (float)this.MightAttributeEffeciencyLevel("TM_Sprint_eff"))); } if (mightDef == TorannMagicDefOf.TM_Grapple || mightDef == TorannMagicDefOf.TM_Grapple_I || mightDef == TorannMagicDefOf.TM_Grapple_II || mightDef == TorannMagicDefOf.TM_Grapple_III) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_Grapple.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Grapple_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.G_Grapple_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_Cleave) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_Cleave.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Cleave_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.G_Cleave_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_Whirlwind) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_Whirlwind.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Whirlwind_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.G_Whirlwind_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_Headshot) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_Headshot.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Headshot_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.S_Headshot_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_DisablingShot || mightDef == TorannMagicDefOf.TM_DisablingShot_I || mightDef == TorannMagicDefOf.TM_DisablingShot_II || mightDef == TorannMagicDefOf.TM_DisablingShot_III) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_DisablingShot.FirstOrDefault((MightPowerSkill x) => x.label == "TM_DisablingShot_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.S_DisablingShot_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_AntiArmor) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_AntiArmor.FirstOrDefault((MightPowerSkill x) => x.label == "TM_AntiArmor_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.S_AntiArmor_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_SeismicSlash) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_SeismicSlash.FirstOrDefault((MightPowerSkill x) => x.label == "TM_SeismicSlash_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.B_SeismicSlash_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_BladeSpin) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_BladeSpin.FirstOrDefault((MightPowerSkill x) => x.label == "TM_BladeSpin_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.B_BladeSpin_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_PhaseStrike || mightDef == TorannMagicDefOf.TM_PhaseStrike_I || mightDef == TorannMagicDefOf.TM_PhaseStrike_II || mightDef == TorannMagicDefOf.TM_PhaseStrike_III) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_PhaseStrike.FirstOrDefault((MightPowerSkill x) => x.label == "TM_PhaseStrike_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.B_PhaseStrike_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_AnimalFriend) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_AnimalFriend.FirstOrDefault((MightPowerSkill x) => x.label == "TM_AnimalFriend_eff"); if (this.bondedPet != null) { adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.R_AnimalFriend_eff * (float)mightPowerSkill.level) / 2); } else { adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.R_AnimalFriend_eff * (float)mightPowerSkill.level)); } } if (mightDef == TorannMagicDefOf.TM_ArrowStorm || mightDef == TorannMagicDefOf.TM_ArrowStorm_I || mightDef == TorannMagicDefOf.TM_ArrowStorm_II || mightDef == TorannMagicDefOf.TM_ArrowStorm_III) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_ArrowStorm.FirstOrDefault((MightPowerSkill x) => x.label == "TM_ArrowStorm_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.R_ArrowStorm_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_Disguise) { adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.F_Disguise_eff * (float)this.MightAttributeEffeciencyLevel("TM_Disguise_eff"))); } if (mightDef == TorannMagicDefOf.TM_Transpose || mightDef == TorannMagicDefOf.TM_Transpose_I || mightDef == TorannMagicDefOf.TM_Transpose_II || mightDef == TorannMagicDefOf.TM_Transpose_III) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_Transpose.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Transpose_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.F_Transpose_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_Mimic) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_Mimic.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Mimic_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.F_Mimic_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_Reversal) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_Reversal.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Reversal_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.F_Reversal_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_Possess) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_Possess.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Possess_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.F_Possess_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_PsionicBarrier || mightDef == TorannMagicDefOf.TM_PsionicBarrier_Projected) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_PsionicBarrier.FirstOrDefault((MightPowerSkill x) => x.label == "TM_PsionicBarrier_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.P_PsionicBarrier_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_PsionicBlast || mightDef == TorannMagicDefOf.TM_PsionicBlast_I || mightDef == TorannMagicDefOf.TM_PsionicBlast_II || mightDef == TorannMagicDefOf.TM_PsionicBlast_III) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_PsionicBlast.FirstOrDefault((MightPowerSkill x) => x.label == "TM_PsionicBlast_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.P_PsionicBlast_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_PsionicDash) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_PsionicDash.FirstOrDefault((MightPowerSkill x) => x.label == "TM_PsionicDash_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.P_PsionicDash_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_PsionicStorm) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_PsionicStorm.FirstOrDefault((MightPowerSkill x) => x.label == "TM_PsionicStorm_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.P_PsionicStorm_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_Spite || mightDef == TorannMagicDefOf.TM_Spite_I || mightDef == TorannMagicDefOf.TM_Spite_II || mightDef == TorannMagicDefOf.TM_Spite_III) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_Spite.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Spite_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.DK_Spite_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_WaveOfFear) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_WaveOfFear.FirstOrDefault((MightPowerSkill x) => x.label == "TM_WaveOfFear_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.DK_WaveOfFear_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_GraveBlade || mightDef == TorannMagicDefOf.TM_GraveBlade_I || mightDef == TorannMagicDefOf.TM_GraveBlade_II || mightDef == TorannMagicDefOf.TM_GraveBlade_III) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_GraveBlade.FirstOrDefault((MightPowerSkill x) => x.label == "TM_GraveBlade_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.DK_GraveBlade_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_TigerStrike) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_TigerStrike.FirstOrDefault((MightPowerSkill x) => x.label == "TM_TigerStrike_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.M_TigerStrike_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_DragonStrike) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_DragonStrike.FirstOrDefault((MightPowerSkill x) => x.label == "TM_DragonStrike_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.M_DragonStrike_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_ThunderStrike) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_ThunderStrike.FirstOrDefault((MightPowerSkill x) => x.label == "TM_ThunderStrike_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.M_ThunderStrike_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_ProvisionerAura) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_ProvisionerAura.FirstOrDefault((MightPowerSkill x) => x.label == "TM_ProvisionerAura_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.C_ProvisionerAura_eff * (float)mightPowerSkill.level)); if (this.Pawn.health.hediffSet.HasHediff(TorannMagicDefOf.TM_ProvisionerAuraHD)) { return 0f; } } if (mightDef == TorannMagicDefOf.TM_TaskMasterAura) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_TaskMasterAura.FirstOrDefault((MightPowerSkill x) => x.label == "TM_TaskMasterAura_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.C_TaskMasterAura_eff * (float)mightPowerSkill.level)); if (this.Pawn.health.hediffSet.HasHediff(TorannMagicDefOf.TM_TaskMasterAuraHD)) { return 0f; } } if (mightDef == TorannMagicDefOf.TM_CommanderAura) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_CommanderAura.FirstOrDefault((MightPowerSkill x) => x.label == "TM_CommanderAura_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.C_CommanderAura_eff * (float)mightPowerSkill.level)); if (this.Pawn.health.hediffSet.HasHediff(TorannMagicDefOf.TM_CommanderAuraHD)) { return 0f; } } if (mightDef == TorannMagicDefOf.TM_StayAlert || mightDef == TorannMagicDefOf.TM_StayAlert_I || mightDef == TorannMagicDefOf.TM_StayAlert_II || mightDef == TorannMagicDefOf.TM_StayAlert_III) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_StayAlert.FirstOrDefault((MightPowerSkill x) => x.label == "TM_StayAlert_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.C_StayAlert_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_MoveOut || mightDef == TorannMagicDefOf.TM_MoveOut_I || mightDef == TorannMagicDefOf.TM_MoveOut_II || mightDef == TorannMagicDefOf.TM_MoveOut_III) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_MoveOut.FirstOrDefault((MightPowerSkill x) => x.label == "TM_MoveOut_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.C_MoveOut_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_HoldTheLine || mightDef == TorannMagicDefOf.TM_HoldTheLine_I || mightDef == TorannMagicDefOf.TM_HoldTheLine_II || mightDef == TorannMagicDefOf.TM_HoldTheLine_III) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_HoldTheLine.FirstOrDefault((MightPowerSkill x) => x.label == "TM_HoldTheLine_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.C_HoldTheLine_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_PistolWhip) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_PistolSpec.FirstOrDefault((MightPowerSkill x) => x.label == "TM_PistolSpec_ver"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.SS_PistolWhip_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_SuppressingFire) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_RifleSpec.FirstOrDefault((MightPowerSkill x) => x.label == "TM_RifleSpec_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.SS_SuppressingFire_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_Mk203GL) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_RifleSpec.FirstOrDefault((MightPowerSkill x) => x.label == "TM_RifleSpec_ver"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.SS_Mk203GL_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_Buckshot) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_ShotgunSpec.FirstOrDefault((MightPowerSkill x) => x.label == "TM_ShotgunSpec_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.SS_Buckshot_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_BreachingCharge) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_ShotgunSpec.FirstOrDefault((MightPowerSkill x) => x.label == "TM_ShotgunSpec_ver"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.SS_BreachingCharge_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_CQC) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_CQC.FirstOrDefault((MightPowerSkill x) => x.label == "TM_CQC_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.SS_CQC_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_FirstAid) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_FirstAid.FirstOrDefault((MightPowerSkill x) => x.label == "TM_FirstAid_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.SS_FirstAid_eff * (float)mightPowerSkill.level)); } if (mightDef == TorannMagicDefOf.TM_60mmMortar) { MightPowerSkill mightPowerSkill = this.MightData.MightPowerSkill_60mmMortar.FirstOrDefault((MightPowerSkill x) => x.label == "TM_60mmMortar_eff"); adjustedStaminaCost = mightDef.staminaCost - (mightDef.staminaCost * (this.SS_60mmMortar_eff * (float)mightPowerSkill.level)); } } if (this.spCost != 1f && mightDef != TorannMagicDefOf.TM_ProvisionerAura && mightDef != TorannMagicDefOf.TM_CommanderAura && mightDef != TorannMagicDefOf.TM_TaskMasterAura) { adjustedStaminaCost = adjustedStaminaCost * this.spCost; } MightPowerSkill globalSkill = this.MightData.MightPowerSkill_global_seff.FirstOrDefault((MightPowerSkill x) => x.label == "TM_global_seff_pwr"); if (globalSkill != null && mightDef != TorannMagicDefOf.TM_ProvisionerAura && mightDef != TorannMagicDefOf.TM_CommanderAura && mightDef != TorannMagicDefOf.TM_TaskMasterAura) { adjustedStaminaCost -= adjustedStaminaCost * (global_seff * globalSkill.level); } return Mathf.Max(adjustedStaminaCost, .5f * mightDef.staminaCost); } public override List<HediffDef> IgnoredHediffs() { return new List<HediffDef> { TorannMagicDefOf.TM_MagicUserHD }; } public override void PostPreApplyDamage(DamageInfo dinfo, out bool absorbed) { Pawn abilityUser = base.AbilityUser; absorbed = false; //bool flag = abilityUser.story.traits.HasTrait(TorannMagicDefOf.Gladiator) || abilityUser.story.traits.HasTrait; //if (isGladiator) //{ List<Hediff> list = new List<Hediff>(); List<Hediff> arg_32_0 = list; IEnumerable<Hediff> arg_32_1; if (abilityUser == null) { arg_32_1 = null; } else { Pawn_HealthTracker expr_1A = abilityUser.health; if (expr_1A == null) { arg_32_1 = null; } else { HediffSet expr_26 = expr_1A.hediffSet; arg_32_1 = (expr_26 != null) ? expr_26.hediffs : null; } } arg_32_0.AddRange(arg_32_1); Pawn expr_3E = abilityUser; int? arg_84_0; if (expr_3E == null) { arg_84_0 = null; } else { Pawn_HealthTracker expr_52 = expr_3E.health; if (expr_52 == null) { arg_84_0 = null; } else { HediffSet expr_66 = expr_52.hediffSet; arg_84_0 = (expr_66 != null) ? new int?(expr_66.hediffs.Count<Hediff>()) : null; } } bool flag = (arg_84_0 ?? 0) > 0; if (flag) { foreach (Hediff current in list) { if (current.def == TorannMagicDefOf.TM_HediffInvulnerable) { absorbed = true; MoteMaker.MakeStaticMote(AbilityUser.Position, AbilityUser.Map, ThingDefOf.Mote_ExplosionFlash, 10); dinfo.SetAmount(0); return; } if (current.def == TorannMagicDefOf.TM_PsionicHD) { if (dinfo.Def == TMDamageDefOf.DamageDefOf.TM_PsionicInjury) { absorbed = true; dinfo.SetAmount(0); return; } } if (current.def == TorannMagicDefOf.TM_ReversalHD) { Pawn instigator = dinfo.Instigator as Pawn; if (instigator != null) { if (instigator.equipment != null && instigator.equipment.PrimaryEq != null) { if (instigator.equipment.PrimaryEq.PrimaryVerb != null) { absorbed = true; Vector3 drawPos = AbilityUser.DrawPos; drawPos.x += ((instigator.DrawPos.x - drawPos.x) / 20f) + Rand.Range(-.2f, .2f); drawPos.z += ((instigator.DrawPos.z - drawPos.z) / 20f) + Rand.Range(-.2f, .2f); TM_MoteMaker.ThrowSparkFlashMote(drawPos, this.Pawn.Map, 2f); DoReversal(dinfo); dinfo.SetAmount(0); MightPowerSkill ver = this.MightData.MightPowerSkill_Reversal.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Reversal_ver"); if (ver.level > 0) { SiphonReversal(ver.level); } return; } } else if (instigator.RaceProps.Animal && dinfo.Amount != 0 && (instigator.Position - this.Pawn.Position).LengthHorizontal <= 2) { absorbed = true; Vector3 drawPos = AbilityUser.DrawPos; drawPos.x += ((instigator.DrawPos.x - drawPos.x) / 20f) + Rand.Range(-.2f, .2f); drawPos.z += ((instigator.DrawPos.z - drawPos.z) / 20f) + Rand.Range(-.2f, .2f); TM_MoteMaker.ThrowSparkFlashMote(drawPos, this.Pawn.Map, 2f); DoMeleeReversal(dinfo); dinfo.SetAmount(0); MightPowerSkill ver = this.MightData.MightPowerSkill_Reversal.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Reversal_ver"); if (ver.level > 0) { SiphonReversal(ver.level); } return; } } Building instigatorBldg = dinfo.Instigator as Building; if (instigatorBldg != null) { if (instigatorBldg.def.Verbs != null) { absorbed = true; Vector3 drawPos = AbilityUser.DrawPos; drawPos.x += ((instigatorBldg.DrawPos.x - drawPos.x) / 20f) + Rand.Range(-.2f, .2f); drawPos.z += ((instigatorBldg.DrawPos.z - drawPos.z) / 20f) + Rand.Range(-.2f, .2f); TM_MoteMaker.ThrowSparkFlashMote(drawPos, this.Pawn.Map, 2f); DoReversal(dinfo); dinfo.SetAmount(0); MightPowerSkill ver = this.MightData.MightPowerSkill_Reversal.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Reversal_ver"); if (ver.level > 0) { SiphonReversal(ver.level); } return; } } } if (current.def == TorannMagicDefOf.TM_HediffEnchantment_phantomShift && Rand.Chance(.2f)) { absorbed = true; MoteMaker.MakeStaticMote(AbilityUser.Position, AbilityUser.Map, ThingDefOf.Mote_ExplosionFlash, 8); MoteMaker.ThrowSmoke(abilityUser.Position.ToVector3Shifted(), abilityUser.Map, 1.2f); dinfo.SetAmount(0); return; } if (arcaneRes != 0 && resMitigationDelay < this.age) { if (current.def == TorannMagicDefOf.TM_HediffEnchantment_arcaneRes) { if ((dinfo.Def.armorCategory != null && (dinfo.Def.armorCategory == TorannMagicDefOf.Dark || dinfo.Def.armorCategory == TorannMagicDefOf.Light)) || dinfo.Def.defName.Contains("TM_") || dinfo.Def.defName == "FrostRay" || dinfo.Def.defName == "Snowball" || dinfo.Def.defName == "Iceshard" || dinfo.Def.defName == "Firebolt") { absorbed = true; int actualDmg = Mathf.RoundToInt(dinfo.Amount / arcaneRes); resMitigationDelay = this.age + 10; dinfo.SetAmount(actualDmg); abilityUser.TakeDamage(dinfo); return; } } } if (fortitudeMitigationDelay < this.age) { if (current.def == TorannMagicDefOf.TM_HediffFortitude) { MightPowerSkill pwr = this.MightData.MightPowerSkill_Fortitude.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Fortitude_pwr"); MightPowerSkill ver = this.MightData.MightPowerSkill_Fortitude.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Fortitude_ver"); absorbed = true; int mitigationAmt = 5 + pwr.level; ModOptions.SettingsRef settingsRef = new ModOptions.SettingsRef(); if (settingsRef.AIHardMode && !abilityUser.IsColonist) { mitigationAmt = 8; } float actualDmg; float dmgAmt = dinfo.Amount; this.Stamina.GainNeed((.01f * dmgAmt) + (.005f * (float)ver.level)); if (dmgAmt < mitigationAmt) { actualDmg = 0; return; } else { actualDmg = dmgAmt - mitigationAmt; } fortitudeMitigationDelay = this.age + 5; dinfo.SetAmount(actualDmg); abilityUser.TakeDamage(dinfo); return; } if (current.def == TorannMagicDefOf.TM_MindOverBodyHD) { MightPowerSkill ver = this.MightData.MightPowerSkill_MindOverBody.FirstOrDefault((MightPowerSkill x) => x.label == "TM_MindOverBody_ver"); absorbed = true; int mitigationAmt = Mathf.Clamp(7 + (2 * ver.level) - Mathf.RoundToInt(totalApparelWeight / 2), 0, 13); ModOptions.SettingsRef settingsRef = new ModOptions.SettingsRef(); if (settingsRef.AIHardMode && !abilityUser.IsColonist) { mitigationAmt = 10; } float actualDmg; float dmgAmt = dinfo.Amount; if (dmgAmt < mitigationAmt) { Vector3 drawPos = this.Pawn.DrawPos; Thing instigator = dinfo.Instigator; if (instigator != null && instigator.DrawPos != null) { float drawAngle = (instigator.DrawPos - drawPos).AngleFlat(); drawPos.x += Mathf.Clamp(((instigator.DrawPos.x - drawPos.x) / 5f) + Rand.Range(-.1f, .1f), -.45f, .45f); drawPos.z += Mathf.Clamp(((instigator.DrawPos.z - drawPos.z) / 5f) + Rand.Range(-.1f, .1f), -.45f, .45f); TM_MoteMaker.ThrowSparkFlashMote(drawPos, this.Pawn.Map, 1f); } actualDmg = 0; return; } else { actualDmg = dmgAmt - mitigationAmt; } fortitudeMitigationDelay = this.age + 6; dinfo.SetAmount(actualDmg); abilityUser.TakeDamage(dinfo); return; } } } } list = null; base.PostPreApplyDamage(dinfo, out absorbed); } public void DoMeleeReversal(DamageInfo dinfo) { TM_Action.DoMeleeReversal(dinfo, this.Pawn); } public void DoReversal(DamageInfo dinfo) { TM_Action.DoReversal(dinfo, this.Pawn); } public void SiphonReversal(int verVal) { Pawn pawn = this.Pawn; CompAbilityUserMight comp = pawn.GetComp<CompAbilityUserMight>(); comp.Stamina.CurLevel += .015f * verVal; int num = 1 + verVal; using (IEnumerator<BodyPartRecord> enumerator = pawn.health.hediffSet.GetInjuredParts().GetEnumerator()) { while (enumerator.MoveNext()) { BodyPartRecord rec = enumerator.Current; bool flag2 = num > 0; if (flag2) { int num2 = 1 + verVal; ModOptions.SettingsRef settingsRef = new ModOptions.SettingsRef(); if (!pawn.IsColonist && settingsRef.AIHardMode) { num2 = 5; } IEnumerable<Hediff_Injury> arg_BB_0 = pawn.health.hediffSet.GetHediffs<Hediff_Injury>(); Func<Hediff_Injury, bool> arg_BB_1; arg_BB_1 = (Hediff_Injury injury) => injury.Part == rec; foreach (Hediff_Injury current in arg_BB_0.Where(arg_BB_1)) { bool flag4 = num2 > 0; if (flag4) { bool flag5 = current.CanHealNaturally() && !current.IsPermanent(); if (flag5) { if (!pawn.IsColonist) { current.Heal(20.0f + ((float)verVal * 3f)); // power affects how much to heal } else { current.Heal(2.0f + ((float)verVal * 1f)); // power affects how much to heal } TM_MoteMaker.ThrowRegenMote(pawn.Position.ToVector3Shifted(), pawn.Map, .6f); TM_MoteMaker.ThrowRegenMote(pawn.Position.ToVector3Shifted(), pawn.Map, .4f); num--; num2--; } } } } } } } public void GiveReversalJob(DamageInfo dinfo) // buggy AF due to complications with CompDeflector { try { Pawn pawn; bool flag = (pawn = dinfo.Instigator as Pawn) != null && dinfo.Weapon != null; if (flag) { if (dinfo.Weapon.IsMeleeWeapon || dinfo.WeaponBodyPartGroup != null) { reversal_dinfo = new DamageInfo(dinfo.Def, dinfo.Amount, dinfo.ArmorPenetrationInt, dinfo.Angle - 180, this.Pawn, dinfo.HitPart, dinfo.Weapon, DamageInfo.SourceCategory.ThingOrUnknown); reversalTarget = dinfo.Instigator; } else { Job job = new Job(CompDeflectorDefOf.CastDeflectVerb) { playerForced = true, locomotionUrgency = LocomotionUrgency.Sprint }; bool flag2 = pawn.equipment != null; if (flag2) { CompEquippable primaryEq = pawn.equipment.PrimaryEq; bool flag3 = primaryEq != null; if (flag3) { bool flag4 = primaryEq.PrimaryVerb != null; if (flag4) { Verb_Deflected verb_Deflected = (Verb_Deflected)this.CopyAndReturnNewVerb(primaryEq.PrimaryVerb); //verb_Deflected = this.ReflectionHandler(verb_Deflected); //Log.Message("verb deflected with properties is " + verb_Deflected.ToString()); //throwing an error, so nothing is happening in jobdriver_castdeflectverb pawn = dinfo.Instigator as Pawn; job.targetA = pawn; job.verbToUse = verb_Deflected; job.killIncappedTarget = pawn.Downed; this.Pawn.jobs.TryTakeOrderedJob(job, JobTag.Misc); } } } } } } catch (NullReferenceException) { } } public Verb CopyAndReturnNewVerb(Verb newVerb = null) { if (newVerb != null) { deflectVerb = newVerb as Verb_Deflected; deflectVerb = (Verb_Deflected)Activator.CreateInstance(typeof(Verb_Deflected)); deflectVerb.caster = this.Pawn; //Initialize VerbProperties var newVerbProps = new VerbProperties { //Copy values over to a new verb props hasStandardCommand = newVerb.verbProps.hasStandardCommand, defaultProjectile = newVerb.verbProps.defaultProjectile, range = newVerb.verbProps.range, muzzleFlashScale = newVerb.verbProps.muzzleFlashScale, warmupTime = 0, defaultCooldownTime = 0, soundCast = SoundDefOf.MetalHitImportant, impactMote = newVerb.verbProps.impactMote, label = newVerb.verbProps.label, ticksBetweenBurstShots = 0, rangedFireRulepack = RulePackDef.Named("TM_Combat_Reflection"), accuracyLong = 70f * Rand.Range(1f, 2f), accuracyMedium = 80f * Rand.Range(1f, 2f), accuracyShort = 90f * Rand.Range(1f, 2f) }; //Apply values deflectVerb.verbProps = newVerbProps; } else { if (deflectVerb != null) return deflectVerb; deflectVerb = (Verb_Deflected)Activator.CreateInstance(typeof(Verb_Deflected)); deflectVerb.caster = this.Pawn; deflectVerb.verbProps = newVerb.verbProps; } return deflectVerb; } public Verb_Deflected ReflectionHandler(Verb_Deflected newVerb) { VerbProperties verbProperties = new VerbProperties { hasStandardCommand = newVerb.verbProps.hasStandardCommand, defaultProjectile = newVerb.verbProps.defaultProjectile, range = newVerb.verbProps.range, muzzleFlashScale = newVerb.verbProps.muzzleFlashScale, warmupTime = 0f, defaultCooldownTime = 0f, soundCast = SoundDefOf.MetalHitImportant, accuracyLong = 70f * Rand.Range(1f, 2f), accuracyMedium = 80f * Rand.Range(1f, 2f), accuracyShort = 90f * Rand.Range(1f, 2f) }; newVerb.verbProps = verbProperties; return newVerb; } public void ResolveReversalDamage() { reversalTarget.TakeDamage(reversal_dinfo); reversalTarget = null; } public void ResolveAutoCast() { ModOptions.SettingsRef settingsRef = new ModOptions.SettingsRef(); if (settingsRef.autocastEnabled && this.Pawn.jobs != null && this.Pawn.CurJob != null && this.Pawn.CurJob.def != TorannMagicDefOf.TMCastAbilityVerb && this.Pawn.CurJob.def != TorannMagicDefOf.TMCastAbilitySelf && this.Pawn.CurJob.def != JobDefOf.Ingest && this.Pawn.CurJob.def != JobDefOf.ManTurret && this.Pawn.GetPosture() == PawnPosture.Standing && !this.Pawn.CurJob.playerForced) { //Log.Message("pawn " + this.Pawn.LabelShort + " current job is " + this.Pawn.CurJob.def.defName); //non-combat (undrafted) spells bool castSuccess = false; bool isFaceless = this.mimicAbility != null; bool isCustom = this.customIndex >= 0; if (this.Pawn.drafter != null && !this.Pawn.Drafted && this.Stamina != null && this.Stamina.CurLevelPercentage >= settingsRef.autocastMinThreshold) { foreach (MightPower mp in this.MightData.MightPowersCustom) { if (mp.learned && mp.autocast && mp.autocasting != null && mp.autocasting.mightUser && mp.autocasting.undrafted) { //try //{ TMAbilityDef tmad = mp.TMabilityDefs[mp.level] as TMAbilityDef; // issues with index? bool canUseWithEquippedWeapon = true; bool canUseIfViolentAbility = this.Pawn.story.DisabledWorkTagsBackstoryAndTraits.HasFlag(WorkTags.Violent) ? !tmad.MainVerb.isViolent : true; if (tmad.requiredWeaponsOrCategories != null && tmad.IsRestrictedByEquipment(this.Pawn)) { continue; } if (canUseWithEquippedWeapon && canUseIfViolentAbility) { PawnAbility ability = this.AbilityData.Powers.FirstOrDefault((PawnAbility x) => x.Def == tmad); if (mp.autocasting.type == TMDefs.AutocastType.OnTarget && this.Pawn.CurJob.targetA != null && this.Pawn.CurJob.targetA.Thing != null) { LocalTargetInfo localTarget = TM_Calc.GetAutocastTarget(this.Pawn, mp.autocasting, this.Pawn.CurJob.targetA); if (localTarget.IsValid) { Thing targetThing = localTarget.Thing; if (!(targetThing.GetType() == mp.autocasting.GetTargetType)) { continue; } if (mp.autocasting.requiresLoS && !TM_Calc.HasLoSFromTo(this.Pawn.Position, targetThing, this.Pawn, mp.autocasting.minRange, ability.Def.MainVerb.range)) { continue; } if (mp.autocasting.maxRange != 0f && mp.autocasting.maxRange < (this.Pawn.Position - targetThing.Position).LengthHorizontal) { continue; } bool TE = mp.autocasting.targetEnemy && targetThing.Faction != null && targetThing.Faction.HostileTo(this.Pawn.Faction); if (TE && targetThing is Pawn) { Pawn targetPawn = targetThing as Pawn; if (targetPawn.Downed) { continue; } } bool TN = mp.autocasting.targetNeutral && (targetThing.Faction == null || !targetThing.Faction.HostileTo(this.Pawn.Faction)); bool TF = mp.autocasting.targetFriendly && targetThing.Faction == this.Pawn.Faction; if (!(TE || TN || TF)) { continue; } if (!mp.autocasting.ValidConditions(this.Pawn, targetThing)) { continue; } AutoCast.CombatAbility_OnTarget.TryExecute(this, tmad, ability, mp, targetThing, mp.autocasting.minRange, out castSuccess); } } if (mp.autocasting.type == TMDefs.AutocastType.OnSelf) { LocalTargetInfo localTarget = TM_Calc.GetAutocastTarget(this.Pawn, mp.autocasting, this.Pawn.CurJob.targetA); if (localTarget.IsValid) { Pawn targetThing = localTarget.Pawn; if (!(targetThing.GetType() == mp.autocasting.GetTargetType)) { continue; } if (!mp.autocasting.ValidConditions(this.Pawn, targetThing)) { continue; } AutoCast.CombatAbility_OnSelf.Evaluate(this, tmad, ability, mp, out castSuccess); } } if (mp.autocasting.type == TMDefs.AutocastType.OnCell && this.Pawn.CurJob.targetA != null) { LocalTargetInfo localTarget = TM_Calc.GetAutocastTarget(this.Pawn, mp.autocasting, this.Pawn.CurJob.targetA); if (localTarget.IsValid) { IntVec3 targetThing = localTarget.Cell; if (!(targetThing.GetType() == mp.autocasting.GetTargetType)) { continue; } if (mp.autocasting.requiresLoS && !TM_Calc.HasLoSFromTo(this.Pawn.Position, targetThing, this.Pawn, mp.autocasting.minRange, ability.Def.MainVerb.range)) { continue; } if (mp.autocasting.maxRange != 0f && mp.autocasting.maxRange < (this.Pawn.Position - targetThing).LengthHorizontal) { continue; } if (!mp.autocasting.ValidConditions(this.Pawn, targetThing)) { continue; } AutoCast.CombatAbility_OnCell.TryExecute(this, tmad, ability, mp, targetThing, mp.autocasting.minRange, out castSuccess); } } if (mp.autocasting.type == TMDefs.AutocastType.OnNearby) { LocalTargetInfo localTarget = TM_Calc.GetAutocastTarget(this.Pawn, mp.autocasting, this.Pawn.CurJob.targetA); if (localTarget.IsValid) { Thing targetThing = localTarget.Thing; if (!(targetThing.GetType() == mp.autocasting.GetTargetType)) { continue; } if (mp.autocasting.requiresLoS && !TM_Calc.HasLoSFromTo(this.Pawn.Position, targetThing, this.Pawn, mp.autocasting.minRange, ability.Def.MainVerb.range)) { continue; } if (mp.autocasting.maxRange != 0f && mp.autocasting.maxRange < (this.Pawn.Position - targetThing.Position).LengthHorizontal) { continue; } bool TE = mp.autocasting.targetEnemy && targetThing.Faction != null && targetThing.Faction.HostileTo(this.Pawn.Faction); if (TE && targetThing is Pawn) { Pawn targetPawn = targetThing as Pawn; if (targetPawn.Downed) { continue; } } bool TN = mp.autocasting.targetNeutral && (targetThing.Faction == null || !targetThing.Faction.HostileTo(this.Pawn.Faction)); bool TF = mp.autocasting.targetFriendly && targetThing.Faction == this.Pawn.Faction; if (!(TE || TN || TF)) { continue; } if (!mp.autocasting.ValidConditions(this.Pawn, targetThing)) { continue; } AutoCast.CombatAbility_OnTarget.TryExecute(this, tmad, ability, mp, targetThing, mp.autocasting.minRange, out castSuccess); } } if (castSuccess) goto AutoCastExit; } //} //catch //{ // Log.Message("no index found at " + mp.level + " for " + mp.abilityDef.defName); //} } } //Hunting only if (this.Pawn.CurJob.def == JobDefOf.Hunt && this.Pawn.CurJob.targetA != null && this.Pawn.CurJob.targetA.Thing != null && this.Pawn.CurJob.targetA.Thing is Pawn) { if ((this.Pawn.story.traits.HasTrait(TorannMagicDefOf.Ranger) || isFaceless || isCustom) && !this.Pawn.story.DisabledWorkTagsBackstoryAndTraits.HasFlag(WorkTags.Violent)) { PawnAbility ability = null; foreach (MightPower current in this.MightData.MightPowersR) { if (current.abilityDef != null && ((this.mimicAbility != null && this.mimicAbility.defName.Contains(current.abilityDef.defName)) || this.Pawn.story.traits.HasTrait(TorannMagicDefOf.Ranger))) { foreach (TMAbilityDef tmad in current.TMabilityDefs) { if (tmad == TorannMagicDefOf.TM_ArrowStorm || tmad == TorannMagicDefOf.TM_ArrowStorm_I || tmad == TorannMagicDefOf.TM_ArrowStorm_II || tmad == TorannMagicDefOf.TM_ArrowStorm_III) { if (this.Pawn.equipment.Primary != null && this.Pawn.equipment.Primary.def.IsRangedWeapon) { Thing wpn = this.Pawn.equipment.Primary; if (TM_Calc.IsUsingBow(this.Pawn)) { MightPower mightPower = this.MightData.MightPowersR.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == tmad); if (mightPower != null && mightPower.learned && mightPower.autocast) { ability = this.AbilityData.Powers.FirstOrDefault((PawnAbility x) => x.Def == tmad); AutoCast.CombatAbility_OnTarget_LoS.TryExecute(this, tmad, ability, mightPower, this.Pawn.CurJob.targetA, 4, out castSuccess); if (castSuccess) goto AutoCastExit; } } } } } } } } if ((this.Pawn.story.traits.HasTrait(TorannMagicDefOf.TM_SuperSoldier) || isFaceless || isCustom) && this.Pawn.story.DisabledWorkTagsBackstoryAndTraits != WorkTags.Violent) { PawnAbility ability = null; foreach (MightPower current in this.MightData.MightPowersSS) { if (current.abilityDef != null) { if (this.Pawn.equipment.Primary != null && this.Pawn.equipment.Primary.def.IsRangedWeapon) { if (this.specWpnRegNum != -1) { if (current.abilityDef == TorannMagicDefOf.TM_PistolWhip) { MightPower mightPower = this.MightData.MightPowersSS.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_PistolWhip); if (mightPower != null && mightPower.autocast) { ability = this.AbilityData.Powers.FirstOrDefault((PawnAbility x) => x.Def == TorannMagicDefOf.TM_PistolWhip); Pawn targetPawn = this.Pawn.TargetCurrentlyAimingAt.Thing as Pawn; if (targetPawn != null && this.Pawn.TargetCurrentlyAimingAt != this.Pawn) { AutoCast.MeleeCombat_OnTarget.TryExecute(this, TorannMagicDefOf.TM_PistolWhip, ability, mightPower, targetPawn, out castSuccess); if (castSuccess) goto AutoCastExit; } } } if (current.abilityDef == TorannMagicDefOf.TM_SuppressingFire) { MightPower mightPower = this.MightData.MightPowersSS.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_SuppressingFire); if (mightPower != null && mightPower.autocast) { ability = this.AbilityData.Powers.FirstOrDefault((PawnAbility x) => x.Def == TorannMagicDefOf.TM_SuppressingFire); Pawn targetPawn = this.Pawn.TargetCurrentlyAimingAt.Thing as Pawn; if (targetPawn != null) { AutoCast.CombatAbility_OnTarget_LoS.TryExecute(this, TorannMagicDefOf.TM_SuppressingFire, ability, mightPower, targetPawn, 1, out castSuccess); if (castSuccess) goto AutoCastExit; } } } if (current.abilityDef == TorannMagicDefOf.TM_Buckshot) { MightPower mightPower = this.MightData.MightPowersSS.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_Buckshot); if (mightPower != null && mightPower.autocast) { ability = this.AbilityData.Powers.FirstOrDefault((PawnAbility x) => x.Def == TorannMagicDefOf.TM_Buckshot); Pawn targetPawn = this.Pawn.TargetCurrentlyAimingAt.Thing as Pawn; if (targetPawn != null) { AutoCast.CombatAbility_OnTarget_LoS.TryExecute(this, TorannMagicDefOf.TM_Buckshot, ability, mightPower, targetPawn, 1, out castSuccess); if (castSuccess) goto AutoCastExit; } } } } } } } } if ((this.Pawn.story.traits.HasTrait(TorannMagicDefOf.TM_Sniper) || isFaceless || isCustom) && this.Pawn.story.DisabledWorkTagsBackstoryAndTraits != WorkTags.Violent) { PawnAbility ability = null; foreach (MightPower current in this.MightData.MightPowersS) { if (current.abilityDef != null && (current.abilityDef == this.mimicAbility || this.Pawn.story.traits.HasTrait(TorannMagicDefOf.TM_Sniper))) { if (this.Pawn.equipment.Primary != null && this.Pawn.equipment.Primary.def.IsRangedWeapon) { if (current.abilityDef == TorannMagicDefOf.TM_Headshot) { MightPower mightPower = this.MightData.MightPowersS.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_Headshot); if (mightPower != null && mightPower.autocast) { ability = this.AbilityData.Powers.FirstOrDefault((PawnAbility x) => x.Def == TorannMagicDefOf.TM_Headshot); AutoCast.CombatAbility_OnTarget_LoS.TryExecute(this, TorannMagicDefOf.TM_Headshot, ability, mightPower, this.Pawn.CurJob.targetA, 4, out castSuccess); if (castSuccess) goto AutoCastExit; } } } } } } if ((this.Pawn.story.traits.HasTrait(TorannMagicDefOf.DeathKnight) || isCustom) && this.Pawn.story.DisabledWorkTagsBackstoryAndTraits != WorkTags.Violent) { PawnAbility ability = null; foreach (MightPower current in this.MightData.MightPowersDK) { if (current.abilityDef != null && ((this.mimicAbility != null && this.mimicAbility.defName.Contains(current.abilityDef.defName)) || this.Pawn.story.traits.HasTrait(TorannMagicDefOf.DeathKnight))) { foreach (TMAbilityDef tmad in current.TMabilityDefs) { if (tmad == TorannMagicDefOf.TM_Spite || tmad == TorannMagicDefOf.TM_Spite_I || tmad == TorannMagicDefOf.TM_Spite_II || tmad == TorannMagicDefOf.TM_Spite_III) { if (this.Pawn.equipment.Primary != null && this.Pawn.equipment.Primary.def.IsRangedWeapon) { MightPower mightPower = this.MightData.MightPowersDK.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == tmad); if (mightPower != null && mightPower.learned && mightPower.autocast) { ability = this.AbilityData.Powers.FirstOrDefault((PawnAbility x) => x.Def == tmad); AutoCast.CombatAbility_OnTarget_LoS.TryExecute(this, tmad, ability, mightPower, this.Pawn.CurJob.targetA, 4, out castSuccess); if (castSuccess) goto AutoCastExit; } } } } } } } if (this.skill_ThrowingKnife && this.Pawn.story.DisabledWorkTagsBackstoryAndTraits != WorkTags.Violent) { MightPower mightPower = this.MightData.MightPowersStandalone.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_ThrowingKnife); if (mightPower != null && mightPower.autocast) { PawnAbility ability = this.AbilityData.Powers.FirstOrDefault((PawnAbility x) => x.Def == TorannMagicDefOf.TM_ThrowingKnife); AutoCast.CombatAbility_OnTarget_LoS.TryExecute(this, TorannMagicDefOf.TM_ThrowingKnife, ability, mightPower, this.Pawn.CurJob.targetA, 4, out castSuccess); if (castSuccess) goto AutoCastExit; } } if (this.skill_TempestStrike && this.Pawn.story.DisabledWorkTagsBackstoryAndTraits != WorkTags.Violent) { MightPower mightPower = this.MightData.MightPowersStandalone.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_TempestStrike); if (mightPower != null && mightPower.autocast) { PawnAbility ability = this.AbilityData.Powers.FirstOrDefault((PawnAbility x) => x.Def == TorannMagicDefOf.TM_TempestStrike); AutoCast.CombatAbility_OnTarget_LoS.TryExecute(this, TorannMagicDefOf.TM_TempestStrike, ability, mightPower, this.Pawn.CurJob.targetA, 4, out castSuccess); if (castSuccess) goto AutoCastExit; } } } if ((this.Pawn.story.traits.HasTrait(TorannMagicDefOf.Bladedancer) || isFaceless || isCustom) && this.Pawn.story.DisabledWorkTagsBackstoryAndTraits != WorkTags.Violent) { PawnAbility ability = null; foreach (MightPower current in this.MightData.MightPowersB) { if (current.abilityDef != null && ((this.mimicAbility != null && this.mimicAbility.defName.Contains(current.abilityDef.defName)) || this.Pawn.story.traits.HasTrait(TorannMagicDefOf.Bladedancer) || isCustom)) //current.abilityDef == this.mimicAbility || { foreach (TMAbilityDef tmad in current.TMabilityDefs) { if (tmad == TorannMagicDefOf.TM_PhaseStrike || tmad == TorannMagicDefOf.TM_PhaseStrike_I || tmad == TorannMagicDefOf.TM_PhaseStrike_II || tmad == TorannMagicDefOf.TM_PhaseStrike_III) { MightPower mightPower = this.MightData.MightPowersB.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == tmad); if (mightPower != null && mightPower.autocast && this.Pawn.equipment.Primary != null && !this.Pawn.equipment.Primary.def.IsRangedWeapon) { ability = this.AbilityData.Powers.FirstOrDefault((PawnAbility x) => x.Def == tmad); float minDistance = ActualStaminaCost(tmad) * 100; AutoCast.Phase.Evaluate(this, tmad, ability, mightPower, minDistance, out castSuccess); if (castSuccess) goto AutoCastExit; } } } } } } if (this.Pawn.story.traits.HasTrait(TorannMagicDefOf.TM_SuperSoldier) || isFaceless || isCustom) { PawnAbility ability = null; foreach (MightPower current in this.MightData.MightPowersSS) { if (current.abilityDef != null && (current.abilityDef == this.mimicAbility || this.Pawn.story.traits.HasTrait(TorannMagicDefOf.TM_SuperSoldier))) { if (current.abilityDef == TorannMagicDefOf.TM_FirstAid && TM_Calc.IsPawnInjured(this.Pawn, .2f)) { MightPower mightPower = this.MightData.MightPowersSS.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_FirstAid); if (mightPower != null && mightPower.autocast && !this.Pawn.CurJob.playerForced) { ability = this.AbilityData.Powers.FirstOrDefault((PawnAbility x) => x.Def == TorannMagicDefOf.TM_FirstAid); AutoCast.HealSelf.Evaluate(this, TorannMagicDefOf.TM_FirstAid, ability, mightPower, out castSuccess); if (castSuccess) goto AutoCastExit; } } } } } if (this.MightUserLevel >= 20) { MightPower mightPower = this.MightData.MightPowersStandalone.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_TeachMight); if (mightPower.autocast && !this.Pawn.CurJob.playerForced && mightPower.learned) { if (this.Pawn.CurJobDef.joyKind != null || this.Pawn.CurJobDef == JobDefOf.Wait_Wander || Pawn.CurJobDef == JobDefOf.GotoWander) { PawnAbility ability = this.AbilityData.Powers.FirstOrDefault((PawnAbility x) => x.Def == TorannMagicDefOf.TM_TeachMight); AutoCast.TeachMight.Evaluate(this, TorannMagicDefOf.TM_TeachMight, ability, mightPower, out castSuccess); if (castSuccess) goto AutoCastExit; } } } } //combat (drafted) spells if (this.Pawn.drafter != null && this.Pawn.Drafted && this.Pawn.drafter.FireAtWill && this.Stamina != null && (this.Stamina.CurLevelPercentage >= settingsRef.autocastCombatMinThreshold || this.Pawn.story.traits.HasTrait(TorannMagicDefOf.TM_Monk)) && this.Pawn.CurJob.def != JobDefOf.Goto && this.Pawn.CurJob.def != JobDefOf.AttackMelee) { foreach (MightPower mp in this.MightData.MightPowersCustom) { if (mp.learned && mp.autocast && mp.autocasting != null && mp.autocasting.mightUser && mp.autocasting.drafted) { //try //{ TMAbilityDef tmad = mp.TMabilityDefs[mp.level] as TMAbilityDef; // issues with index? bool canUseWithEquippedWeapon = true; bool canUseIfViolentAbility = this.Pawn.story.DisabledWorkTagsBackstoryAndTraits.HasFlag(WorkTags.Violent) ? !tmad.MainVerb.isViolent : true; if (tmad.requiredWeaponsOrCategories != null && tmad.IsRestrictedByEquipment(this.Pawn)) { continue; } if (canUseWithEquippedWeapon && canUseIfViolentAbility) { PawnAbility ability = this.AbilityData.Powers.FirstOrDefault((PawnAbility x) => x.Def == tmad); if (mp.autocasting.type == TMDefs.AutocastType.OnTarget && this.Pawn.TargetCurrentlyAimingAt != null && this.Pawn.TargetCurrentlyAimingAt.Thing != null) { LocalTargetInfo localTarget = TM_Calc.GetAutocastTarget(this.Pawn, mp.autocasting, this.Pawn.TargetCurrentlyAimingAt); if (localTarget.IsValid) { Thing targetThing = localTarget.Thing; if (!(targetThing.GetType() == mp.autocasting.GetTargetType)) { continue; } if (mp.autocasting.requiresLoS && !TM_Calc.HasLoSFromTo(this.Pawn.Position, targetThing, this.Pawn, mp.autocasting.minRange, ability.Def.MainVerb.range)) { continue; } if (mp.autocasting.maxRange != 0f && mp.autocasting.maxRange < (this.Pawn.Position - targetThing.Position).LengthHorizontal) { continue; } bool TE = mp.autocasting.targetEnemy && targetThing.Faction != null && targetThing.Faction.HostileTo(this.Pawn.Faction); if (TE && targetThing is Pawn) { Pawn targetPawn = targetThing as Pawn; if (targetPawn.Downed) { continue; } } bool TN = mp.autocasting.targetNeutral && (targetThing.Faction == null || !targetThing.Faction.HostileTo(this.Pawn.Faction)); bool TF = mp.autocasting.targetFriendly && targetThing.Faction == this.Pawn.Faction; if (!(TE || TN || TF)) { continue; } if (!mp.autocasting.ValidConditions(this.Pawn, targetThing)) { continue; } AutoCast.CombatAbility_OnTarget.TryExecute(this, tmad, ability, mp, targetThing, mp.autocasting.minRange, out castSuccess); } } if (mp.autocasting.type == TMDefs.AutocastType.OnSelf) { LocalTargetInfo localTarget = TM_Calc.GetAutocastTarget(this.Pawn, mp.autocasting, this.Pawn); if (localTarget.IsValid) { Pawn targetThing = localTarget.Pawn; if (!(targetThing.GetType() == mp.autocasting.GetTargetType)) { continue; } if (!mp.autocasting.ValidConditions(this.Pawn, targetThing)) { continue; } AutoCast.CombatAbility_OnSelf.Evaluate(this, tmad, ability, mp, out castSuccess); } } if (mp.autocasting.type == TMDefs.AutocastType.OnCell && this.Pawn.TargetCurrentlyAimingAt != null) { LocalTargetInfo localTarget = TM_Calc.GetAutocastTarget(this.Pawn, mp.autocasting, this.Pawn.TargetCurrentlyAimingAt); if (localTarget.IsValid) { IntVec3 targetThing = localTarget.Cell; if (!(targetThing.GetType() == mp.autocasting.GetTargetType)) { continue; } if (mp.autocasting.requiresLoS && !TM_Calc.HasLoSFromTo(this.Pawn.Position, targetThing, this.Pawn, mp.autocasting.minRange, ability.Def.MainVerb.range)) { continue; } if (mp.autocasting.maxRange != 0f && mp.autocasting.maxRange < (this.Pawn.Position - targetThing).LengthHorizontal) { continue; } if (!mp.autocasting.ValidConditions(this.Pawn, targetThing)) { continue; } AutoCast.CombatAbility_OnCell.TryExecute(this, tmad, ability, mp, targetThing, mp.autocasting.minRange, out castSuccess); } } if (mp.autocasting.type == TMDefs.AutocastType.OnNearby) { LocalTargetInfo localTarget = TM_Calc.GetAutocastTarget(this.Pawn, mp.autocasting, this.Pawn.TargetCurrentlyAimingAt); if (localTarget.IsValid) { Thing targetThing = localTarget.Thing; if (!(targetThing.GetType() == mp.autocasting.GetTargetType)) { continue; } if (mp.autocasting.requiresLoS && !TM_Calc.HasLoSFromTo(this.Pawn.Position, targetThing, this.Pawn, mp.autocasting.minRange, ability.Def.MainVerb.range)) { continue; } if (mp.autocasting.maxRange != 0f && mp.autocasting.maxRange < (this.Pawn.Position - targetThing.Position).LengthHorizontal) { continue; } bool TE = mp.autocasting.targetEnemy && targetThing.Faction != null && targetThing.Faction.HostileTo(this.Pawn.Faction); if (TE && targetThing is Pawn) { Pawn targetPawn = targetThing as Pawn; if (targetPawn.Downed) { continue; } } bool TN = mp.autocasting.targetNeutral && (targetThing.Faction == null || !targetThing.Faction.HostileTo(this.Pawn.Faction)); bool TF = mp.autocasting.targetFriendly && targetThing.Faction == this.Pawn.Faction; if (!(TE || TN || TF)) { continue; } if (!mp.autocasting.ValidConditions(this.Pawn, targetThing)) { continue; } AutoCast.CombatAbility_OnTarget.TryExecute(this, tmad, ability, mp, targetThing, mp.autocasting.minRange, out castSuccess); } } if (castSuccess) goto AutoCastExit; } //} //catch //{ // Log.Message("no index found at " + mp.level + " for " + mp.abilityDef.defName); //} } } if ((this.Pawn.story.traits.HasTrait(TorannMagicDefOf.Bladedancer) || isFaceless || isCustom) && this.Pawn.story.DisabledWorkTagsBackstoryAndTraits != WorkTags.Violent) { PawnAbility ability = null; foreach (MightPower current in this.MightData.MightPowersB) { if (current.abilityDef != null && (current.abilityDef == this.mimicAbility || this.Pawn.story.traits.HasTrait(TorannMagicDefOf.Bladedancer))) { if (current.abilityDef == TorannMagicDefOf.TM_BladeSpin) { MightPower mightPower = this.MightData.MightPowersB.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_BladeSpin); if (mightPower != null && mightPower.autocast && this.Pawn.equipment.Primary != null && !this.Pawn.equipment.Primary.def.IsRangedWeapon) { ability = this.AbilityData.Powers.FirstOrDefault((PawnAbility x) => x.Def == TorannMagicDefOf.TM_BladeSpin); MightPowerSkill ver = this.MightData.MightPowerSkill_BladeSpin.FirstOrDefault((MightPowerSkill x) => x.label == "TM_BladeSpin_ver"); AutoCast.AoECombat.Evaluate(this, TorannMagicDefOf.TM_BladeSpin, ability, mightPower, 2, Mathf.RoundToInt(2 + (.5f * ver.level)), this.Pawn.Position, true, out castSuccess); if (castSuccess) goto AutoCastExit; } } } } } if ((this.Pawn.story.traits.HasTrait(TorannMagicDefOf.TM_Monk) || isCustom) && this.Pawn.story.DisabledWorkTagsBackstoryAndTraits != WorkTags.Violent) { PawnAbility ability = null; foreach (MightPower current in this.MightData.MightPowersM) { if (current.abilityDef != null && (current.abilityDef == this.mimicAbility || this.Pawn.story.traits.HasTrait(TorannMagicDefOf.TM_Monk))) { if (current.abilityDef == TorannMagicDefOf.TM_TigerStrike) { MightPower mightPower = this.MightData.MightPowersM.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_TigerStrike); if (mightPower != null && mightPower.autocast && this.Pawn.equipment.Primary == null) { ability = this.AbilityData.Powers.FirstOrDefault((PawnAbility x) => x.Def == TorannMagicDefOf.TM_TigerStrike); AutoCast.MonkCombatAbility.EvaluateMinRange(this, TorannMagicDefOf.TM_TigerStrike, ability, mightPower, this.Pawn.TargetCurrentlyAimingAt, 1.48f, out castSuccess); if (castSuccess) goto AutoCastExit; } } if (current.abilityDef == TorannMagicDefOf.TM_ThunderStrike) { MightPower mightPower = this.MightData.MightPowersM.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_ThunderStrike); if (mightPower != null && mightPower.autocast) { ability = this.AbilityData.Powers.FirstOrDefault((PawnAbility x) => x.Def == TorannMagicDefOf.TM_ThunderStrike); AutoCast.MonkCombatAbility.EvaluateMinRange(this, TorannMagicDefOf.TM_ThunderStrike, ability, mightPower, this.Pawn.TargetCurrentlyAimingAt, 6f, out castSuccess); if (castSuccess) goto AutoCastExit; } } } } } if ((this.Pawn.story.traits.HasTrait(TorannMagicDefOf.Gladiator) || isFaceless || isCustom) && this.Pawn.story.DisabledWorkTagsBackstoryAndTraits != WorkTags.Violent) { PawnAbility ability = null; foreach (MightPower current in this.MightData.MightPowersG) { if (current.abilityDef != null && ((this.mimicAbility != null && this.mimicAbility.defName.Contains(current.abilityDef.defName)) || this.Pawn.story.traits.HasTrait(TorannMagicDefOf.Gladiator))) { foreach (TMAbilityDef tmad in current.TMabilityDefs) { if (tmad == TorannMagicDefOf.TM_Grapple || tmad == TorannMagicDefOf.TM_Grapple_I || tmad == TorannMagicDefOf.TM_Grapple_II || tmad == TorannMagicDefOf.TM_Grapple_III) { MightPower mightPower = this.MightData.MightPowersG.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == tmad); if (mightPower != null && mightPower.learned && mightPower.autocast) { ability = this.AbilityData.Powers.FirstOrDefault((PawnAbility x) => x.Def == tmad); AutoCast.CombatAbility.Evaluate(this, tmad, ability, mightPower, out castSuccess); if (castSuccess) goto AutoCastExit; } } } } } } if ((this.Pawn.story.traits.HasTrait(TorannMagicDefOf.Ranger) || isFaceless || isCustom) && this.Pawn.story.DisabledWorkTagsBackstoryAndTraits != WorkTags.Violent) { PawnAbility ability = null; foreach (MightPower current in this.MightData.MightPowersR) { if (current.abilityDef != null && ((this.mimicAbility != null && this.mimicAbility.defName.Contains(current.abilityDef.defName)) || this.Pawn.story.traits.HasTrait(TorannMagicDefOf.Ranger))) { foreach (TMAbilityDef tmad in current.TMabilityDefs) { if (tmad == TorannMagicDefOf.TM_ArrowStorm || tmad == TorannMagicDefOf.TM_ArrowStorm_I || tmad == TorannMagicDefOf.TM_ArrowStorm_II || tmad == TorannMagicDefOf.TM_ArrowStorm_III) { if (this.Pawn.equipment.Primary != null && this.Pawn.equipment.Primary.def.IsRangedWeapon) { Thing wpn = this.Pawn.equipment.Primary; if (TM_Calc.IsUsingBow(this.Pawn)) { MightPower mightPower = this.MightData.MightPowersR.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == tmad); if (mightPower != null && mightPower.learned && mightPower.autocast) { ability = this.AbilityData.Powers.FirstOrDefault((PawnAbility x) => x.Def == tmad); AutoCast.CombatAbility.Evaluate(this, tmad, ability, mightPower, out castSuccess); if (castSuccess) goto AutoCastExit; } } } } } } } } if ((this.Pawn.story.traits.HasTrait(TorannMagicDefOf.DeathKnight) || isCustom) && this.Pawn.story.DisabledWorkTagsBackstoryAndTraits != WorkTags.Violent) { PawnAbility ability = null; foreach (MightPower current in this.MightData.MightPowersDK) { if (current.abilityDef != null) { foreach (TMAbilityDef tmad in current.TMabilityDefs) { if (tmad == TorannMagicDefOf.TM_Spite || tmad == TorannMagicDefOf.TM_Spite_I || tmad == TorannMagicDefOf.TM_Spite_II || tmad == TorannMagicDefOf.TM_Spite_III) { MightPower mightPower = this.MightData.MightPowersDK.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == tmad); if (mightPower != null && mightPower.learned && mightPower.autocast) { ability = this.AbilityData.Powers.FirstOrDefault((PawnAbility x) => x.Def == tmad); AutoCast.CombatAbility.EvaluateMinRange(this, tmad, ability, mightPower, 4, out castSuccess); if (castSuccess) goto AutoCastExit; } } } } } } if ((this.Pawn.story.traits.HasTrait(TorannMagicDefOf.TM_Sniper) || isFaceless || isCustom) && this.Pawn.story.DisabledWorkTagsBackstoryAndTraits != WorkTags.Violent) { PawnAbility ability = null; foreach (MightPower current in this.MightData.MightPowersS) { if (current.abilityDef != null && ((this.mimicAbility != null && this.mimicAbility.defName.Contains(current.abilityDef.defName)) || this.Pawn.story.traits.HasTrait(TorannMagicDefOf.TM_Sniper))) { if (TM_Calc.IsUsingRanged(this.Pawn)) { foreach (TMAbilityDef tmad in current.TMabilityDefs) { if (tmad == TorannMagicDefOf.TM_AntiArmor) { MightPower mightPower = this.MightData.MightPowersS.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_AntiArmor); if (mightPower != null && mightPower.autocast) { ability = this.AbilityData.Powers.FirstOrDefault((PawnAbility x) => x.Def == TorannMagicDefOf.TM_AntiArmor); AutoCast.CombatAbility.Evaluate(this, TorannMagicDefOf.TM_AntiArmor, ability, mightPower, out castSuccess); if (castSuccess) goto AutoCastExit; } } if (tmad == TorannMagicDefOf.TM_Headshot) { MightPower mightPower = this.MightData.MightPowersS.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_Headshot); if (mightPower != null && mightPower.autocast) { ability = this.AbilityData.Powers.FirstOrDefault((PawnAbility x) => x.Def == TorannMagicDefOf.TM_Headshot); AutoCast.CombatAbility.Evaluate(this, TorannMagicDefOf.TM_Headshot, ability, mightPower, out castSuccess); if (castSuccess) goto AutoCastExit; } } if (tmad == TorannMagicDefOf.TM_DisablingShot || tmad == TorannMagicDefOf.TM_DisablingShot_I || tmad == TorannMagicDefOf.TM_DisablingShot_II || tmad == TorannMagicDefOf.TM_DisablingShot_III) { MightPower mightPower = this.MightData.MightPowersS.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == tmad); if (mightPower != null && mightPower.learned && mightPower.autocast) { ability = this.AbilityData.Powers.FirstOrDefault((PawnAbility x) => x.Def == tmad); AutoCast.CombatAbility.Evaluate(this, tmad, ability, mightPower, out castSuccess); if (castSuccess) goto AutoCastExit; } } } } } } } if (this.Pawn.story.traits.HasTrait(TorannMagicDefOf.TM_SuperSoldier) || isFaceless || isCustom) { PawnAbility ability = null; foreach (MightPower current in this.MightData.MightPowersSS) { if (current.abilityDef != null && (current.abilityDef == this.mimicAbility || this.Pawn.story.traits.HasTrait(TorannMagicDefOf.TM_SuperSoldier))) { if (current.abilityDef == TorannMagicDefOf.TM_FirstAid && TM_Calc.IsPawnInjured(this.Pawn, .2f)) { MightPower mightPower = this.MightData.MightPowersSS.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_FirstAid); if (mightPower != null && mightPower.autocast) { ability = this.AbilityData.Powers.FirstOrDefault((PawnAbility x) => x.Def == TorannMagicDefOf.TM_FirstAid); AutoCast.HealSelf.Evaluate(this, TorannMagicDefOf.TM_FirstAid, ability, mightPower, out castSuccess); if (castSuccess) goto AutoCastExit; } } } } if (this.Pawn.story.DisabledWorkTagsBackstoryAndTraits != WorkTags.Violent) { foreach (MightPower current in this.MightData.MightPowersSS) { if (current.abilityDef != null && this.Pawn.story.traits.HasTrait(TorannMagicDefOf.TM_SuperSoldier)) { if (this.Pawn.equipment.Primary != null && this.Pawn.equipment.Primary.def.IsRangedWeapon) { if (this.specWpnRegNum != -1) { if (current.abilityDef == TorannMagicDefOf.TM_PistolWhip) { MightPower mightPower = this.MightData.MightPowersSS.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_PistolWhip); if (mightPower != null && mightPower.autocast) { ability = this.AbilityData.Powers.FirstOrDefault((PawnAbility x) => x.Def == TorannMagicDefOf.TM_PistolWhip); Pawn targetPawn = this.Pawn.TargetCurrentlyAimingAt.Thing as Pawn; if (targetPawn != null) { AutoCast.MeleeCombat_OnTarget.TryExecute(this, TorannMagicDefOf.TM_PistolWhip, ability, mightPower, targetPawn, out castSuccess); if (castSuccess) goto AutoCastExit; } } } if (current.abilityDef == TorannMagicDefOf.TM_SuppressingFire) { MightPower mightPower = this.MightData.MightPowersSS.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_SuppressingFire); if (mightPower != null && mightPower.autocast) { ability = this.AbilityData.Powers.FirstOrDefault((PawnAbility x) => x.Def == TorannMagicDefOf.TM_SuppressingFire); Pawn targetPawn = this.Pawn.TargetCurrentlyAimingAt.Thing as Pawn; if (targetPawn != null) { AutoCast.CombatAbility_OnTarget_LoS.TryExecute(this, TorannMagicDefOf.TM_SuppressingFire, ability, mightPower, targetPawn, 6, out castSuccess); if (castSuccess) goto AutoCastExit; } } } if (current.abilityDef == TorannMagicDefOf.TM_Buckshot) { MightPower mightPower = this.MightData.MightPowersSS.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_Buckshot); if (mightPower != null && mightPower.autocast) { ability = this.AbilityData.Powers.FirstOrDefault((PawnAbility x) => x.Def == TorannMagicDefOf.TM_Buckshot); Pawn targetPawn = this.Pawn.TargetCurrentlyAimingAt.Thing as Pawn; if (targetPawn != null) { AutoCast.CombatAbility_OnTarget_LoS.TryExecute(this, TorannMagicDefOf.TM_Buckshot, ability, mightPower, targetPawn, 2, out castSuccess); if (castSuccess) goto AutoCastExit; } } } } } } } } } if (this.Pawn.story.DisabledWorkTagsBackstoryAndTraits != WorkTags.Violent) { MightPower mightPower = this.MightData.MightPowersStandalone.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_ThrowingKnife); if (mightPower != null && mightPower.learned && mightPower.autocast) { PawnAbility ability = this.AbilityData.Powers.FirstOrDefault((PawnAbility x) => x.Def == TorannMagicDefOf.TM_ThrowingKnife); Pawn targetPawn = TM_Calc.FindNearbyEnemy(this.Pawn, Mathf.RoundToInt(ability.Def.MainVerb.range * .9f)); AutoCast.CombatAbility_OnTarget_LoS.TryExecute(this, TorannMagicDefOf.TM_ThrowingKnife, ability, mightPower, targetPawn, 1, out castSuccess); if (castSuccess) goto AutoCastExit; } } if (this.Pawn.story.DisabledWorkTagsBackstoryAndTraits != WorkTags.Violent) { MightPower mightPower = this.MightData.MightPowersStandalone.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_TempestStrike); if (mightPower != null && mightPower.learned && mightPower.autocast) { PawnAbility ability = this.AbilityData.Powers.FirstOrDefault((PawnAbility x) => x.Def == TorannMagicDefOf.TM_TempestStrike); Pawn targetPawn = TM_Calc.FindNearbyEnemy(this.Pawn, Mathf.RoundToInt(ability.Def.MainVerb.range * .9f)); AutoCast.CombatAbility_OnTarget_LoS.TryExecute(this, TorannMagicDefOf.TM_TempestStrike, ability, mightPower, targetPawn, 4, out castSuccess); if (castSuccess) goto AutoCastExit; } } if (this.Pawn.story.DisabledWorkTagsBackstoryAndTraits != WorkTags.Violent) { MightPower mightPower = this.MightData.MightPowersStandalone.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_PommelStrike); if (mightPower != null && mightPower.learned && mightPower.autocast && this.Pawn.TargetCurrentlyAimingAt != null && this.Pawn.TargetCurrentlyAimingAt != this.Pawn) { PawnAbility ability = this.AbilityData.Powers.FirstOrDefault((PawnAbility x) => x.Def == TorannMagicDefOf.TM_PommelStrike); Pawn targetPawn = this.Pawn.TargetCurrentlyAimingAt.Thing as Pawn; float minPain = .3f; if (this.MightData.MightPowerSkill_FieldTraining.FirstOrDefault((MightPowerSkill x) => x.label == "TM_FieldTraining_pwr").level >= 2) { minPain = .2f; } if (targetPawn != null && targetPawn.health?.hediffSet?.PainTotal >= minPain) { AutoCast.MeleeCombat_OnTarget.TryExecute(this, TorannMagicDefOf.TM_PommelStrike, ability, mightPower, targetPawn, out castSuccess); if (castSuccess) goto AutoCastExit; } } } } AutoCastExit:; } } public void ResolveAIAutoCast() { ModOptions.SettingsRef settingsRef = new ModOptions.SettingsRef(); if (settingsRef.autocastEnabled && this.Pawn.jobs != null && this.Pawn.CurJob != null && this.Pawn.CurJob.def != TorannMagicDefOf.TMCastAbilityVerb && this.Pawn.CurJob.def != TorannMagicDefOf.TMCastAbilitySelf && this.Pawn.CurJob.def != JobDefOf.Ingest && this.Pawn.CurJob.def != JobDefOf.ManTurret && this.Pawn.GetPosture() == PawnPosture.Standing) { //Log.Message("pawn " + this.Pawn.LabelShort + " current job is " + this.Pawn.CurJob.def.defName); bool castSuccess = false; if (this.Stamina != null && this.Stamina.CurLevelPercentage >= settingsRef.autocastMinThreshold) { foreach (MightPower mp in this.MightData.MightPowersCustom) { if (mp.learned && mp.autocasting != null && mp.autocasting.mightUser && mp.autocasting.AIUsable) { //try //{ TMAbilityDef tmad = mp.TMabilityDefs[mp.level] as TMAbilityDef; // issues with index? bool canUseWithEquippedWeapon = true; bool canUseIfViolentAbility = this.Pawn.story.DisabledWorkTagsBackstoryAndTraits.HasFlag(WorkTags.Violent) ? !tmad.MainVerb.isViolent : true; if (tmad.requiredWeaponsOrCategories != null && tmad.IsRestrictedByEquipment(this.Pawn)) { continue; } if (canUseWithEquippedWeapon && canUseIfViolentAbility) { PawnAbility ability = this.AbilityData.Powers.FirstOrDefault((PawnAbility x) => x.Def == tmad); if (mp.autocasting.type == TMDefs.AutocastType.OnTarget && this.Pawn.TargetCurrentlyAimingAt != null) { LocalTargetInfo localTarget = TM_Calc.GetAutocastTarget(this.Pawn, mp.autocasting, this.Pawn.TargetCurrentlyAimingAt); if (localTarget.IsValid) { Thing targetThing = localTarget.Thing; if (!(targetThing.GetType() == mp.autocasting.GetTargetType)) { continue; } if (mp.autocasting.requiresLoS && !TM_Calc.HasLoSFromTo(this.Pawn.Position, targetThing, this.Pawn, mp.autocasting.minRange, ability.Def.MainVerb.range)) { continue; } if (mp.autocasting.maxRange != 0f && mp.autocasting.maxRange < (this.Pawn.Position - targetThing.Position).LengthHorizontal) { continue; } bool TE = mp.autocasting.targetEnemy && targetThing.Faction != null && targetThing.Faction.HostileTo(this.Pawn.Faction); if (TE && targetThing is Pawn) { Pawn targetPawn = targetThing as Pawn; if (targetPawn.Downed) { continue; } } bool TN = mp.autocasting.targetNeutral && (targetThing.Faction == null || !targetThing.Faction.HostileTo(this.Pawn.Faction)); bool TF = mp.autocasting.targetFriendly && targetThing.Faction == this.Pawn.Faction; if (!(TE || TN || TF)) { continue; } if (targetThing is Pawn) { Pawn targetPawn = targetThing as Pawn; if (targetPawn.IsPrisoner) { continue; } } if (!mp.autocasting.ValidConditions(this.Pawn, targetThing)) { continue; } AutoCast.CombatAbility_OnTarget.TryExecute(this, tmad, ability, mp, targetThing, mp.autocasting.minRange, out castSuccess); } } if (mp.autocasting.type == TMDefs.AutocastType.OnSelf) { LocalTargetInfo localTarget = TM_Calc.GetAutocastTarget(this.Pawn, mp.autocasting, this.Pawn.TargetCurrentlyAimingAt); if (localTarget.IsValid) { Pawn targetThing = localTarget.Pawn; if (!(targetThing.GetType() == mp.autocasting.GetTargetType)) { continue; } if (!mp.autocasting.ValidConditions(this.Pawn, targetThing)) { continue; } AutoCast.CombatAbility_OnSelf.Evaluate(this, tmad, ability, mp, out castSuccess); } } if (mp.autocasting.type == TMDefs.AutocastType.OnCell && this.Pawn.CurJob.targetA != null) { LocalTargetInfo localTarget = TM_Calc.GetAutocastTarget(this.Pawn, mp.autocasting, this.Pawn.TargetCurrentlyAimingAt); if (localTarget.IsValid) { IntVec3 targetThing = localTarget.Cell; if (!(targetThing.GetType() == mp.autocasting.GetTargetType)) { continue; } if (mp.autocasting.requiresLoS && !TM_Calc.HasLoSFromTo(this.Pawn.Position, targetThing, this.Pawn, mp.autocasting.minRange, ability.Def.MainVerb.range)) { continue; } if (mp.autocasting.maxRange != 0f && mp.autocasting.maxRange < (this.Pawn.Position - targetThing).LengthHorizontal) { continue; } if (!mp.autocasting.ValidConditions(this.Pawn, targetThing)) { continue; } AutoCast.CombatAbility_OnCell.TryExecute(this, tmad, ability, mp, targetThing, mp.autocasting.minRange, out castSuccess); } } if (mp.autocasting.type == TMDefs.AutocastType.OnNearby) { LocalTargetInfo localTarget = TM_Calc.GetAutocastTarget(this.Pawn, mp.autocasting, this.Pawn.TargetCurrentlyAimingAt); if (localTarget.IsValid) { Thing targetThing = localTarget.Thing; if (!(targetThing.GetType() == mp.autocasting.GetTargetType)) { continue; } if (mp.autocasting.requiresLoS && !TM_Calc.HasLoSFromTo(this.Pawn.Position, targetThing, this.Pawn, mp.autocasting.minRange, ability.Def.MainVerb.range)) { continue; } if (mp.autocasting.maxRange != 0f && mp.autocasting.maxRange < (this.Pawn.Position - targetThing.Position).LengthHorizontal) { continue; } bool TE = mp.autocasting.targetEnemy && targetThing.Faction != null && targetThing.Faction.HostileTo(this.Pawn.Faction); if (TE && targetThing is Pawn) { Pawn targetPawn = targetThing as Pawn; if (targetPawn.Downed) { continue; } } bool TN = mp.autocasting.targetNeutral && (targetThing.Faction == null || !targetThing.Faction.HostileTo(this.Pawn.Faction)); bool TF = mp.autocasting.targetFriendly && targetThing.Faction == this.Pawn.Faction; if (!(TE || TN || TF)) { continue; } if (targetThing is Pawn) { Pawn targetPawn = targetThing as Pawn; if (targetPawn.IsPrisoner) { continue; } } if (!mp.autocasting.ValidConditions(this.Pawn, targetThing)) { continue; } AutoCast.CombatAbility_OnTarget.TryExecute(this, tmad, ability, mp, targetThing, mp.autocasting.minRange, out castSuccess); } } } //} //catch //{ // Log.Message("no index found at " + mp.level + " for " + mp.abilityDef.defName); //} } if (castSuccess) goto AIAutoCastExit; } AIAutoCastExit:; } } } public void ResolveClassSkills() { if (this.MightUserLevel >= 20 && (this.skill_Teach == false || !this.MightData.MightPowersStandalone.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_TeachMight).learned)) { this.MightData.MightPowersStandalone.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_TeachMight).learned = true; this.AddPawnAbility(TorannMagicDefOf.TM_TeachMight); this.skill_Teach = true; } if (this.customClass != null && this.customClass.classHediff != null && !this.Pawn.health.hediffSet.HasHediff(this.customClass.classHediff)) { HealthUtility.AdjustSeverity(this.Pawn, this.customClass.classHediff, this.customClass.hediffSeverity); } if (this.IsMightUser && !this.Pawn.Dead && !this.Pawn.Downed) { if (this.Pawn.story.traits.HasTrait(TorannMagicDefOf.Bladedancer)) { MightPowerSkill bladefocus_pwr = this.Pawn.GetComp<CompAbilityUserMight>().MightData.MightPowerSkill_BladeFocus.FirstOrDefault((MightPowerSkill x) => x.label == "TM_BladeFocus_pwr"); List<Trait> traits = this.Pawn.story.traits.allTraits; for (int i = 0; i < traits.Count; i++) { if (traits[i].def.defName == "Bladedancer") { if (traits[i].Degree != bladefocus_pwr.level) { traits.Remove(traits[i]); this.Pawn.story.traits.GainTrait(new Trait(TraitDef.Named("Bladedancer"), bladefocus_pwr.level, false)); MoteMaker.ThrowHeatGlow(this.Pawn.Position, this.Pawn.Map, 2); } } } } if (this.Pawn.story.traits.HasTrait(TorannMagicDefOf.Gladiator) || (this.customClass != null && this.customClass.classFighterAbilities.Contains(TorannMagicDefOf.TM_Fortitude))) { if (!this.Pawn.health.hediffSet.HasHediff(TorannMagicDefOf.TM_HediffFortitude)) { HealthUtility.AdjustSeverity(this.Pawn, TorannMagicDefOf.TM_HediffFortitude, -5f); HealthUtility.AdjustSeverity(this.Pawn, TorannMagicDefOf.TM_HediffFortitude, 1f); } } if (this.Pawn.health.hediffSet.HasHediff(TorannMagicDefOf.TM_HediffSprint)) { Hediff rec = this.Pawn.health.hediffSet.GetFirstHediffOfDef(TorannMagicDefOf.TM_HediffSprint, false); if (rec != null && rec.Severity != (.5f + this.MightData.MightPowerSkill_Sprint.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Sprint_pwr").level)) { this.Pawn.health.RemoveHediff(rec); HealthUtility.AdjustSeverity(this.Pawn, TorannMagicDefOf.TM_HediffSprint, .5f + this.MightData.MightPowerSkill_Sprint.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Sprint_pwr").level); } } if (this.Pawn.story.traits.HasTrait(TorannMagicDefOf.Ranger)) { MightPowerSkill rangertraining_pwr = this.MightData.MightPowerSkill_RangerTraining.FirstOrDefault((MightPowerSkill x) => x.label == "TM_RangerTraining_pwr"); List<Trait> traits = this.Pawn.story.traits.allTraits; for (int i = 0; i < traits.Count; i++) { if (traits[i].def == TorannMagicDefOf.Ranger) { if (traits[i].Degree != rangertraining_pwr.level) { traits.Remove(traits[i]); this.Pawn.story.traits.GainTrait(new Trait(TraitDef.Named("Ranger"), rangertraining_pwr.level, false)); MoteMaker.ThrowHeatGlow(this.Pawn.Position, this.Pawn.Map, 2); } } } } if (this.Pawn.story.traits.HasTrait(TorannMagicDefOf.TM_Sniper)) { MightPowerSkill sniperfocus_pwr = this.Pawn.GetComp<CompAbilityUserMight>().MightData.MightPowerSkill_SniperFocus.FirstOrDefault((MightPowerSkill x) => x.label == "TM_SniperFocus_pwr"); List<Trait> traits = this.Pawn.story.traits.allTraits; for (int i = 0; i < traits.Count; i++) { if (traits[i].def.defName == "TM_Sniper") { if (traits[i].Degree != sniperfocus_pwr.level) { traits.Remove(traits[i]); this.Pawn.story.traits.GainTrait(new Trait(TorannMagicDefOf.TM_Sniper, sniperfocus_pwr.level, false)); MoteMaker.ThrowHeatGlow(base.Pawn.Position, this.Pawn.Map, 2); } } } } if (this.Pawn.story.traits.HasTrait(TorannMagicDefOf.TM_Psionic) || TM_ClassUtility.ClassHasAbility(TorannMagicDefOf.TM_PsionicAugmentation)) { if (!this.Pawn.health.hediffSet.HasHediff(HediffDef.Named("TM_PsionicHD"), false)) { HealthUtility.AdjustSeverity(this.Pawn, HediffDef.Named("TM_PsionicHD"), 1f); } } ModOptions.SettingsRef settingsRef = new ModOptions.SettingsRef(); if ((this.Pawn.story.traits.HasTrait(TorannMagicDefOf.Bladedancer) || (this.customClass != null && this.customClass.classFighterAbilities.Contains(TorannMagicDefOf.TM_BladeArt))) && !this.Pawn.health.hediffSet.HasHediff(TorannMagicDefOf.TM_BladeArtHD)) { MightPowerSkill bladeart_pwr = this.Pawn.GetComp<CompAbilityUserMight>().MightData.MightPowerSkill_BladeArt.FirstOrDefault((MightPowerSkill x) => x.label == "TM_BladeArt_pwr"); //HealthUtility.AdjustSeverity(this.Pawn, TorannMagicDefOf.TM_BladeArtHD, -5f); HealthUtility.AdjustSeverity(this.Pawn, TorannMagicDefOf.TM_BladeArtHD, .5f + bladeart_pwr.level); if (!this.Pawn.IsColonist && settingsRef.AIHardMode) { HealthUtility.AdjustSeverity(this.Pawn, TorannMagicDefOf.TM_BladeArtHD, 4); } } if ((this.Pawn.story.traits.HasTrait(TorannMagicDefOf.Ranger) || (this.customClass != null && this.customClass.classFighterAbilities.Contains(TorannMagicDefOf.TM_BowTraining))) && !this.Pawn.health.hediffSet.HasHediff(TorannMagicDefOf.TM_BowTrainingHD)) { MightPowerSkill bowtraining_pwr = this.Pawn.GetComp<CompAbilityUserMight>().MightData.MightPowerSkill_BowTraining.FirstOrDefault((MightPowerSkill x) => x.label == "TM_BowTraining_pwr"); //HealthUtility.AdjustSeverity(this.Pawn, TorannMagicDefOf.TM_BowTrainingHD, -5f); HealthUtility.AdjustSeverity(this.Pawn, TorannMagicDefOf.TM_BowTrainingHD, .5f + bowtraining_pwr.level); if (!this.Pawn.IsColonist && settingsRef.AIHardMode) { HealthUtility.AdjustSeverity(this.Pawn, TorannMagicDefOf.TM_BowTrainingHD, 4); } } using (IEnumerator<Hediff> enumerator = this.Pawn.health.hediffSet.GetHediffs<Hediff>().GetEnumerator()) { while (enumerator.MoveNext()) { Hediff rec = enumerator.Current; if (rec.def == TorannMagicDefOf.TM_BladeArtHD && this.Pawn.IsColonist) { MightPowerSkill bladeart_pwr = this.Pawn.GetComp<CompAbilityUserMight>().MightData.MightPowerSkill_BladeArt.FirstOrDefault((MightPowerSkill x) => x.label == "TM_BladeArt_pwr"); if (rec.Severity < (float)(.5f + bladeart_pwr.level) || rec.Severity > (float)(.6f + bladeart_pwr.level)) { HealthUtility.AdjustSeverity(this.Pawn, TorannMagicDefOf.TM_BladeArtHD, -5f); HealthUtility.AdjustSeverity(this.Pawn, TorannMagicDefOf.TM_BladeArtHD, .5f + bladeart_pwr.level); MoteMaker.ThrowDustPuff(this.Pawn.Position.ToVector3Shifted(), this.Pawn.Map, .6f); MoteMaker.ThrowHeatGlow(this.Pawn.Position, this.Pawn.Map, 1.6f); } } if (rec.def == TorannMagicDefOf.TM_BowTrainingHD && this.Pawn.IsColonist) { MightPowerSkill bowtraining_pwr = this.Pawn.GetComp<CompAbilityUserMight>().MightData.MightPowerSkill_BowTraining.FirstOrDefault((MightPowerSkill x) => x.label == "TM_BowTraining_pwr"); if (rec.Severity < (float)(.5f + bowtraining_pwr.level) || rec.Severity > (float)(.6f + bowtraining_pwr.level)) { HealthUtility.AdjustSeverity(this.Pawn, TorannMagicDefOf.TM_BowTrainingHD, -5f); HealthUtility.AdjustSeverity(this.Pawn, TorannMagicDefOf.TM_BowTrainingHD, .5f + bowtraining_pwr.level); MoteMaker.ThrowDustPuff(this.Pawn.Position.ToVector3Shifted(), this.Pawn.Map, .6f); MoteMaker.ThrowHeatGlow(this.Pawn.Position, this.Pawn.Map, 1.6f); } } } } if (this.Pawn.story.traits.HasTrait(TorannMagicDefOf.DeathKnight) || (this.customClass != null && (this.customClass.classFighterAbilities.Contains(TorannMagicDefOf.TM_Shroud) || this.customClass.classHediff == TorannMagicDefOf.TM_HateHD))) { int hatePwr = this.MightData.MightPowerSkill_Shroud.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Shroud_pwr").level; float sevSvr = 0; Hediff hediff = null; for (int h = 0; h < this.Pawn.health.hediffSet.hediffs.Count; h++) { if (this.Pawn.health.hediffSet.hediffs[h].def.defName.Contains("TM_HateH")) { hediff = this.Pawn.health.hediffSet.hediffs[h]; } } if (hediff != null) { sevSvr = hediff.Severity; if (hatePwr == 5 && hediff.def.defName != "TM_HateHD_V") { this.Pawn.health.RemoveHediff(hediff); HealthUtility.AdjustSeverity(this.Pawn, HediffDef.Named("TM_HateHD_V"), sevSvr); } else if (hatePwr == 4 && hediff.def.defName != "TM_HateHD_IV") { this.Pawn.health.RemoveHediff(hediff); HealthUtility.AdjustSeverity(this.Pawn, HediffDef.Named("TM_HateHD_IV"), sevSvr); } else if (hatePwr == 3 && hediff.def.defName != "TM_HateHD_III") { this.Pawn.health.RemoveHediff(hediff); HealthUtility.AdjustSeverity(this.Pawn, HediffDef.Named("TM_HateHD_III"), sevSvr); } else if (hatePwr == 2 && hediff.def.defName != "TM_HateHD_II") { this.Pawn.health.RemoveHediff(hediff); HealthUtility.AdjustSeverity(this.Pawn, HediffDef.Named("TM_HateHD_II"), sevSvr); } else if (hatePwr == 1 && hediff.def.defName != "TM_HateHD_I") { this.Pawn.health.RemoveHediff(hediff); HealthUtility.AdjustSeverity(this.Pawn, HediffDef.Named("TM_HateHD_I"), sevSvr); } else if (hatePwr == 0 && hediff.def.defName != "TM_HateHD") { this.Pawn.health.RemoveHediff(hediff); HealthUtility.AdjustSeverity(this.Pawn, HediffDef.Named("TM_HateHD"), sevSvr); } } if (!TM_Calc.HasHateHediff(this.Pawn)) { HealthUtility.AdjustSeverity(this.Pawn, HediffDef.Named("TM_HateHD"), 1); } } if (this.Pawn.story.traits.HasTrait(TorannMagicDefOf.TM_Monk) || (this.customClass != null && (this.customClass.classHediff == TorannMagicDefOf.TM_ChiHD || this.customClass.classFighterAbilities.Contains(TorannMagicDefOf.TM_Chi)))) { if (!this.Pawn.health.hediffSet.HasHediff(TorannMagicDefOf.TM_ChiHD, false)) { HealthUtility.AdjustSeverity(this.Pawn, TorannMagicDefOf.TM_ChiHD, 1f); } } if (this.Pawn.story.traits.HasTrait(TorannMagicDefOf.TM_Monk) || (this.customClass != null && this.customClass.classFighterAbilities.Contains(TorannMagicDefOf.TM_MindOverBody))) { if (!this.Pawn.health.hediffSet.HasHediff(TorannMagicDefOf.TM_MindOverBodyHD, false)) { HealthUtility.AdjustSeverity(this.Pawn, TorannMagicDefOf.TM_MindOverBodyHD, .5f); } else { Hediff mob = this.Pawn.health.hediffSet.GetFirstHediffOfDef(TorannMagicDefOf.TM_MindOverBodyHD, false); int mobPwr = this.MightData.MightPowerSkill_MindOverBody.FirstOrDefault((MightPowerSkill x) => x.label == "TM_MindOverBody_pwr").level; if (mobPwr == 3 && mob.Severity < 3) { this.Pawn.health.RemoveHediff(mob); HealthUtility.AdjustSeverity(this.Pawn, TorannMagicDefOf.TM_MindOverBodyHD, 3.5f); } else if (mobPwr == 2 && mob.Severity < 2) { this.Pawn.health.RemoveHediff(mob); HealthUtility.AdjustSeverity(this.Pawn, TorannMagicDefOf.TM_MindOverBodyHD, 2.5f); } else if (mobPwr == 1 && mob.Severity < 1) { this.Pawn.health.RemoveHediff(mob); HealthUtility.AdjustSeverity(this.Pawn, TorannMagicDefOf.TM_MindOverBodyHD, 1.5f); } else if (mobPwr == 0 && mob.Severity >= 1) { this.Pawn.health.RemoveHediff(mob); HealthUtility.AdjustSeverity(this.Pawn, TorannMagicDefOf.TM_MindOverBodyHD, .5f); } } } if (this.Pawn.story.traits.HasTrait(TorannMagicDefOf.TM_Wayfarer) || (this.customClass != null && this.customClass.classFighterAbilities.Contains(TorannMagicDefOf.TM_FieldTraining))) { int pwrVal = this.MightData.MightPowerSkill_FieldTraining.FirstOrDefault((MightPowerSkill x) => x.label == "TM_FieldTraining_pwr").level; int verVal = this.MightData.MightPowerSkill_FieldTraining.FirstOrDefault((MightPowerSkill x) => x.label == "TM_FieldTraining_ver").level; using (IEnumerator<Hediff> enumerator = this.Pawn.health.hediffSet.GetHediffs<Hediff>().GetEnumerator()) { while (enumerator.MoveNext()) { Hediff rec = enumerator.Current; if (rec.def == TorannMagicDefOf.TM_HediffHeavyBlow && rec.Severity != (.95f + (.19f * pwrVal))) { this.Pawn.health.RemoveHediff(rec); HealthUtility.AdjustSeverity(this.Pawn, TorannMagicDefOf.TM_HediffHeavyBlow, .95f + (.19f * pwrVal)); } if (rec.def == TorannMagicDefOf.TM_HediffStrongBack) { if (verVal >= 8) { if (rec.Severity != 2.5f) { this.Pawn.health.RemoveHediff(rec); HealthUtility.AdjustSeverity(this.Pawn, TorannMagicDefOf.TM_HediffStrongBack, 2.5f); } } else if (verVal >= 3) { if (rec.Severity != 1.5f) { this.Pawn.health.RemoveHediff(rec); HealthUtility.AdjustSeverity(this.Pawn, TorannMagicDefOf.TM_HediffStrongBack, 1.5f); } } } if (rec.def == TorannMagicDefOf.TM_HediffThickSkin) { if (verVal >= 12) { if (rec.Severity != 3.5f) { this.Pawn.health.RemoveHediff(rec); HealthUtility.AdjustSeverity(this.Pawn, TorannMagicDefOf.TM_HediffThickSkin, 3.5f); } } else if (verVal >= 7) { if (rec.Severity != 2.5f) { this.Pawn.health.RemoveHediff(rec); HealthUtility.AdjustSeverity(this.Pawn, TorannMagicDefOf.TM_HediffThickSkin, 2.5f); } } else if (verVal >= 2) { if (rec.Severity != 1.5f) { this.Pawn.health.RemoveHediff(rec); HealthUtility.AdjustSeverity(this.Pawn, TorannMagicDefOf.TM_HediffThickSkin, 1.5f); } } } if (rec.def == TorannMagicDefOf.TM_HediffFightersFocus) { if (verVal >= 1) { if (rec.Severity != 1.5f) { this.Pawn.health.RemoveHediff(rec); HealthUtility.AdjustSeverity(this.Pawn, TorannMagicDefOf.TM_HediffFightersFocus, 1.5f); } } } if (rec.def == TorannMagicDefOf.TM_HediffSprint) { if (rec.Severity != (.5f + (int)(pwrVal / 3))) { this.Pawn.health.RemoveHediff(rec); HealthUtility.AdjustSeverity(this.Pawn, TorannMagicDefOf.TM_HediffSprint, .5f + (int)(pwrVal / 3)); } } } } if (verVal >= 6 && !this.skill_Legion) { this.skill_Legion = true; this.AddPawnAbility(TorannMagicDefOf.TM_Legion); } } if (this.Pawn.story.traits.HasTrait(TorannMagicDefOf.TM_SuperSoldier) || (this.customClass != null && this.customClass.classHediff == TorannMagicDefOf.TM_SS_SerumHD)) { if (!this.Pawn.health.hediffSet.HasHediff(TorannMagicDefOf.TM_SS_SerumHD, false)) { if (!this.Pawn.IsColonist) { float range = Rand.Range(5f, 25f); HealthUtility.AdjustSeverity(this.Pawn, TorannMagicDefOf.TM_SS_SerumHD, range); } else { HealthUtility.AdjustSeverity(this.Pawn, TorannMagicDefOf.TM_SS_SerumHD, 2.2f); } } } if (this.Pawn.health.hediffSet.HasHediff(TorannMagicDefOf.TM_SS_SerumHD) && this.Pawn.Downed && nextSSTend < Find.TickManager.TicksGame && (this.Pawn.story.traits.HasTrait(TorannMagicDefOf.TM_SuperSoldier) || (this.customClass != null && this.customClass.classFighterAbilities.Contains(TorannMagicDefOf.TM_FirstAid)))) { Hediff_Injury wound = this.Pawn.health.hediffSet.GetInjuriesTendable().RandomElement(); if (wound != null && wound.CanHealNaturally()) { wound.Tended(Rand.Range(0, .3f)); } nextSSTend = Find.TickManager.TicksGame + Rand.Range(6000, 8000); } } } public override IEnumerable<Gizmo> CompGetGizmosExtra() { return base.CompGetGizmosExtra(); } private void ResolveSustainedSkills() { float _maxSP = 0; float _maxSPUpkeep = 0; float _spRegenRate = 0; float _spRegenRateUpkeep = 0; float _coolDown = 0; float _spCost = 0; float _xpGain = 0; float _arcaneRes = 0; float _arcaneDmg = 0; bool _arcaneSpectre = false; bool _phantomShift = false; float _arcalleumCooldown = 0f; //Determine trait adjustments IEnumerable<TMDefs.DefModExtension_TraitEnchantments> traitEnum = this.Pawn.story.traits.allTraits .Select((Trait t) => t.def.GetModExtension<TMDefs.DefModExtension_TraitEnchantments>()); foreach (TMDefs.DefModExtension_TraitEnchantments e in traitEnum) { if (e != null) { _maxSP += e.maxSP; _spCost += e.spCost; _spRegenRate += e.spRegenRate; _coolDown += e.mightCooldown; _xpGain += e.xpGain; _arcaneRes += e.arcaneRes; _arcaneDmg += e.combatDmg; } } //Determine apparel and equipment enchantments List<Apparel> apparel = this.Pawn.apparel.WornApparel; if (apparel != null) { totalApparelWeight = 0; for (int i = 0; i < this.Pawn.apparel.WornApparelCount; i++) { Enchantment.CompEnchantedItem item = apparel[i].GetComp<Enchantment.CompEnchantedItem>(); if (item != null) { if (item.HasEnchantment) { float enchantmentFactor = 1f; totalApparelWeight += apparel[i].def.GetStatValueAbstract(StatDefOf.Mass, apparel[i].Stuff); if (item.MadeFromEnchantedStuff) { Enchantment.CompProperties_EnchantedStuff compES = apparel[i].Stuff.GetCompProperties<Enchantment.CompProperties_EnchantedStuff>(); enchantmentFactor = compES.enchantmentBonusMultiplier; float arcalleumFactor = compES.arcalleumCooldownPerMass; if (apparel[i].Stuff.defName == "TM_Arcalleum") { _arcaneRes += .05f; } _arcalleumCooldown += totalApparelWeight * (arcalleumFactor / 100); } _maxSP += item.maxMP * enchantmentFactor; _spRegenRate += item.mpRegenRate * enchantmentFactor; _coolDown += item.coolDown * enchantmentFactor; _xpGain += item.xpGain * enchantmentFactor; _spCost += item.mpCost * enchantmentFactor; _arcaneRes += item.arcaneRes * enchantmentFactor; _arcaneDmg += item.arcaneDmg * enchantmentFactor; if (item.arcaneSpectre == true) { _arcaneSpectre = true; } if (item.phantomShift == true) { _phantomShift = true; } } } } } if (this.Pawn.equipment != null && this.Pawn.equipment.Primary != null) { Enchantment.CompEnchantedItem item = this.Pawn.equipment.Primary.GetComp<Enchantment.CompEnchantedItem>(); if (item != null) { if (item.HasEnchantment) { float enchantmentFactor = 1f; if (item.MadeFromEnchantedStuff) { Enchantment.CompProperties_EnchantedStuff compES = Pawn.equipment.Primary.Stuff.GetCompProperties<Enchantment.CompProperties_EnchantedStuff>(); enchantmentFactor = compES.enchantmentBonusMultiplier; float arcalleumFactor = compES.arcalleumCooldownPerMass; if (Pawn.equipment.Primary.Stuff.defName == "TM_Arcalleum") { _arcaneDmg += .1f; } _arcalleumCooldown += this.Pawn.equipment.Primary.def.GetStatValueAbstract(StatDefOf.Mass, this.Pawn.equipment.Primary.Stuff) * (arcalleumFactor / 100f); } _maxSP += item.maxMP * enchantmentFactor; _spRegenRate += item.mpRegenRate * enchantmentFactor; _coolDown += item.coolDown * enchantmentFactor; _xpGain += item.xpGain * enchantmentFactor; _spCost += item.mpCost * enchantmentFactor; _arcaneRes += item.arcaneRes * enchantmentFactor; _arcaneDmg += item.arcaneDmg * enchantmentFactor; } if (this.Pawn.story != null && this.Pawn.story.traits.HasTrait(TorannMagicDefOf.TM_Monk) && this.Pawn.Faction != null && this.Pawn.Faction.HostileTo(Faction.OfPlayer)) { ThingWithComps outItem; this.Pawn.equipment.TryDropEquipment(this.Pawn.equipment.Primary, out outItem, this.Pawn.Position, true); } } } //Determine active or sustained abilities using (IEnumerator<Hediff> enumerator = this.Pawn.health.hediffSet.GetHediffs<Hediff>().GetEnumerator()) { while (enumerator.MoveNext()) { Hediff rec = enumerator.Current; TMAbilityDef ability = this.MightData.GetHediffAbility(rec); if (ability != null) { MightPowerSkill skill = this.MightData.GetSkill_Efficiency(ability); int level = 0; if (skill != null) { level = skill.level; } _maxSPUpkeep += ability.upkeepEnergyCost * (1f - (ability.upkeepEfficiencyPercent * level)); _spRegenRateUpkeep += ability.upkeepRegenCost * (1f - (ability.upkeepEfficiencyPercent * level)); } else { //if (rec.def.defName == ("TM_HediffSprint")) //{ // MightPowerSkill eff = this.Pawn.GetComp<CompAbilityUserMight>().MightData.MightPowerSkill_Sprint.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Sprint_eff"); // _maxSP -= .3f * (1 - (.1f * eff.level)); // //Catch negative values // if (this.maxSP < 0) // { // this.Pawn.health.RemoveHediff(rec); // Log.Message("Removed " + rec.def.LabelCap + ", insufficient stamina to maintain."); // } //} //if (rec.def.defName == "TM_HediffGearRepair") //{ // _maxSP -= .2f; // //Catch negative values // if (this.maxSP < 0) // { // this.Pawn.health.RemoveHediff(rec); // Log.Message("Removed " + rec.def.LabelCap + ", insufficient stamina to maintain."); // } //} //if (rec.def.defName == "TM_HediffInnerHealing") //{ // _maxSP -= .1f; // //Catch negative values // if (this.maxSP < 0) // { // this.Pawn.health.RemoveHediff(rec); // Log.Message("Removed " + rec.def.LabelCap + ", insufficient stamina to maintain."); // } //} //if (rec.def.defName == "TM_HediffHeavyBlow") //{ // _maxSP -= .3f; // //Catch negative values // if (this.maxSP < 0) // { // this.Pawn.health.RemoveHediff(rec); // Log.Message("Removed " + rec.def.LabelCap + ", insufficient stamina to maintain."); // } //} //if (rec.def.defName == "TM_HediffStrongBack") //{ // _maxSP -= .2f; // //Catch negative values // if (this.maxSP < 0) // { // this.Pawn.health.RemoveHediff(rec); // Log.Message("Removed " + rec.def.LabelCap + ", insufficient stamina to maintain."); // } //} //if (rec.def.defName == "TM_HediffThickSkin") //{ // _maxSP -= .3f; // _spRegenRate -= .15f; // //Catch negative values // if (this.maxSP < 0) // { // this.Pawn.health.RemoveHediff(rec); // Log.Message("Removed " + rec.def.LabelCap + ", insufficient stamina to maintain."); // } //} //if (rec.def.defName == "TM_HediffFightersFocus") //{ // _maxSP -= .15f; // //Catch negative values // if (this.maxSP < 0) // { // this.Pawn.health.RemoveHediff(rec); // Log.Message("Removed " + rec.def.LabelCap + ", insufficient stamina to maintain."); // } //} //if (rec.def == TorannMagicDefOf.TM_ProvisionerAuraHD) //{ // _maxSP -= (.6f * (1f - (this.C_ProvisionerAura_eff * this.Pawn.GetComp<CompAbilityUserMight>().MightData.MightPowerSkill_ProvisionerAura.FirstOrDefault((MightPowerSkill x) => x.label == "TM_ProvisionerAura_eff").level))); // //Catch negative values // if (this.maxSP < 0) // { // this.Pawn.health.RemoveHediff(rec); // MightData.MightPowersC.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_ProvisionerAura).AutoCast = false; // Log.Message("Removed " + rec.def.LabelCap + ", insufficient stamina to maintain."); // } //} //if (rec.def == TorannMagicDefOf.TM_TaskMasterAuraHD) //{ // _maxSP -= (.7f * (1f - (this.C_TaskMasterAura_eff * this.Pawn.GetComp<CompAbilityUserMight>().MightData.MightPowerSkill_TaskMasterAura.FirstOrDefault((MightPowerSkill x) => x.label == "TM_TaskMasterAura_eff").level))); // //Catch negative values // if (this.maxSP < 0) // { // this.Pawn.health.RemoveHediff(rec); // Log.Message("Removed " + rec.def.LabelCap + ", insufficient stamina to maintain."); // MightData.MightPowersC.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_TaskMasterAura).AutoCast = false; // } //} //if (rec.def == TorannMagicDefOf.TM_CommanderAuraHD) //{ // _maxSP -= (.8f * (1f - (this.C_CommanderAura_eff * this.Pawn.GetComp<CompAbilityUserMight>().MightData.MightPowerSkill_CommanderAura.FirstOrDefault((MightPowerSkill x) => x.label == "TM_CommanderAura_eff").level))); // //Catch negative values // if (this.maxSP < 0) // { // this.Pawn.health.RemoveHediff(rec); // MightData.MightPowersC.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_CommanderAura).AutoCast = false; // Log.Message("Removed " + rec.def.LabelCap + ", insufficient stamina to maintain."); // } //} } if (rec.def == TorannMagicDefOf.TM_SS_SerumHD) { _spRegenRate += (float)(.1f * rec.CurStageIndex); _arcaneRes += (float)(.15f * rec.CurStageIndex); _arcaneDmg += (float)(.05f * rec.CurStageIndex); } } } //Bonded animal upkeep if (this.bondedPet != null) { _maxSPUpkeep += TorannMagicDefOf.TM_AnimalFriend.upkeepEnergyCost * (1f - (TorannMagicDefOf.TM_AnimalFriend.upkeepEfficiencyPercent * this.MightData.GetSkill_Efficiency(TorannMagicDefOf.TM_AnimalFriend).level)); if (this.bondedPet.Dead || this.bondedPet.Destroyed) { this.Pawn.needs.mood.thoughts.memories.TryGainMemory(TorannMagicDefOf.RangerPetDied, null); this.bondedPet = null; } else if (this.bondedPet.Faction != null && this.bondedPet.Faction != this.Pawn.Faction) { //sold? punish evil this.Pawn.needs.mood.thoughts.memories.TryGainMemory(TorannMagicDefOf.RangerSoldBondedPet, null); this.bondedPet = null; } else if (!this.bondedPet.health.hediffSet.HasHediff(TorannMagicDefOf.TM_RangerBondHD)) { HealthUtility.AdjustSeverity(this.bondedPet, TorannMagicDefOf.TM_RangerBondHD, .5f); } } if (this.Pawn.needs.mood.thoughts.memories.NumMemoriesOfDef(ThoughtDef.Named("RangerSoldBondedPet")) > 0) { if (this.animalBondingDisabled == false) { this.RemovePawnAbility(TorannMagicDefOf.TM_AnimalFriend); this.animalBondingDisabled = true; } } else { if (this.animalBondingDisabled == true) { this.AddPawnAbility(TorannMagicDefOf.TM_AnimalFriend); this.animalBondingDisabled = false; } } if (MightData.MightAbilityPoints < 0) { MightData.MightAbilityPoints = 0; } //Class and global bonuses _arcaneDmg += .01f * this.MightData.MightPowerSkill_WayfarerCraft.FirstOrDefault((MightPowerSkill x) => x.label == "TM_WayfarerCraft_pwr").level; _arcaneRes += .02f * this.MightData.MightPowerSkill_WayfarerCraft.FirstOrDefault((MightPowerSkill x) => x.label == "TM_WayfarerCraft_pwr").level; _spCost -= .01f * this.MightData.MightPowerSkill_WayfarerCraft.FirstOrDefault((MightPowerSkill x) => x.label == "TM_WayfarerCraft_eff").level; _xpGain += .02f * this.MightData.MightPowerSkill_WayfarerCraft.FirstOrDefault((MightPowerSkill x) => x.label == "TM_WayfarerCraft_eff").level; _coolDown -= .01f * this.MightData.MightPowerSkill_WayfarerCraft.FirstOrDefault((MightPowerSkill x) => x.label == "TM_WayfarerCraft_ver").level; _spRegenRate += .01f * this.MightData.MightPowerSkill_WayfarerCraft.FirstOrDefault((MightPowerSkill x) => x.label == "TM_WayfarerCraft_ver").level; _maxSP += .02f * this.MightData.MightPowerSkill_WayfarerCraft.FirstOrDefault((MightPowerSkill x) => x.label == "TM_WayfarerCraft_ver").level; _maxSPUpkeep *= 1f - (.03f * this.MightData.MightPowerSkill_FieldTraining.FirstOrDefault((MightPowerSkill x) => x.label == "TM_FieldTraining_eff").level); _spRegenRateUpkeep *= 1f - (.03f * this.MightData.MightPowerSkill_FieldTraining.FirstOrDefault((MightPowerSkill x) => x.label == "TM_FieldTraining_eff").level); _maxSP += .04f * this.MightData.MightPowerSkill_global_endurance.FirstOrDefault((MightPowerSkill x) => x.label == "TM_global_endurance_pwr").level; _spRegenRate += .05f * this.MightData.MightPowerSkill_global_refresh.FirstOrDefault((MightPowerSkill x) => x.label == "TM_global_refresh_pwr").level; _spCost += -.025f * this.MightData.MightPowerSkill_global_seff.FirstOrDefault((MightPowerSkill x) => x.label == "TM_global_seff_pwr").level; _arcaneDmg += .05f * this.MightData.MightPowerSkill_global_strength.FirstOrDefault((MightPowerSkill x) => x.label == "TM_global_strength_pwr").level; _arcaneRes += (1f - this.Pawn.GetStatValue(StatDefOf.PsychicSensitivity, false)) / 2f; _arcaneDmg += (this.Pawn.GetStatValue(StatDefOf.PsychicSensitivity, false) - 1f) / 4f; if (this.Pawn.story.traits.HasTrait(TorannMagicDefOf.TM_BoundlessTD)) { this.arcalleumCooldown = Mathf.Clamp(0f + _arcalleumCooldown, 0f, .1f); } else { this.arcalleumCooldown = Mathf.Clamp(0f + _arcalleumCooldown, 0f, .5f); } //resolve upkeep costs _maxSP -= _maxSPUpkeep; _spRegenRate -= _spRegenRateUpkeep; //finalize this.maxSP = Mathf.Clamp(1 + _maxSP, 0f, 5f); this.spRegenRate = 1f + _spRegenRate; this.coolDown = Mathf.Clamp(1f + _coolDown, .25f, 10f); this.xpGain = Mathf.Clamp(1f + _xpGain, 0.01f, 5f); this.spCost = Mathf.Clamp(1f + _spCost, 0.1f, 5f); this.arcaneRes = 1 + _arcaneRes; this.mightPwr = 1 + _arcaneDmg; if (this.IsMightUser && !TM_Calc.IsCrossClass(this.Pawn, false)) { if (_maxSP != 0 && !this.Pawn.health.hediffSet.HasHediff(HediffDef.Named("TM_HediffEnchantment_maxEnergy"))) { HealthUtility.AdjustSeverity(this.Pawn, HediffDef.Named("TM_HediffEnchantment_maxEnergy"), .5f); } if (_spRegenRate != 0 && !this.Pawn.health.hediffSet.HasHediff(HediffDef.Named("TM_HediffEnchantment_energyRegen"))) { HealthUtility.AdjustSeverity(this.Pawn, HediffDef.Named("TM_HediffEnchantment_energyRegen"), .5f); } if (_coolDown != 0 && !this.Pawn.health.hediffSet.HasHediff(HediffDef.Named("TM_HediffEnchantment_coolDown"))) { HealthUtility.AdjustSeverity(this.Pawn, HediffDef.Named("TM_HediffEnchantment_coolDown"), .5f); } if (_xpGain != 0 && !this.Pawn.health.hediffSet.HasHediff(HediffDef.Named("TM_HediffEnchantment_xpGain"))) { HealthUtility.AdjustSeverity(this.Pawn, HediffDef.Named("TM_HediffEnchantment_xpGain"), .5f); } if (_spCost != 0 && !this.Pawn.health.hediffSet.HasHediff(HediffDef.Named("TM_HediffEnchantment_energyCost"))) { HealthUtility.AdjustSeverity(this.Pawn, HediffDef.Named("TM_HediffEnchantment_energyCost"), .5f); } if (_arcaneRes != 0 && !this.Pawn.health.hediffSet.HasHediff(HediffDef.Named("TM_HediffEnchantment_dmgResistance"))) { HealthUtility.AdjustSeverity(this.Pawn, HediffDef.Named("TM_HediffEnchantment_dmgResistance"), .5f); } if (_arcaneDmg != 0 && !this.Pawn.health.hediffSet.HasHediff(HediffDef.Named("TM_HediffEnchantment_dmgBonus"))) { HealthUtility.AdjustSeverity(this.Pawn, HediffDef.Named("TM_HediffEnchantment_dmgBonus"), .5f); } if (_arcalleumCooldown != 0 && !this.Pawn.health.hediffSet.HasHediff(HediffDef.Named("TM_HediffEnchantment_arcalleumCooldown"))) { HealthUtility.AdjustSeverity(this.Pawn, HediffDef.Named("TM_HediffEnchantment_arcalleumCooldown"), .5f); } if (_arcaneSpectre == true && !this.Pawn.health.hediffSet.HasHediff(HediffDef.Named("TM_HediffEnchantment_arcaneSpectre"))) { HealthUtility.AdjustSeverity(this.Pawn, HediffDef.Named("TM_HediffEnchantment_arcaneSpectre"), .5f); } else if (_arcaneSpectre == false && this.Pawn.health.hediffSet.HasHediff(HediffDef.Named("TM_HediffEnchantment_arcaneSpectre"))) { this.Pawn.health.RemoveHediff(this.Pawn.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("TM_HediffEnchantment_arcaneSpectre"))); } if (_phantomShift == true) { HealthUtility.AdjustSeverity(this.Pawn, HediffDef.Named("TM_HediffEnchantment_phantomShift"), .5f); } else if (_phantomShift == false && this.Pawn.health.hediffSet.HasHediff(HediffDef.Named("TM_HediffEnchantment_phantomShift"))) { this.Pawn.health.RemoveHediff(this.Pawn.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("TM_HediffEnchantment_phantomShift"))); } } } public void ResolveStamina() { bool flag = this.Stamina == null; if (flag) { Hediff firstHediffOfDef = base.AbilityUser.health.hediffSet.GetFirstHediffOfDef(TorannMagicDefOf.TM_MightUserHD, false); bool flag2 = firstHediffOfDef != null; if (flag2) { firstHediffOfDef.Severity = 1f; } else { Hediff hediff = HediffMaker.MakeHediff(TorannMagicDefOf.TM_MightUserHD, base.AbilityUser, null); hediff.Severity = 1f; base.AbilityUser.health.AddHediff(hediff, null, null); } } } public void ResolveMightPowers() { bool flag = this.mightPowersInitialized; if (!flag) { this.mightPowersInitialized = true; } } public void ResolveMightTab() { InspectTabBase inspectTabsx = base.AbilityUser.GetInspectTabs().FirstOrDefault((InspectTabBase x) => x.labelKey == "TM_TabMight"); IEnumerable<InspectTabBase> inspectTabs = base.AbilityUser.GetInspectTabs(); bool flag = inspectTabs != null && inspectTabs.Count<InspectTabBase>() > 0; if (flag) { if (inspectTabsx == null) { try { base.AbilityUser.def.inspectorTabsResolved.Add(InspectTabManager.GetSharedInstance(typeof(ITab_Pawn_Might))); } catch (Exception ex) { Log.Error(string.Concat(new object[] { "Could not instantiate inspector tab of type ", typeof(ITab_Pawn_Might), ": ", ex })); } } } } public override void PostExposeData() { //base.PostExposeData(); Scribe_Values.Look<bool>(ref this.mightPowersInitialized, "mightPowersInitialized", false, false); Scribe_Collections.Look<Thing>(ref this.combatItems, "combatItems", LookMode.Reference); Scribe_Deep.Look(ref this.equipmentContainer, "equipmentContainer", new object[0]); Scribe_References.Look<Pawn>(ref this.bondedPet, "bondedPet", false); Scribe_Values.Look<bool>(ref this.skill_GearRepair, "skill_GearRepair", false, false); Scribe_Values.Look<bool>(ref this.skill_InnerHealing, "skill_InnerHealing", false, false); Scribe_Values.Look<bool>(ref this.skill_HeavyBlow, "skill_HeavyBlow", false, false); Scribe_Values.Look<bool>(ref this.skill_Sprint, "skill_Sprint", false, false); Scribe_Values.Look<bool>(ref this.skill_StrongBack, "skill_StrongBack", false, false); Scribe_Values.Look<bool>(ref this.skill_ThickSkin, "skill_ThickSkin", false, false); Scribe_Values.Look<bool>(ref this.skill_FightersFocus, "skill_FightersFocus", false, false); Scribe_Values.Look<bool>(ref this.skill_BurningFury, "skill_BurningFury", false, false); Scribe_Values.Look<bool>(ref this.skill_ThrowingKnife, "skill_ThrowingKnife", false, false); Scribe_Values.Look<bool>(ref this.skill_PommelStrike, "skill_PommelStrike", false, false); Scribe_Values.Look<bool>(ref this.skill_Legion, "skill_Legion", false, false); Scribe_Values.Look<bool>(ref this.skill_TempestStrike, "skill_TempestStrike", false, false); Scribe_Values.Look<bool>(ref this.skill_PistolWhip, "skill_PistolWhip", false, false); Scribe_Values.Look<bool>(ref this.skill_SuppressingFire, "skill_SuppressingFire", false, false); Scribe_Values.Look<bool>(ref this.skill_Mk203GL, "skill_Mk203GL", false, false); Scribe_Values.Look<bool>(ref this.skill_Buckshot, "skill_Buckshot", false, false); Scribe_Values.Look<bool>(ref this.skill_BreachingCharge, "skill_BreachingCharge", false, false); Scribe_Values.Look<bool>(ref this.skill_Teach, "skill_Teach", false, false); Scribe_Values.Look<int>(ref this.allowMeditateTick, "allowMeditateTick", 0, false); Scribe_Values.Look<bool>(ref this.deathRetaliating, "deathRetaliating", false, false); Scribe_Values.Look<bool>(ref this.canDeathRetaliate, "canDeathRetaliate", false, false); Scribe_Values.Look<int>(ref this.ticksTillRetaliation, "ticksTillRetaliation", 600, false); Scribe_Values.Look<bool>(ref this.useCleaveToggle, "useCleaveToggle", true, false); Scribe_Values.Look<bool>(ref this.useCQCToggle, "useCQCToggle", true, false); Scribe_Defs.Look<TMAbilityDef>(ref this.mimicAbility, "mimicAbility"); Scribe_Values.Look<float>(ref this.maxSP, "maxSP", 1f, false); Scribe_Deep.Look<MightData>(ref this.mightData, "mightData", new object[] { this }); bool flag11 = Scribe.mode == LoadSaveMode.PostLoadInit; if (flag11) { Pawn abilityUser = base.AbilityUser; int index = TM_ClassUtility.IsCustomClassIndex(abilityUser.story.traits.allTraits); if (index >= 0) { if (TM_ClassUtility.CustomClasses()[index].isFighter) { this.customClass = TM_ClassUtility.CustomClasses()[index]; this.customIndex = index; foreach (var ability in customClass.classFighterAbilities) { for (int j = 0; j < this.MightData.AllMightPowers.Count; j++) { if (this.MightData.AllMightPowers[j].learned && this.MightData.AllMightPowers[j].TMabilityDefsSet.Contains(ability)) { if (ability.shouldInitialize) { int level = this.MightData.AllMightPowers[j].level; base.AddPawnAbility(this.MightData.AllMightPowers[j].TMabilityDefs[level]); } if (ability.childAbilities != null && ability.childAbilities.Count > 0) { for (int c = 0; c < ability.childAbilities.Count; c++) { if (ability.childAbilities[c].shouldInitialize) { this.AddPawnAbility(ability.childAbilities[c]); } } } } } } } } else { bool flag40 = abilityUser.story.traits.HasTrait(TorannMagicDefOf.Gladiator); if (flag40) { bool flag14 = !this.MightData.MightPowersG.NullOrEmpty<MightPower>(); if (flag14) { foreach (MightPower current3 in this.MightData.MightPowersG) { bool flag15 = current3.abilityDef != null; if (flag15) { if (current3.abilityDef == TorannMagicDefOf.TM_Sprint || current3.abilityDef == TorannMagicDefOf.TM_Sprint_I || current3.abilityDef == TorannMagicDefOf.TM_Sprint_II || current3.abilityDef == TorannMagicDefOf.TM_Sprint_III) { if (current3.level == 0) { base.AddPawnAbility(TorannMagicDefOf.TM_Sprint); } else if (current3.level == 1) { base.AddPawnAbility(TorannMagicDefOf.TM_Sprint_I); } else if (current3.level == 2) { base.AddPawnAbility(TorannMagicDefOf.TM_Sprint_II); } else { base.AddPawnAbility(TorannMagicDefOf.TM_Sprint_III); } } if (current3.abilityDef == TorannMagicDefOf.TM_Grapple || current3.abilityDef == TorannMagicDefOf.TM_Grapple_I || current3.abilityDef == TorannMagicDefOf.TM_Grapple_II || current3.abilityDef == TorannMagicDefOf.TM_Grapple_III) { if (current3.level == 0) { base.AddPawnAbility(TorannMagicDefOf.TM_Grapple); } else if (current3.level == 1) { base.AddPawnAbility(TorannMagicDefOf.TM_Grapple_I); } else if (current3.level == 2) { base.AddPawnAbility(TorannMagicDefOf.TM_Grapple_II); } else { base.AddPawnAbility(TorannMagicDefOf.TM_Grapple_III); } } } } } } if (flag40) { // Log.Message("Loading Gladiator Abilities"); //this.AddPawnAbility(TorannMagicDefOf.TM_Fortitude); //this.AddPawnAbility(TorannMagicDefOf.TM_Cleave); this.AddPawnAbility(TorannMagicDefOf.TM_Whirlwind); } bool flag41 = abilityUser.story.traits.HasTrait(TorannMagicDefOf.TM_Sniper); if (flag41) { bool flag17 = !this.MightData.MightPowersS.NullOrEmpty<MightPower>(); if (flag17) { foreach (MightPower current4 in this.MightData.MightPowersS) { bool flag18 = current4.abilityDef != null; if (flag18) { if (current4.abilityDef == TorannMagicDefOf.TM_DisablingShot || current4.abilityDef == TorannMagicDefOf.TM_DisablingShot_I || current4.abilityDef == TorannMagicDefOf.TM_DisablingShot_II || current4.abilityDef == TorannMagicDefOf.TM_DisablingShot_III) { if (current4.level == 0) { base.AddPawnAbility(TorannMagicDefOf.TM_DisablingShot); } else if (current4.level == 1) { base.AddPawnAbility(TorannMagicDefOf.TM_DisablingShot_I); } else if (current4.level == 2) { base.AddPawnAbility(TorannMagicDefOf.TM_DisablingShot_II); } else { base.AddPawnAbility(TorannMagicDefOf.TM_DisablingShot_III); } } } } } } if (flag41) { //Log.Message("Loading Sniper Abilities"); //this.AddPawnAbility(TorannMagicDefOf.TM_SniperFocus); this.AddPawnAbility(TorannMagicDefOf.TM_Headshot); this.AddPawnAbility(TorannMagicDefOf.TM_AntiArmor); this.AddPawnAbility(TorannMagicDefOf.TM_ShadowSlayer); } bool flag42 = abilityUser.story.traits.HasTrait(TorannMagicDefOf.Bladedancer); if (flag42) { bool flag19 = !this.MightData.MightPowersB.NullOrEmpty<MightPower>(); if (flag19) { foreach (MightPower current5 in this.MightData.MightPowersB) { bool flag20 = current5.abilityDef != null; if (flag20) { if (current5.abilityDef == TorannMagicDefOf.TM_PhaseStrike || current5.abilityDef == TorannMagicDefOf.TM_PhaseStrike_I || current5.abilityDef == TorannMagicDefOf.TM_PhaseStrike_II || current5.abilityDef == TorannMagicDefOf.TM_PhaseStrike_III) { if (current5.level == 0) { base.AddPawnAbility(TorannMagicDefOf.TM_PhaseStrike); } else if (current5.level == 1) { base.AddPawnAbility(TorannMagicDefOf.TM_PhaseStrike_I); } else if (current5.level == 2) { base.AddPawnAbility(TorannMagicDefOf.TM_PhaseStrike_II); } else { base.AddPawnAbility(TorannMagicDefOf.TM_PhaseStrike_III); } } } } } } if (flag42) { //Log.Message("Loading Bladedancer Abilities"); //this.AddPawnAbility(TorannMagicDefOf.TM_BladeFocus); //this.AddPawnAbility(TorannMagicDefOf.TM_BladeArt); this.AddPawnAbility(TorannMagicDefOf.TM_SeismicSlash); this.AddPawnAbility(TorannMagicDefOf.TM_BladeSpin); } bool flag43 = abilityUser.story.traits.HasTrait(TorannMagicDefOf.Ranger); if (flag43) { bool flag21 = !this.MightData.MightPowersR.NullOrEmpty<MightPower>(); if (flag21) { foreach (MightPower current6 in this.MightData.MightPowersR) { bool flag22 = current6.abilityDef != null; if (flag22) { if (current6.abilityDef == TorannMagicDefOf.TM_ArrowStorm || current6.abilityDef == TorannMagicDefOf.TM_ArrowStorm_I || current6.abilityDef == TorannMagicDefOf.TM_ArrowStorm_II || current6.abilityDef == TorannMagicDefOf.TM_ArrowStorm_III) { if (current6.level == 0) { base.AddPawnAbility(TorannMagicDefOf.TM_ArrowStorm); } else if (current6.level == 1) { base.AddPawnAbility(TorannMagicDefOf.TM_ArrowStorm_I); } else if (current6.level == 2) { base.AddPawnAbility(TorannMagicDefOf.TM_ArrowStorm_II); } else { base.AddPawnAbility(TorannMagicDefOf.TM_ArrowStorm_III); } } } } } } if (flag43) { //Log.Message("Loading Ranger Abilities"); //this.AddPawnAbility(TorannMagicDefOf.TM_RangerTraining); //this.AddPawnAbility(TorannMagicDefOf.TM_BowTraining); this.AddPawnAbility(TorannMagicDefOf.TM_PoisonTrap); this.AddPawnAbility(TorannMagicDefOf.TM_AnimalFriend); } bool flag44 = abilityUser.story.traits.HasTrait(TorannMagicDefOf.Faceless); if (flag44) { bool flag21 = !this.MightData.MightPowersF.NullOrEmpty<MightPower>(); if (flag21) { foreach (MightPower current7 in this.MightData.MightPowersF) { bool flag22 = current7.abilityDef != null; if (flag22) { if (current7.abilityDef == TorannMagicDefOf.TM_Transpose || current7.abilityDef == TorannMagicDefOf.TM_Transpose_I || current7.abilityDef == TorannMagicDefOf.TM_Transpose_II || current7.abilityDef == TorannMagicDefOf.TM_Transpose_III) { if (current7.level == 0) { base.AddPawnAbility(TorannMagicDefOf.TM_Transpose); } else if (current7.level == 1) { base.AddPawnAbility(TorannMagicDefOf.TM_Transpose_I); } else if (current7.level == 2) { base.AddPawnAbility(TorannMagicDefOf.TM_Transpose_II); } else { base.AddPawnAbility(TorannMagicDefOf.TM_Transpose_III); } } } } } } if (flag44) { //Log.Message("Loading Faceless Abilities"); this.AddPawnAbility(TorannMagicDefOf.TM_Disguise); this.AddPawnAbility(TorannMagicDefOf.TM_Mimic); this.AddPawnAbility(TorannMagicDefOf.TM_Reversal); this.AddPawnAbility(TorannMagicDefOf.TM_Possess); } bool flag45 = abilityUser.story.traits.HasTrait(TorannMagicDefOf.TM_Psionic); if (flag45) { bool flag21 = !this.MightData.MightPowersP.NullOrEmpty<MightPower>(); if (flag21) { foreach (MightPower current8 in this.MightData.MightPowersP) { bool flag22 = current8.abilityDef != null; if (flag22) { if (current8.abilityDef == TorannMagicDefOf.TM_PsionicBlast || current8.abilityDef == TorannMagicDefOf.TM_PsionicBlast_I || current8.abilityDef == TorannMagicDefOf.TM_PsionicBlast_II || current8.abilityDef == TorannMagicDefOf.TM_PsionicBlast_III) { if (current8.level == 0) { base.AddPawnAbility(TorannMagicDefOf.TM_PsionicBlast); } else if (current8.level == 1) { base.AddPawnAbility(TorannMagicDefOf.TM_PsionicBlast_I); } else if (current8.level == 2) { base.AddPawnAbility(TorannMagicDefOf.TM_PsionicBlast_II); } else { base.AddPawnAbility(TorannMagicDefOf.TM_PsionicBlast_III); } } if (current8.abilityDef == TorannMagicDefOf.TM_PsionicBarrier || current8.abilityDef == TorannMagicDefOf.TM_PsionicBarrier_Projected) { if (current8.level == 0) { base.AddPawnAbility(TorannMagicDefOf.TM_PsionicBarrier); } else { base.AddPawnAbility(TorannMagicDefOf.TM_PsionicBarrier_Projected); } } } } } } if (flag45) { //Log.Message("Loading Psionic Abilities"); //this.AddPawnAbility(TorannMagicDefOf.TM_PsionicBarrier); this.AddPawnAbility(TorannMagicDefOf.TM_PsionicDash); this.AddPawnAbility(TorannMagicDefOf.TM_PsionicStorm); } bool flag46 = abilityUser.story.traits.HasTrait(TorannMagicDefOf.DeathKnight); if (flag46) { bool flag21 = !this.MightData.MightPowersDK.NullOrEmpty<MightPower>(); if (flag21) { foreach (MightPower current9 in this.MightData.MightPowersDK) { bool flag22 = current9.abilityDef != null; if (flag22) { if (current9.abilityDef == TorannMagicDefOf.TM_Spite || current9.abilityDef == TorannMagicDefOf.TM_Spite_I || current9.abilityDef == TorannMagicDefOf.TM_Spite_II || current9.abilityDef == TorannMagicDefOf.TM_Spite_III) { if (current9.level == 0) { base.AddPawnAbility(TorannMagicDefOf.TM_Spite); } else if (current9.level == 1) { base.AddPawnAbility(TorannMagicDefOf.TM_Spite_I); } else if (current9.level == 2) { base.AddPawnAbility(TorannMagicDefOf.TM_Spite_II); } else { base.AddPawnAbility(TorannMagicDefOf.TM_Spite_III); } } if (current9.abilityDef == TorannMagicDefOf.TM_GraveBlade || current9.abilityDef == TorannMagicDefOf.TM_GraveBlade_I || current9.abilityDef == TorannMagicDefOf.TM_GraveBlade_II || current9.abilityDef == TorannMagicDefOf.TM_GraveBlade_III) { if (current9.level == 0) { base.AddPawnAbility(TorannMagicDefOf.TM_GraveBlade); } else if (current9.level == 1) { base.AddPawnAbility(TorannMagicDefOf.TM_GraveBlade_I); } else if (current9.level == 2) { base.AddPawnAbility(TorannMagicDefOf.TM_GraveBlade_II); } else { base.AddPawnAbility(TorannMagicDefOf.TM_GraveBlade_III); } } } } } } if (flag46) { //Log.Message("Loading Death Knight Abilities"); this.AddPawnAbility(TorannMagicDefOf.TM_WaveOfFear); } bool flag47 = abilityUser.story.traits.HasTrait(TorannMagicDefOf.TM_Monk); if (flag47) { //Log.Message("Loading Monk Abilities"); //this.AddPawnAbility(TorannMagicDefOf.TM_Chi); this.AddPawnAbility(TorannMagicDefOf.TM_ChiBurst); //this.AddPawnAbility(TorannMagicDefOf.TM_MindOverBody); this.AddPawnAbility(TorannMagicDefOf.TM_Meditate); this.AddPawnAbility(TorannMagicDefOf.TM_TigerStrike); this.AddPawnAbility(TorannMagicDefOf.TM_DragonStrike); this.AddPawnAbility(TorannMagicDefOf.TM_ThunderStrike); } bool flag48 = abilityUser.story.traits.HasTrait(TorannMagicDefOf.TM_Commander); if (flag48) { // Log.Message("Loading Commander Abilities"); this.AddPawnAbility(TorannMagicDefOf.TM_ProvisionerAura); this.AddPawnAbility(TorannMagicDefOf.TM_TaskMasterAura); this.AddPawnAbility(TorannMagicDefOf.TM_CommanderAura); } if (flag48) { bool flag14 = !this.MightData.MightPowersC.NullOrEmpty<MightPower>(); if (flag14) { foreach (MightPower current10 in this.MightData.MightPowersC) { bool flag15 = current10.abilityDef != null; if (flag15) { if (current10.abilityDef == TorannMagicDefOf.TM_StayAlert || current10.abilityDef == TorannMagicDefOf.TM_StayAlert_I || current10.abilityDef == TorannMagicDefOf.TM_StayAlert_II || current10.abilityDef == TorannMagicDefOf.TM_StayAlert_III) { if (current10.level == 0) { base.AddPawnAbility(TorannMagicDefOf.TM_StayAlert); } else if (current10.level == 1) { base.AddPawnAbility(TorannMagicDefOf.TM_StayAlert_I); } else if (current10.level == 2) { base.AddPawnAbility(TorannMagicDefOf.TM_StayAlert_II); } else { base.AddPawnAbility(TorannMagicDefOf.TM_StayAlert_III); } } if (current10.abilityDef == TorannMagicDefOf.TM_MoveOut || current10.abilityDef == TorannMagicDefOf.TM_MoveOut_I || current10.abilityDef == TorannMagicDefOf.TM_MoveOut_II || current10.abilityDef == TorannMagicDefOf.TM_MoveOut_III) { if (current10.level == 0) { base.AddPawnAbility(TorannMagicDefOf.TM_MoveOut); } else if (current10.level == 1) { base.AddPawnAbility(TorannMagicDefOf.TM_MoveOut_I); } else if (current10.level == 2) { base.AddPawnAbility(TorannMagicDefOf.TM_MoveOut_II); } else { base.AddPawnAbility(TorannMagicDefOf.TM_MoveOut_III); } } if (current10.abilityDef == TorannMagicDefOf.TM_HoldTheLine || current10.abilityDef == TorannMagicDefOf.TM_HoldTheLine_I || current10.abilityDef == TorannMagicDefOf.TM_HoldTheLine_II || current10.abilityDef == TorannMagicDefOf.TM_HoldTheLine_III) { if (current10.level == 0) { base.AddPawnAbility(TorannMagicDefOf.TM_HoldTheLine); } else if (current10.level == 1) { base.AddPawnAbility(TorannMagicDefOf.TM_HoldTheLine_I); } else if (current10.level == 2) { base.AddPawnAbility(TorannMagicDefOf.TM_HoldTheLine_II); } else { base.AddPawnAbility(TorannMagicDefOf.TM_HoldTheLine_III); } } } } } } bool flag49 = abilityUser.story.traits.HasTrait(TorannMagicDefOf.TM_SuperSoldier); if (flag49) { //Log.Message("Loading Super Soldier Abilities"); //this.AddPawnAbility(TorannMagicDefOf.TM_CQC); this.AddPawnAbility(TorannMagicDefOf.TM_FirstAid); this.AddPawnAbility(TorannMagicDefOf.TM_60mmMortar); } } if (this.equipmentContainer != null && this.equipmentContainer.Count > 0) { //Thing outThing = new Thing(); try { //Log.Message("primary is " + this.Pawn.equipment.Primary); //Log.Message("equipment container is " + this.equipmentContainer[0]); for (int i = 0; i < this.Pawn.equipment.AllEquipmentListForReading.Count; i++) { ThingWithComps t = this.Pawn.equipment.AllEquipmentListForReading[i]; if (t.def.defName.Contains("Spec_Base")) { t.Destroy(DestroyMode.Vanish); } } if (ModCheck.Validate.SimpleSidearms.IsInitialized()) { ModCheck.SS.ClearWeaponMemory(this.Pawn); } if (this.specWpnRegNum == -1) { if (this.MightData.MightPowersSS.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_PistolSpec).learned) { TM_Action.DoAction_PistolSpecCopy(this.Pawn, this.equipmentContainer[0]); } else if (this.MightData.MightPowersSS.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_RifleSpec).learned) { TM_Action.DoAction_RifleSpecCopy(this.Pawn, this.equipmentContainer[0]); } else if (this.MightData.MightPowersSS.FirstOrDefault<MightPower>((MightPower x) => x.abilityDef == TorannMagicDefOf.TM_ShotgunSpec).learned) { TM_Action.DoAction_ShotgunSpecCopy(this.Pawn, this.equipmentContainer[0]); } } } catch (Exception ex) { Log.Message("exception on load: " + ex); //do nothing } } this.UpdateAutocastDef(); this.InitializeSkill(); //base.UpdateAbilities(); } } public void UpdateAutocastDef() { IEnumerable<TM_CustomPowerDef> mpDefs = TM_Data.CustomFighterPowerDefs; if (this.IsMightUser && this.MightData != null && this.MightData.MightPowersCustom != null) { foreach (MightPower mp in this.MightData.MightPowersCustom) { foreach (TM_CustomPowerDef mpDef in mpDefs) { if (mpDef.customPower.abilityDefs.FirstOrDefault().ToString() == mp.GetAbilityDef(0).ToString()) { if (mpDef.customPower.autocasting != null) { mp.autocasting = mpDef.customPower.autocasting; } } } } } } private Dictionary<string, Command> gizmoCommands = new Dictionary<string, Command>(); public Command GetGizmoCommands(string key) { if (!gizmoCommands.ContainsKey(key)) { Pawn p = this.Pawn; if (key == "wayfarer") { Command_Action itemWayfarer = new Command_Action { action = new Action(delegate { TM_Action.PromoteWayfarer(p); }), order = 52, defaultLabel = TM_TextPool.TM_PromoteWayfarer, defaultDesc = TM_TextPool.TM_PromoteWayfarerDesc, icon = ContentFinder<Texture2D>.Get("UI/wayfarer", true), }; gizmoCommands.Add(key, itemWayfarer); } if (key == "cleave") { String toggle = "cleave"; String label = "TM_CleaveEnabled".Translate(); String desc = "TM_CleaveToggleDesc".Translate(); if (!this.useCleaveToggle) { toggle = "cleavetoggle_off"; label = "TM_CleaveDisabled".Translate(); } Command_Toggle itemCleave = new Command_Toggle { defaultLabel = label, defaultDesc = desc, order = -90, icon = ContentFinder<Texture2D>.Get("UI/" + toggle, true), isActive = () => this.useCleaveToggle, toggleAction = delegate { this.useCleaveToggle = !this.useCleaveToggle; } }; gizmoCommands.Add(key, itemCleave); } if (key == "cqc") { String toggle = "cqc"; String label = "TM_CQCEnabled".Translate(); String desc = "TM_CQCToggleDesc".Translate(); if (!this.useCQCToggle) { //toggle = "cqc_off"; label = "TM_CQCDisabled".Translate(); } Command_Toggle itemCQC = new Command_Toggle { defaultLabel = label, defaultDesc = desc, order = -90, icon = ContentFinder<Texture2D>.Get("UI/" + toggle, true), isActive = () => this.useCQCToggle, toggleAction = delegate { this.useCQCToggle = !this.useCQCToggle; } }; gizmoCommands.Add(key, itemCQC); } if (key == "psiAugmentation") { String toggle = "psionicaugmentation"; String label = "TM_AugmentationsEnabled".Translate(); String desc = "TM_AugmentationsToggleDesc".Translate(); if (!this.usePsionicAugmentationToggle) { toggle = "psionicaugmentation_off"; label = "TM_AugmentationsDisabled".Translate(); } Command_Toggle item = new Command_Toggle { defaultLabel = label, defaultDesc = desc, order = -90, icon = ContentFinder<Texture2D>.Get("UI/" + toggle, true), isActive = () => this.usePsionicAugmentationToggle, toggleAction = delegate { this.usePsionicAugmentationToggle = !this.usePsionicAugmentationToggle; } }; gizmoCommands.Add(key, item); } if (key == "psiMindAttack") { String toggle2 = "psionicmindattack"; String label2 = "TM_MindAttackEnabled".Translate(); String desc2 = "TM_MindAttackToggleDesc".Translate(); if (!this.usePsionicMindAttackToggle) { toggle2 = "psionicmindattack_off"; label2 = "TM_MindAttackDisabled".Translate(); } Command_Toggle item2 = new Command_Toggle { defaultLabel = label2, defaultDesc = desc2, order = -89, icon = ContentFinder<Texture2D>.Get("UI/" + toggle2, true), isActive = () => this.usePsionicMindAttackToggle, toggleAction = delegate { this.usePsionicMindAttackToggle = !this.usePsionicMindAttackToggle; } }; gizmoCommands.Add(key, item2); } } if (gizmoCommands.TryGetValue(key, out var value)) { return value; } else { return null; } } } }
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.OpenApi.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Feedbacks.Collector.API { 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.AddCors(c => { c.AddPolicy("AllowFCAPIOrigin", options => options.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()); }); services.AddMvc(); services.AddVersionedApiExplorer( options => { // add the versioned api explorer, which also adds IApiVersionDescriptionProvider service // note: the specified format code will format the version as "'v'major[.minor][-status]" options.GroupNameFormat = "'v'VVV"; options.SubstituteApiVersionInUrl = true; }); //Add api versioning services.AddApiVersioning(v => { v.ReportApiVersions = true; v.AssumeDefaultVersionWhenUnspecified = true; v.DefaultApiVersion = new ApiVersion(1, 0); }); services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "feedbacks.collector.api", Version = "v1", Description = "Will be collecting user feedbacks over article posting", Contact = new OpenApiContact() { Name = "Mahi Uddin", Email = "[email protected]", Url = new Uri("https://www.linkedin.com/in/kingcobrass/") } }); }); } // 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", "Feedbacks.Collector.API v1")); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseCors(options => options.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
using System; using System.Linq; using System.Threading.Tasks; using Fluid; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Options; using OrchardCore.Autoroute.Model; using OrchardCore.Autoroute.Models; using OrchardCore.ContentManagement; using OrchardCore.ContentManagement.Handlers; using OrchardCore.ContentManagement.Metadata; using OrchardCore.ContentManagement.Records; using OrchardCore.ContentManagement.Routing; using OrchardCore.Environment.Cache; using OrchardCore.Liquid; using OrchardCore.Settings; using YesSql; namespace OrchardCore.Autoroute.Handlers { public class AutoroutePartHandler : ContentPartHandler<AutoroutePart> { private readonly IAutorouteEntries _entries; private readonly AutorouteOptions _options; private readonly ILiquidTemplateManager _liquidTemplateManager; private readonly IContentDefinitionManager _contentDefinitionManager; private readonly ISiteService _siteService; private readonly ITagCache _tagCache; private readonly ISession _session; public AutoroutePartHandler( IAutorouteEntries entries, IOptions<AutorouteOptions> options, ILiquidTemplateManager liquidTemplateManager, IContentDefinitionManager contentDefinitionManager, ISiteService siteService, ITagCache tagCache, ISession session) { _entries = entries; _options = options.Value; _liquidTemplateManager = liquidTemplateManager; _contentDefinitionManager = contentDefinitionManager; _siteService = siteService; _tagCache = tagCache; _session = session; } public override async Task PublishedAsync(PublishContentContext context, AutoroutePart part) { if (!String.IsNullOrWhiteSpace(part.Path)) { _entries.AddEntry(part.ContentItem.ContentItemId, part.Path); } if (part.SetHomepage) { var site = await _siteService.GetSiteSettingsAsync(); if (site.HomeRoute == null) { site.HomeRoute = new RouteValueDictionary(); } var homeRoute = site.HomeRoute; foreach (var entry in _options.GlobalRouteValues) { homeRoute[entry.Key] = entry.Value; } homeRoute[_options.ContentItemIdKey] = context.ContentItem.ContentItemId; // Once we too the flag into account we can dismiss it. part.SetHomepage = false; await _siteService.UpdateSiteSettingsAsync(site); } // Evict any dependent item from cache await RemoveTagAsync(part); } public override Task UnpublishedAsync(PublishContentContext context, AutoroutePart part) { if (!String.IsNullOrWhiteSpace(part.Path)) { _entries.RemoveEntry(part.ContentItem.ContentItemId, part.Path); // Evict any dependent item from cache return RemoveTagAsync(part); } return Task.CompletedTask; } public override Task RemovedAsync(RemoveContentContext context, AutoroutePart part) { if (!String.IsNullOrWhiteSpace(part.Path)) { _entries.RemoveEntry(part.ContentItem.ContentItemId, part.Path); // Evict any dependent item from cache return RemoveTagAsync(part); } return Task.CompletedTask; } public override async Task UpdatedAsync(UpdateContentContext context, AutoroutePart part) { // Compute the Path only if it's empty if (!String.IsNullOrWhiteSpace(part.Path)) { return; } var pattern = GetPattern(part); if (!String.IsNullOrEmpty(pattern)) { var templateContext = new TemplateContext(); templateContext.SetValue("ContentItem", part.ContentItem); part.Path = await _liquidTemplateManager.RenderAsync(pattern, NullEncoder.Default, templateContext); part.Path = part.Path.Replace("\r", String.Empty).Replace("\n", String.Empty); if (!await IsPathUniqueAsync(part.Path, part)) { part.Path = await GenerateUniquePathAsync(part.Path, part); } part.Apply(); } } public async override Task CloningAsync(CloneContentContext context, AutoroutePart part) { var clonedPart = context.CloneContentItem.As<AutoroutePart>(); clonedPart.Path = await GenerateUniquePathAsync(part.Path, clonedPart); clonedPart.SetHomepage = false; clonedPart.Apply(); } private Task RemoveTagAsync(AutoroutePart part) { return _tagCache.RemoveTagAsync($"alias:{part.Path}"); } /// <summary> /// Get the pattern from the AutoroutePartSettings property for its type /// </summary> private string GetPattern(AutoroutePart part) { var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(part.ContentItem.ContentType); var contentTypePartDefinition = contentTypeDefinition.Parts.FirstOrDefault(x => String.Equals(x.PartDefinition.Name, "AutoroutePart", StringComparison.Ordinal)); var pattern = contentTypePartDefinition.Settings.ToObject<AutoroutePartSettings>().Pattern; return pattern; } private async Task<string> GenerateUniquePathAsync(string path, AutoroutePart context) { var version = 1; var unversionedPath = path; var versionSeparatorPosition = path.LastIndexOf('-'); if (versionSeparatorPosition > -1 && int.TryParse(path.Substring(versionSeparatorPosition).TrimStart('-'), out version)) { unversionedPath = path.Substring(0, versionSeparatorPosition); } while (true) { var versionedPath = $"{unversionedPath}-{version++}"; if (await IsPathUniqueAsync(versionedPath, context)) { return versionedPath; } } } private async Task<bool> IsPathUniqueAsync(string path, AutoroutePart context) { return (await _session.QueryIndex<AutoroutePartIndex>(o => o.ContentItemId != context.ContentItem.ContentItemId && o.Path == path).CountAsync()) == 0; } } }
using UnityEngine; using System.Collections; using UnityEngine.UI; public class PlayerController : MonoBehaviour { // Use this for initialization private Animator anim; private Rigidbody2D rb2d; public Transform posPe; [HideInInspector] public bool tocaChao = false; //Declaração da variaveis do pulo public float Velocidade; public float ForcaPulo = 1000f; [HideInInspector] public bool viradoDireita = true; public bool jump; public Image vida; private MensagemControle MC; private float tempodetiro = 0.2f; private float controledetiro = 0f; public Transform posicaotiro; public GameObject tiro; void Start () { anim = GetComponent<Animator> (); rb2d = GetComponent<Rigidbody2D> (); GameObject mensagemControleObject = GameObject.FindWithTag ("MensagemControle"); if (mensagemControleObject != null) { MC = mensagemControleObject.GetComponent<MensagemControle> (); } } // Update is called once per frame void Update () { //Verifica se p player está tocando o chão tocaChao = Physics2D.Linecast (transform.position, posPe.position, 1 << LayerMask.NameToLayer ("Ground")); if ((Input.GetKeyDown("space"))&& tocaChao) { jump = true; } if (controledetiro > 0) { controledetiro -= Time.deltaTime; } if (Input.GetKeyDown ("j")) { Tiro (); controledetiro = tempodetiro; } } void FixedUpdate() { float translationY = 0; float translationX = Input.GetAxis ("Horizontal") * Velocidade; transform.Translate (translationX, translationY, 0); transform.Rotate (0, 0, 0); if (translationX != 0 && tocaChao) { anim.SetTrigger ("run armado"); } else { anim.SetTrigger("stand armado"); } if (jump == true) { anim.SetTrigger("pula"); rb2d.AddForce(new Vector2(0f, ForcaPulo)); jump = false; } if (jump == false && translationX != 0 && tocaChao){ anim.SetTrigger ("run armado"); } else { anim.SetTrigger("stand armado"); } if(translationX>0 && !viradoDireita) { Flip(); } else if (translationX < 0 && viradoDireita) Flip (); if (translationX > 0 && !viradoDireita) { Flip (); } else if (translationX < 0 && viradoDireita) { Flip(); } } void Flip() { viradoDireita = !viradoDireita; Vector3 escala = transform.localScale; escala.x *= -1; transform.localScale = escala; } public void SubtraiVida() { vida.fillAmount-=0.1f; if (vida.fillAmount <= 0) { MC.GameOver(); Destroy(gameObject); } } void Tiro(){ if (controledetiro <= 0f) { if (tiro != null) { var clonetiro = Instantiate (tiro, posicaotiro.position, Quaternion.identity) as GameObject; clonetiro.transform.localScale = this.transform.localScale; Destroy (clonetiro,20f); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace DllToInject { //this awesome code was extracted from here: https://stackoverflow.com/a/53029501 class PointerToObject { [StructLayout(LayoutKind.Explicit)] private struct ObjectReinterpreter { [FieldOffset(0)] public ObjectWrapper AsObject; [FieldOffset(0)] public IntPtrWrapper AsIntPtr; } private class ObjectWrapper { public object Object; } private class IntPtrWrapper { public IntPtr Value; } ObjectReinterpreter or; public PointerToObject(IntPtr pointer) { or = new ObjectReinterpreter(); or.AsObject = new ObjectWrapper(); or.AsIntPtr.Value = pointer; } public object GetObject() { return or.AsObject.Object; } } }
using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace Meziantou.Analyzer.Rules { [DiagnosticAnalyzer(LanguageNames.CSharp)] public sealed class StringShouldNotContainsNonDeterministicEndOfLineAnalyzer : DiagnosticAnalyzer { private static readonly DiagnosticDescriptor s_rule = new( RuleIdentifiers.StringShouldNotContainsNonDeterministicEndOfLine, title: "String contains an implicit end of line character", messageFormat: "String contains an implicit end of line character", RuleCategories.Usage, DiagnosticSeverity.Hidden, isEnabledByDefault: true, description: "", helpLinkUri: RuleIdentifiers.GetHelpUri(RuleIdentifiers.StringShouldNotContainsNonDeterministicEndOfLine)); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(s_rule); public override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.RegisterSyntaxNodeAction(AnalyzeStringLiteralExpression, SyntaxKind.StringLiteralExpression); context.RegisterSyntaxNodeAction(AnalyzeInterpolatedVerbatimStringStartToken, SyntaxKind.InterpolatedStringExpression); } private void AnalyzeInterpolatedVerbatimStringStartToken(SyntaxNodeAnalysisContext context) { var node = (InterpolatedStringExpressionSyntax)context.Node; foreach (var item in node.Contents) { if (item is InterpolatedStringTextSyntax text) { var position = text.GetLocation().GetLineSpan(); if (position.StartLinePosition.Line != position.EndLinePosition.Line) { context.ReportDiagnostic(s_rule, node); return; } } } } private void AnalyzeStringLiteralExpression(SyntaxNodeAnalysisContext context) { var node = (LiteralExpressionSyntax)context.Node; var position = node.GetLocation().GetLineSpan(); if (position.StartLinePosition.Line != position.EndLinePosition.Line) { context.ReportDiagnostic(s_rule, node); } } } }
using System; class Program { static void Main(string[] args) { AVL<int> tree = new AVL<int>(); tree.Insert(1); tree.Insert(2); tree.Insert(3); tree.Insert(4); tree.Insert(5); tree.Insert(6); } }
@model BookStore.Models.Book @{ ViewData["Title"] = "Delete"; } <h1>Delete</h1> <h3>Are you sure you want to delete this?</h3> <div> <h4>Book</h4> <hr /> <dl class="row"> <dt class = "col-sm-2"> @Html.DisplayNameFor(model => model.id) </dt> <dd class = "col-sm-10"> @Html.DisplayFor(model => model.id) </dd> <dt class = "col-sm-2"> @Html.DisplayNameFor(model => model.title) </dt> <dd class = "col-sm-10"> @Html.DisplayFor(model => model.title) </dd> <dt class = "col-sm-2"> @Html.DisplayNameFor(model => model.description) </dt> <dd class = "col-sm-10"> @Html.DisplayFor(model => model.description) </dd> </dl> <form asp-action="_Delete" asp-route-id="@Model.id"> <input type="submit" value="Delete" class="btn btn-danger" /> | <a asp-action="Index" class="btn btn-outline-info">Back to List</a> </form> </div>
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Text; using System.Threading; using System.Xml; using Orleans.Configuration; using Orleans.Providers; namespace Orleans.Runtime.Configuration { /// <summary> /// Orleans client configuration parameters. /// </summary> [Serializable] public class ClientConfiguration : MessagingConfiguration, IStatisticsConfiguration { internal const string DEPRECATE_DEPLOYMENT_ID_MESSAGE = "DeploymentId is the same as ClusterId. Please use ClusterId instead of DeploymentId."; /// <summary> /// Specifies the type of the gateway provider. /// </summary> public enum GatewayProviderType { /// <summary>No provider specified</summary> None, /// <summary>use Azure, requires SystemStore element</summary> AzureTable, /// <summary>use ADO.NET, requires SystemStore element</summary> AdoNet, /// <summary>use ZooKeeper, requires SystemStore element</summary> ZooKeeper, /// <summary>use Config based static list, requires Config element(s)</summary> Config, /// <summary>use provider from third-party assembly</summary> Custom } /// <summary> /// The name of this client. /// </summary> public string ClientName { get; set; } = "Client"; /// <summary>Gets the configuration source file path</summary> public string SourceFile { get; private set; } /// <summary> /// The list of the gateways to use. /// Each GatewayNode element specifies an outside grain client gateway node. /// If outside (non-Orleans) clients are to connect to the Orleans system, then at least one gateway node must be specified. /// Additional gateway nodes may be specified if desired, and will add some failure resilience and scalability. /// If multiple gateways are specified, then each client will select one from the list at random. /// </summary> public IList<IPEndPoint> Gateways { get; set; } /// <summary> /// </summary> public int PreferedGatewayIndex { get; set; } /// <summary> /// </summary> public GatewayProviderType GatewayProvider { get; set; } /// <summary> /// Service Id. /// </summary> public Guid ServiceId { get; set; } /// <summary> /// Specifies a unique identifier for this cluster. /// If the silos are deployed on Azure (run as workers roles), deployment id is set automatically by Azure runtime, /// accessible to the role via RoleEnvironment.DeploymentId static variable and is passed to the silo automatically by the role via config. /// So if the silos are run as Azure roles this variable should not be specified in the OrleansConfiguration.xml (it will be overwritten if specified). /// If the silos are deployed on the cluster and not as Azure roles, this variable should be set by a deployment script in the OrleansConfiguration.xml file. /// </summary> public string ClusterId { get; set; } /// <summary> /// Deployment Id. This is the same as ClusterId and has been deprecated in favor of it. /// </summary> [Obsolete(DEPRECATE_DEPLOYMENT_ID_MESSAGE)] public string DeploymentId { get => this.ClusterId; set => this.ClusterId = value; } /// <summary> /// Specifies the connection string for the gateway provider. /// If the silos are deployed on Azure (run as workers roles), DataConnectionString may be specified via RoleEnvironment.GetConfigurationSettingValue("DataConnectionString"); /// In such a case it is taken from there and passed to the silo automatically by the role via config. /// So if the silos are run as Azure roles and this config is specified via RoleEnvironment, /// this variable should not be specified in the OrleansConfiguration.xml (it will be overwritten if specified). /// If the silos are deployed on the cluster and not as Azure roles, this variable should be set in the OrleansConfiguration.xml file. /// If not set at all, DevelopmentStorageAccount will be used. /// </summary> public string DataConnectionString { get; set; } /// <summary> /// When using ADO, identifies the underlying data provider for the gateway provider. This three-part naming syntax is also used when creating a new factory /// and for identifying the provider in an application configuration file so that the provider name, along with its associated /// connection string, can be retrieved at run time. https://msdn.microsoft.com/en-us/library/dd0w4a2z%28v=vs.110%29.aspx /// </summary> public string AdoInvariant { get; set; } public string CustomGatewayProviderAssemblyName { get; set; } /// <summary> /// Whether Trace.CorrelationManager.ActivityId settings should be propagated into grain calls. /// </summary> public bool PropagateActivityId { get; set; } /// <summary> /// </summary> public AddressFamily PreferredFamily { get; set; } /// <summary> /// The Interface attribute specifies the name of the network interface to use to work out an IP address for this machine. /// </summary> public string NetInterface { get; private set; } /// <summary> /// The Port attribute specifies the specific listen port for this client machine. /// If value is zero, then a random machine-assigned port number will be used. /// </summary> public int Port { get; private set; } /// <summary>Gets the true host name, no IP address. It equals Dns.GetHostName()</summary> public string DNSHostName { get; private set; } /// <summary> /// </summary> public TimeSpan GatewayListRefreshPeriod { get; set; } public string StatisticsProviderName { get; set; } public TimeSpan StatisticsPerfCountersWriteInterval { get; set; } public TimeSpan StatisticsLogWriteInterval { get; set; } [Obsolete("Statistics table is no longer supported.")] public bool StatisticsWriteLogStatisticsToTable { get; set; } public StatisticsLevel StatisticsCollectionLevel { get; set; } public TelemetryConfiguration TelemetryConfiguration { get; } = new TelemetryConfiguration(); public LimitManager LimitManager { get; private set; } private static readonly TimeSpan DEFAULT_STATS_PERF_COUNTERS_WRITE_PERIOD = Constants.INFINITE_TIMESPAN; /// <summary> /// </summary> public bool UseAzureSystemStore { get { return GatewayProvider == GatewayProviderType.AzureTable && !String.IsNullOrWhiteSpace(this.ClusterId) && !String.IsNullOrWhiteSpace(DataConnectionString); } } /// <summary> /// </summary> public bool UseAdoNetSystemStore { get { return GatewayProvider == GatewayProviderType.AdoNet && !String.IsNullOrWhiteSpace(this.ClusterId) && !String.IsNullOrWhiteSpace(DataConnectionString); } } private bool HasStaticGateways { get { return Gateways != null && Gateways.Count > 0; } } /// <summary> /// </summary> public IDictionary<string, ProviderCategoryConfiguration> ProviderConfigurations { get; set; } /// <summary>Initializes a new instance of <see cref="ClientConfiguration"/>.</summary> public ClientConfiguration() : base(false) { SourceFile = null; PreferedGatewayIndex = GatewayOptions.DEFAULT_PREFERED_GATEWAY_INDEX; Gateways = new List<IPEndPoint>(); GatewayProvider = GatewayProviderType.None; PreferredFamily = ClientMessagingOptions.DEFAULT_PREFERRED_FAMILY; NetInterface = null; Port = 0; DNSHostName = Dns.GetHostName(); this.ClusterId = ""; DataConnectionString = ""; // Assume the ado invariant is for sql server storage if not explicitly specified AdoInvariant = Constants.INVARIANT_NAME_SQL_SERVER; PropagateActivityId = MessagingOptions.DEFAULT_PROPAGATE_E2E_ACTIVITY_ID; GatewayListRefreshPeriod = GatewayOptions.DEFAULT_GATEWAY_LIST_REFRESH_PERIOD; StatisticsProviderName = null; StatisticsPerfCountersWriteInterval = DEFAULT_STATS_PERF_COUNTERS_WRITE_PERIOD; StatisticsLogWriteInterval = StatisticsOptions.DEFAULT_LOG_WRITE_PERIOD; StatisticsCollectionLevel = StatisticsOptions.DEFAULT_COLLECTION_LEVEL; LimitManager = new LimitManager(); ProviderConfigurations = new Dictionary<string, ProviderCategoryConfiguration>(); } public void Load(TextReader input) { var xml = new XmlDocument(); var xmlReader = XmlReader.Create(input); xml.Load(xmlReader); XmlElement root = xml.DocumentElement; LoadFromXml(root); } internal void LoadFromXml(XmlElement root) { foreach (XmlNode node in root.ChildNodes) { var child = node as XmlElement; if (child != null) { switch (child.LocalName) { case "Gateway": Gateways.Add(ConfigUtilities.ParseIPEndPoint(child).GetResult()); if (GatewayProvider == GatewayProviderType.None) { GatewayProvider = GatewayProviderType.Config; } break; case "Azure": // Throw exception with explicit deprecation error message throw new OrleansException( "The Azure element has been deprecated -- use SystemStore element instead."); case "SystemStore": if (child.HasAttribute("SystemStoreType")) { var sst = child.GetAttribute("SystemStoreType"); GatewayProvider = (GatewayProviderType)Enum.Parse(typeof(GatewayProviderType), sst); } if (child.HasAttribute("CustomGatewayProviderAssemblyName")) { CustomGatewayProviderAssemblyName = child.GetAttribute("CustomGatewayProviderAssemblyName"); if (CustomGatewayProviderAssemblyName.EndsWith(".dll")) throw new FormatException("Use fully qualified assembly name for \"CustomGatewayProviderAssemblyName\""); if (GatewayProvider != GatewayProviderType.Custom) throw new FormatException("SystemStoreType should be \"Custom\" when CustomGatewayProviderAssemblyName is specified"); } if (child.HasAttribute("DeploymentId")) { this.ClusterId = child.GetAttribute("DeploymentId"); } if (child.HasAttribute("ServiceId")) { this.ServiceId = ConfigUtilities.ParseGuid(child.GetAttribute("ServiceId"), "Invalid Guid value for the ServiceId attribute"); } if (child.HasAttribute(Constants.DATA_CONNECTION_STRING_NAME)) { DataConnectionString = child.GetAttribute(Constants.DATA_CONNECTION_STRING_NAME); if (String.IsNullOrWhiteSpace(DataConnectionString)) { throw new FormatException("SystemStore.DataConnectionString cannot be blank"); } if (GatewayProvider == GatewayProviderType.None) { // Assume the connection string is for Azure storage if not explicitly specified GatewayProvider = GatewayProviderType.AzureTable; } } if (child.HasAttribute(Constants.ADO_INVARIANT_NAME)) { AdoInvariant = child.GetAttribute(Constants.ADO_INVARIANT_NAME); if (String.IsNullOrWhiteSpace(AdoInvariant)) { throw new FormatException("SystemStore.AdoInvariant cannot be blank"); } } break; case "Tracing": if (ConfigUtilities.TryParsePropagateActivityId(child, ClientName, out var propagateActivityId)) this.PropagateActivityId = propagateActivityId; break; case "Statistics": ConfigUtilities.ParseStatistics(this, child, ClientName); break; case "Limits": ConfigUtilities.ParseLimitValues(LimitManager, child, ClientName); break; case "Debug": break; case "Messaging": base.Load(child); break; case "LocalAddress": if (child.HasAttribute("PreferredFamily")) { PreferredFamily = ConfigUtilities.ParseEnum<AddressFamily>(child.GetAttribute("PreferredFamily"), "Invalid address family for the PreferredFamily attribute on the LocalAddress element"); } else { throw new FormatException("Missing PreferredFamily attribute on the LocalAddress element"); } if (child.HasAttribute("Interface")) { NetInterface = child.GetAttribute("Interface"); } if (child.HasAttribute("Port")) { Port = ConfigUtilities.ParseInt(child.GetAttribute("Port"), "Invalid integer value for the Port attribute on the LocalAddress element"); } break; case "Telemetry": ConfigUtilities.ParseTelemetry(child, this.TelemetryConfiguration); break; default: if (child.LocalName.EndsWith("Providers", StringComparison.Ordinal)) { var providerCategory = ProviderCategoryConfiguration.Load(child); if (ProviderConfigurations.ContainsKey(providerCategory.Name)) { var existingCategory = ProviderConfigurations[providerCategory.Name]; existingCategory.Merge(providerCategory); } else { ProviderConfigurations.Add(providerCategory.Name, providerCategory); } } break; } } } } /// <summary> /// </summary> public static ClientConfiguration LoadFromFile(string fileName) { if (fileName == null) { return null; } using (TextReader input = File.OpenText(fileName)) { var config = new ClientConfiguration(); config.Load(input); config.SourceFile = fileName; return config; } } /// <summary> /// Registers a given type of <typeparamref name="T"/> where <typeparamref name="T"/> is stream provider /// </summary> /// <typeparam name="T">Non-abstract type which implements <see cref="Orleans.Streams.IStreamProvider"/> stream</typeparam> /// <param name="providerName">Name of the stream provider</param> /// <param name="properties">Properties that will be passed to stream provider upon initialization</param> public void RegisterStreamProvider<T>(string providerName, IDictionary<string, string> properties = null) where T : Orleans.Streams.IStreamProvider { if (typeof(T).IsAbstract || typeof(T).IsGenericType || !typeof(Streams.IStreamProvider).IsAssignableFrom(typeof(T))) throw new ArgumentException("Expected non-generic, non-abstract type which implements IStreamProvider interface", "typeof(T)"); ProviderConfigurationUtility.RegisterProvider(this.ProviderConfigurations, ProviderCategoryConfiguration.STREAM_PROVIDER_CATEGORY_NAME, typeof(T).FullName, providerName, properties); } /// <summary> /// Registers a given stream provider. /// </summary> /// <param name="providerTypeFullName">Full name of the stream provider type</param> /// <param name="providerName">Name of the stream provider</param> /// <param name="properties">Properties that will be passed to the stream provider upon initialization </param> public void RegisterStreamProvider(string providerTypeFullName, string providerName, IDictionary<string, string> properties = null) { ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STREAM_PROVIDER_CATEGORY_NAME, providerTypeFullName, providerName, properties); } /// <summary> /// Retrieves an existing provider configuration /// </summary> /// <param name="providerTypeFullName">Full name of the stream provider type</param> /// <param name="providerName">Name of the stream provider</param> /// <param name="config">The provider configuration, if exists</param> /// <returns>True if a configuration for this provider already exists, false otherwise.</returns> public bool TryGetProviderConfiguration(string providerTypeFullName, string providerName, out IProviderConfiguration config) { return ProviderConfigurationUtility.TryGetProviderConfiguration(ProviderConfigurations, providerTypeFullName, providerName, out config); } /// <summary> /// Retrieves an enumeration of all currently configured provider configurations. /// </summary> /// <returns>An enumeration of all currently configured provider configurations.</returns> public IEnumerable<IProviderConfiguration> GetAllProviderConfigurations() { return ProviderConfigurationUtility.GetAllProviderConfigurations(ProviderConfigurations); } /// <summary> /// Loads the configuration from the standard paths, looking up the directory hierarchy /// </summary> /// <returns>Client configuration data if a configuration file was found.</returns> /// <exception cref="FileNotFoundException">Thrown if no configuration file could be found in any of the standard locations</exception> public static ClientConfiguration StandardLoad() { var fileName = ConfigUtilities.FindConfigFile(false); // Throws FileNotFoundException return LoadFromFile(fileName); } /// <summary>Returns a detailed human readable string that represents the current configuration. It does not contain every single configuration knob.</summary> public override string ToString() { var sb = new StringBuilder(); sb.AppendLine("Platform version info:").Append(ConfigUtilities.RuntimeVersionInfo()); sb.Append(" Host: ").AppendLine(Dns.GetHostName()); sb.Append(" Processor Count: ").Append(System.Environment.ProcessorCount).AppendLine(); sb.AppendLine("Client Configuration:"); sb.Append(" Config File Name: ").AppendLine(string.IsNullOrEmpty(SourceFile) ? "" : Path.GetFullPath(SourceFile)); sb.Append(" Start time: ").AppendLine(LogFormatter.PrintDate(DateTime.UtcNow)); sb.Append(" Gateway Provider: ").Append(GatewayProvider); if (GatewayProvider == GatewayProviderType.None) { sb.Append(". Gateway Provider that will be used instead: ").Append(GatewayProviderToUse); } sb.AppendLine(); if (Gateways != null && Gateways.Count > 0 ) { sb.AppendFormat(" Gateways[{0}]:", Gateways.Count).AppendLine(); foreach (var endpoint in Gateways) { sb.Append(" ").AppendLine(endpoint.ToString()); } } else { sb.Append(" Gateways: ").AppendLine("Unspecified"); } sb.Append(" Preferred Gateway Index: ").AppendLine(PreferedGatewayIndex.ToString()); if (Gateways != null && PreferedGatewayIndex >= 0 && PreferedGatewayIndex < Gateways.Count) { sb.Append(" Preferred Gateway Address: ").AppendLine(Gateways[PreferedGatewayIndex].ToString()); } sb.Append(" GatewayListRefreshPeriod: ").Append(GatewayListRefreshPeriod).AppendLine(); if (!String.IsNullOrEmpty(this.ClusterId) || !String.IsNullOrEmpty(DataConnectionString)) { sb.Append(" Azure:").AppendLine(); sb.Append(" ClusterId: ").Append(this.ClusterId).AppendLine(); string dataConnectionInfo = ConfigUtilities.RedactConnectionStringInfo(DataConnectionString); // Don't print Azure account keys in log files sb.Append(" DataConnectionString: ").Append(dataConnectionInfo).AppendLine(); } if (!string.IsNullOrWhiteSpace(NetInterface)) { sb.Append(" Network Interface: ").AppendLine(NetInterface); } if (Port != 0) { sb.Append(" Network Port: ").Append(Port).AppendLine(); } sb.Append(" Preferred Address Family: ").AppendLine(PreferredFamily.ToString()); sb.Append(" DNS Host Name: ").AppendLine(DNSHostName); sb.Append(" Client Name: ").AppendLine(ClientName); sb.Append(ConfigUtilities.IStatisticsConfigurationToString(this)); sb.Append(LimitManager); sb.AppendFormat(base.ToString()); sb.Append(" .NET: ").AppendLine(); int workerThreads; int completionPortThreads; ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads); sb.AppendFormat(" .NET thread pool sizes - Min: Worker Threads={0} Completion Port Threads={1}", workerThreads, completionPortThreads).AppendLine(); ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads); sb.AppendFormat(" .NET thread pool sizes - Max: Worker Threads={0} Completion Port Threads={1}", workerThreads, completionPortThreads).AppendLine(); sb.AppendFormat(" Providers:").AppendLine(); sb.Append(ProviderConfigurationUtility.PrintProviderConfigurations(ProviderConfigurations)); return sb.ToString(); } internal GatewayProviderType GatewayProviderToUse { get { // order is important here for establishing defaults. if (GatewayProvider != GatewayProviderType.None) return GatewayProvider; if (UseAzureSystemStore) return GatewayProviderType.AzureTable; return HasStaticGateways ? GatewayProviderType.Config : GatewayProviderType.None; } } internal void CheckGatewayProviderSettings() { switch (GatewayProvider) { case GatewayProviderType.AzureTable: if (!UseAzureSystemStore) throw new ArgumentException("Config specifies Azure based GatewayProviderType, but Azure element is not specified or not complete.", "GatewayProvider"); break; case GatewayProviderType.Config: if (!HasStaticGateways) throw new ArgumentException("Config specifies Config based GatewayProviderType, but Gateway element(s) is/are not specified.", "GatewayProvider"); break; case GatewayProviderType.Custom: if (String.IsNullOrEmpty(CustomGatewayProviderAssemblyName)) throw new ArgumentException("Config specifies Custom GatewayProviderType, but CustomGatewayProviderAssemblyName attribute is not specified", "GatewayProvider"); break; case GatewayProviderType.None: if (!UseAzureSystemStore && !HasStaticGateways) throw new ArgumentException("Config does not specify GatewayProviderType, and also does not have the adequate defaults: no Azure and or Gateway element(s) are specified.","GatewayProvider"); break; case GatewayProviderType.AdoNet: if (!UseAdoNetSystemStore) throw new ArgumentException("Config specifies SqlServer based GatewayProviderType, but ClusterId or DataConnectionString are not specified or not complete.", "GatewayProvider"); break; case GatewayProviderType.ZooKeeper: break; } } /// <summary> /// Returns a ClientConfiguration object for connecting to a local silo (for testing). /// </summary> /// <param name="gatewayPort">Client gateway TCP port</param> /// <returns>ClientConfiguration object that can be passed to GrainClient class for initialization</returns> public static ClientConfiguration LocalhostSilo(int gatewayPort = 40000) { var config = new ClientConfiguration {GatewayProvider = GatewayProviderType.Config}; config.Gateways.Add(new IPEndPoint(IPAddress.Loopback, gatewayPort)); return config; } } }
using ControleDespesas.Domain.Empresas.Interfaces.Repositories; using ControleDespesas.Infra.Data.Repositories; using ControleDespesas.Test.AppConfigurations.Base; using ControleDespesas.Test.AppConfigurations.Settings; using ControleDespesas.Test.AppConfigurations.Util; using NUnit.Framework; namespace ControleDespesas.Test.Empresas.Repositories { public class EmpresaRepositoryTest : DatabaseTest { private readonly IEmpresaRepository _repository; public EmpresaRepositoryTest() { CriarBaseDeDadosETabelas(); _repository = new EmpresaRepository(MockSettingsInfraData); } [SetUp] public void Setup() => CriarBaseDeDadosETabelas(); [Test] public void Salvar() { var empresa = new SettingsTest().Empresa1; _repository.Salvar(empresa); var retorno = _repository.Obter(empresa.Id); TestContext.WriteLine(retorno.FormatarJsonDeSaida()); Assert.AreEqual(empresa.Id, retorno.Id); Assert.AreEqual(empresa.Nome, retorno.Nome); Assert.AreEqual(empresa.Logo, retorno.Logo); } [Test] public void Atualizar() { var empresa = new SettingsTest().Empresa1; _repository.Salvar(empresa); empresa = new SettingsTest().Empresa1Editada; _repository.Atualizar(empresa); var retorno = _repository.Obter(empresa.Id); TestContext.WriteLine(retorno.FormatarJsonDeSaida()); Assert.AreEqual(empresa.Id, retorno.Id); Assert.AreEqual(empresa.Nome, retorno.Nome); Assert.AreEqual(empresa.Logo, retorno.Logo); } [Test] public void Deletar() { var empresa1 = new SettingsTest().Empresa1; _repository.Salvar(empresa1); var empresa2 = new SettingsTest().Empresa2; _repository.Salvar(empresa2); var empresa3 = new SettingsTest().Empresa3; _repository.Salvar(empresa3); _repository.Deletar(empresa2.Id); var retorno = _repository.Listar(); TestContext.WriteLine(retorno.FormatarJsonDeSaida()); Assert.AreEqual(empresa1.Id, retorno[0].Id); Assert.AreEqual(empresa1.Nome, retorno[0].Nome); Assert.AreEqual(empresa1.Logo, retorno[0].Logo); Assert.AreEqual(empresa3.Id, retorno[1].Id); Assert.AreEqual(empresa3.Nome, retorno[1].Nome); Assert.AreEqual(empresa3.Logo, retorno[1].Logo); } [Test] public void Obter() { var empresa = new SettingsTest().Empresa1; _repository.Salvar(empresa); var retorno = _repository.Obter(empresa.Id); TestContext.WriteLine(retorno.FormatarJsonDeSaida()); Assert.AreEqual(empresa.Id, retorno.Id); Assert.AreEqual(empresa.Nome, retorno.Nome); Assert.AreEqual(empresa.Logo, retorno.Logo); } [Test] public void Listar() { var empresa1 = new SettingsTest().Empresa1; _repository.Salvar(empresa1); var empresa2 = new SettingsTest().Empresa2; _repository.Salvar(empresa2); var empresa3 = new SettingsTest().Empresa3; _repository.Salvar(empresa3); var retorno = _repository.Listar(); TestContext.WriteLine(retorno.FormatarJsonDeSaida()); Assert.AreEqual(empresa1.Id, retorno[0].Id); Assert.AreEqual(empresa1.Nome, retorno[0].Nome); Assert.AreEqual(empresa1.Logo, retorno[0].Logo); Assert.AreEqual(empresa2.Id, retorno[1].Id); Assert.AreEqual(empresa2.Nome, retorno[1].Nome); Assert.AreEqual(empresa2.Logo, retorno[1].Logo); Assert.AreEqual(empresa3.Id, retorno[2].Id); Assert.AreEqual(empresa3.Nome, retorno[2].Nome); Assert.AreEqual(empresa3.Logo, retorno[2].Logo); } [Test] public void CheckId() { var empresa = new SettingsTest().Empresa1; _repository.Salvar(empresa); var idExistente = _repository.CheckId(empresa.Id); var idNaoExiste = _repository.CheckId(25); TestContext.WriteLine(idExistente); TestContext.WriteLine(idNaoExiste); Assert.True(idExistente); Assert.False(idNaoExiste); } [Test] public void LocalizarMaxId() { var empresa1 = new SettingsTest().Empresa1; _repository.Salvar(empresa1); var empresa2 = new SettingsTest().Empresa2; _repository.Salvar(empresa2); var empresa3 = new SettingsTest().Empresa3; _repository.Salvar(empresa3); var maxId = _repository.LocalizarMaxId(); TestContext.WriteLine(maxId); Assert.AreEqual(empresa3.Id, maxId); } [TearDown] public void TearDown() => DroparTabelas(); } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using VideoOS.ConfigurationAPI; namespace ConfigAPIClient.Util { public static class BitmapFormatting { public static void PrivacyMaskOverlay(ConfigurationItem item, Bitmap bitmap, bool isShowingMotionDetect) { if (item == null) return; Property maskProperty = item.Properties.FirstOrDefault<Property>(p => p.Key == "PrivacyMaskRegions"); Property sizeProperty = item.Properties.FirstOrDefault<Property>(p => p.Key == "GridSize"); bool enabled = item.EnableProperty != null && item.EnableProperty.Enabled; string sizeString = sizeProperty.Value.Substring(sizeProperty.Value.Length - 1); int size10 = 0; int size = Int32.Parse(sizeString, System.Globalization.CultureInfo.InvariantCulture); if (Int32.TryParse(sizeProperty.Value.Substring(sizeProperty.Value.Length - 2), System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out size10)) size = size10; String mask = maskProperty.Value; if (enabled) { using (Graphics g = Graphics.FromImage(bitmap)) { int maskIx = 0; int boxWidth = bitmap.Width / size; int boxHeight = bitmap.Height / size; Brush fillBrush = new SolidBrush(Color.FromArgb(0x40, Color.Red)); Pen fillPen = new Pen(Color.FromArgb(0x20, Color.Red), 1); if (!isShowingMotionDetect) g.DrawRectangle(Pens.Red, 0, 0, bitmap.Width - 1, bitmap.Height - 1); for (int iy = 0; iy < size; iy++) { for (int ix = 0; ix < size; ix++) { int x1 = ix * bitmap.Width / size; int y1 = iy * bitmap.Height / size; if (mask.Length > maskIx && mask[maskIx] == '1') g.FillRectangle(fillBrush, x1, y1, boxWidth, boxHeight); else if (!isShowingMotionDetect) g.DrawRectangle(fillPen, x1, y1, boxWidth, boxHeight); maskIx++; } } } } } public static void MotionDetectMaskOverlay(ConfigurationItem item, Bitmap bitmap) { Property maskProperty = item.Properties.FirstOrDefault<Property>(p => p.Key == "ExcludeRegions"); Property sizeProperty = item.Properties.FirstOrDefault<Property>(p => p.Key == "GridSize"); bool enabled = item.EnableProperty != null && item.EnableProperty.Enabled; string sizeString = sizeProperty.Value.Substring(sizeProperty.Value.Length - 1); int size10 = 0; int size = Int32.Parse(sizeString, System.Globalization.CultureInfo.InvariantCulture); if (Int32.TryParse(sizeProperty.Value.Substring(sizeProperty.Value.Length - 2), System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out size10)) size = size10; String mask = maskProperty.Value; if (enabled) { using (Graphics g = Graphics.FromImage(bitmap)) { int maskIx = 0; int boxWidth = bitmap.Width / size; int boxHeight = bitmap.Height / size; Brush fillBrush = new SolidBrush(Color.FromArgb(0x40, Color.Blue)); Pen fillPen = new Pen(Color.FromArgb(0x20, Color.Blue), 1); g.DrawRectangle(Pens.Red, 0, 0, bitmap.Width - 1, bitmap.Height - 1); for (int iy = 0; iy < size; iy++) { for (int ix = 0; ix < size; ix++) { int x1 = ix * bitmap.Width / size; int y1 = iy * bitmap.Height / size; if (mask.Length > maskIx && mask[maskIx] == '1') g.FillRectangle(fillBrush, x1, y1, boxWidth, boxHeight); else g.DrawRectangle(fillPen, x1, y1, boxWidth, boxHeight); maskIx++; } } } } } } }
using System; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Razer.Chroma.Broadcast; using RGBKit.Core; namespace AuraConnect { /// <summary> /// The Aura Connect worker /// </summary> public class Worker : BackgroundService { /// <summary> /// The logger /// </summary> private readonly ILogger<Worker> _logger; /// <summary> /// The configuration /// </summary> private readonly IConfiguration _configuration; /// <summary> /// The RGB Kit service /// </summary> private readonly IRGBKitService _rgbKit; /// <summary> /// The Razer Broadcast API /// </summary> private readonly RzChromaBroadcastAPI _api; /// <summary> /// If performance metrics are enabled /// </summary> private readonly bool _performanceMetricsEnabled; /// <summary> /// The performance metrics stopwatch /// </summary> private readonly Stopwatch _performanceMetricsStopwatch; /// <summary> /// Creates the worker /// </summary> /// <param name="logger">The logger</param> /// <param name="configuration">The configuration</param> /// <param name="rgbKit">The RGB Kit service</param> public Worker(ILogger<Worker> logger, IConfiguration configuration, IRGBKitService rgbKit) { _logger = logger; _configuration = configuration; _rgbKit = rgbKit; _api = new RzChromaBroadcastAPI(); _api.ConnectionChanged += Api_ConnectionChanged; _api.ColorChanged += Api_ColorChanged; _performanceMetricsEnabled = (bool)_configuration.GetValue(typeof(bool), "PerformanceMetricsEnabled"); _performanceMetricsStopwatch = new Stopwatch(); } /// <summary> /// Executes the worker /// </summary> /// <param name="stoppingToken">The stopping token</param> /// <returns>A task</returns> protected override async Task ExecuteAsync(CancellationToken stoppingToken) { await Task.Delay(1000, stoppingToken); _logger.LogInformation(new EventId(0, "Logging"), "Initializing Aura Connect..."); await Task.Delay(1000, stoppingToken); _rgbKit.Initialize(); _api.Init(Guid.Parse("e6bef332-95b8-76ec-a6d0-9f402bad244c")); foreach (var deviceProvider in _rgbKit.DeviceProviders) { foreach (var device in deviceProvider.Devices) { _logger.LogInformation(new EventId(0, "Logging"), $"Found Device: {deviceProvider.Name} - {device.Name} - {device.Lights.Count()} Lights"); } } _logger.LogInformation(new EventId(0, "Logging"), "Aura Connect started successfully!"); while (!stoppingToken.IsCancellationRequested) { await Task.Delay(1000, stoppingToken); } } /// <summary> /// Occurs when the connection status to the Razer Chroma Broadcast API changes /// </summary> /// <param name="sender">The sending object</param> /// <param name="e">The arguments</param> private void Api_ConnectionChanged(object sender, RzChromaBroadcastConnectionChangedEventArgs e) { _logger.LogInformation(new EventId(0, "Logging"), e.Connected ? "Razer Chroma Broadcast API connected" : "Razer Chroma Broadcast API disconnected"); } /// <summary> /// Occurs when the connection status to the Razer Chroma Broadcast API changes /// </summary> /// <param name="sender">The sending object</param> /// <param name="e">The arguments</param> private void Api_ColorChanged(object sender, RzChromaBroadcastColorChangedEventArgs e) { var currentColor = 0; foreach (var deviceProvider in _rgbKit.DeviceProviders) { foreach (var device in deviceProvider.Devices) { foreach (var light in device.Lights) { light.Color = e.Colors[currentColor]; currentColor++; if (currentColor == e.Colors.Length) currentColor = 0; } if (_performanceMetricsEnabled) { _performanceMetricsStopwatch.Reset(); _performanceMetricsStopwatch.Start(); } if (device.Lights.Count() > 0) { device.ApplyLights(); } if (_performanceMetricsEnabled) { _performanceMetricsStopwatch.Stop(); _logger.LogInformation(new EventId(1, "Metrics"), deviceProvider.Name + " - " + device.Name + ": Took " + _performanceMetricsStopwatch.ElapsedMilliseconds + "ms To Update"); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using Microsoft.EntityFrameworkCore.ChangeTracking.Internal; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.EntityFrameworkCore.Update; namespace Microsoft.EntityFrameworkCore.Metadata { /// <summary> /// Base type for navigations and properties. /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-modeling">Modeling entity types and relationships</see> for more information. /// </remarks> public abstract class RuntimePropertyBase : AnnotatableBase, IRuntimePropertyBase { private readonly PropertyInfo? _propertyInfo; private readonly FieldInfo? _fieldInfo; private readonly PropertyAccessMode _propertyAccessMode = Model.DefaultPropertyAccessMode; // Warning: Never access these fields directly as access needs to be thread-safe private IClrPropertyGetter? _getter; private IClrPropertySetter? _setter; private IClrPropertySetter? _materializationSetter; private PropertyAccessors? _accessors; private PropertyIndexes? _indexes; private IComparer<IUpdateEntry>? _currentValueComparer; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [EntityFrameworkInternal] protected RuntimePropertyBase( string name, PropertyInfo? propertyInfo, FieldInfo? fieldInfo, PropertyAccessMode propertyAccessMode) { Name = name; _propertyInfo = propertyInfo; _fieldInfo = fieldInfo; _propertyAccessMode = propertyAccessMode; } /// <summary> /// Gets the name of this property-like object. /// </summary> public virtual string Name { [DebuggerStepThrough] get; } /// <summary> /// Gets the type that this property-like object belongs to. /// </summary> public abstract RuntimeEntityType DeclaringEntityType { get; } /// <summary> /// Gets the type of value that this property-like object holds. /// </summary> protected abstract Type ClrType { get; } /// <inheritdoc /> PropertyInfo? IReadOnlyPropertyBase.PropertyInfo { [DebuggerStepThrough] get => _propertyInfo; } /// <inheritdoc /> FieldInfo? IReadOnlyPropertyBase.FieldInfo { [DebuggerStepThrough] get => _fieldInfo; } /// <inheritdoc /> [DebuggerStepThrough] PropertyAccessMode IReadOnlyPropertyBase.GetPropertyAccessMode() => _propertyAccessMode; /// <inheritdoc /> IReadOnlyTypeBase IReadOnlyPropertyBase.DeclaringType { [DebuggerStepThrough] get => DeclaringEntityType; } /// <inheritdoc /> IClrPropertySetter IRuntimePropertyBase.Setter => NonCapturingLazyInitializer.EnsureInitialized( ref _setter, this, static property => new ClrPropertySetterFactory().Create(property)); /// <inheritdoc /> IClrPropertySetter IRuntimePropertyBase.MaterializationSetter => NonCapturingLazyInitializer.EnsureInitialized( ref _materializationSetter, this, static property => new ClrPropertyMaterializationSetterFactory().Create(property)); /// <inheritdoc /> PropertyAccessors IRuntimePropertyBase.Accessors => NonCapturingLazyInitializer.EnsureInitialized( ref _accessors, this, static property => new PropertyAccessorsFactory().Create(property)); /// <inheritdoc /> PropertyIndexes IRuntimePropertyBase.PropertyIndexes { get => NonCapturingLazyInitializer.EnsureInitialized( ref _indexes, this, static property => { var _ = ((IRuntimeEntityType)property.DeclaringEntityType).Counts; }); set => NonCapturingLazyInitializer.EnsureInitialized(ref _indexes, value); } /// <inheritdoc /> Type IReadOnlyPropertyBase.ClrType { [DebuggerStepThrough] get => ClrType; } /// <inheritdoc /> [DebuggerStepThrough] IClrPropertyGetter IPropertyBase.GetGetter() => NonCapturingLazyInitializer.EnsureInitialized( ref _getter, this, static property => new ClrPropertyGetterFactory().Create(property)); /// <inheritdoc /> [DebuggerStepThrough] IComparer<IUpdateEntry> IPropertyBase.GetCurrentValueComparer() => NonCapturingLazyInitializer.EnsureInitialized( ref _currentValueComparer, this, static property => new CurrentValueComparerFactory().Create(property)); } }
using System; using CSF.Screenplay.Performables; namespace CSF.Screenplay.Actors { /// <summary> /// Represents an actor which is able to perform 'then' steps (post-conditions to performing actions, usually /// assertions). /// </summary> public interface IThenActor { /// <summary> /// Performs the given action or task. /// </summary> /// <param name="performable">A performable item.</param> void Should(IPerformable performable); /// <summary> /// Performs an action or task which has a public parameterless constructor. /// </summary> /// <typeparam name="TPerformable">The type of the performable item to execute.</typeparam> void Should<TPerformable>() where TPerformable : IPerformable,new(); /// <summary> /// Performs the given action, task or question and gets a result. /// </summary> /// <returns>The result of performing the task.</returns> /// <param name="performable">A task.</param> /// <typeparam name="TResult">The result type, returned from the task.</typeparam> TResult Should<TResult>(IPerformable<TResult> performable); /// <summary> /// Asks the given question and gets the answer. This is a synonym of <see cref="ShouldGet"/>. /// </summary> /// <returns>The answer returned from the question.</returns> /// <param name="question">A question.</param> /// <typeparam name="TResult">The result type, returned from the question.</typeparam> TResult ShouldSee<TResult>(IQuestion<TResult> question); /// <summary> /// Asks the given question and gets the answer. /// </summary> /// <returns>The answer returned from the question.</returns> /// <param name="question">A question.</param> /// <typeparam name="TResult">The result type, returned from the question.</typeparam> TResult ShouldGet<TResult>(IQuestion<TResult> question); /// <summary> /// Asks the given question and gets the answer. This is a synonym of <see cref="ShouldGet"/>. /// </summary> /// <returns>The answer returned from the question.</returns> /// <param name="question">A question.</param> /// <typeparam name="TResult">The result type, returned from the question.</typeparam> TResult ShouldRead<TResult>(IQuestion<TResult> question); } }
using System.Text.Json.Serialization; namespace Horizon.Payment.Alipay.Response { /// <summary> /// AlipayOpenMiniMiniappFavoriteextDeleteResponse. /// </summary> public class AlipayOpenMiniMiniappFavoriteextDeleteResponse : AlipayResponse { /// <summary> /// 成功:true 失败:false /// </summary> [JsonPropertyName("success")] public bool Success { get; set; } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Reflection; using Invio.Extensions.Reflection; using Invio.Xunit; using Xunit; namespace Invio.Immutable { [UnitTest] public sealed class DoublePropertyHandlerProviderTests : PropertyHandlerProviderTestsBase { [Fact] public void IsSupported_DoubleProperty() { // Arrange var property = ReflectionHelper<Annotated>.GetProperty(obj => obj.UsesPropertyAttribute); var provider = this.CreateProvider(); // Act var isSupported = provider.IsSupported(property); // Assert Assert.True(isSupported); } [Theory] [InlineData(nameof(Fake.ObjectProperty))] [InlineData(nameof(Fake.Int32Property))] public void IsSupported_NonDoubleProperties(String propertyName) { // Arrange var property = typeof(Fake).GetProperty(propertyName); var provider = this.CreateProvider(); // Act var isSupported = provider.IsSupported(property); // Assert Assert.False(isSupported); } [Fact] public void Create_DoubleProperty() { // Arrange var property = ReflectionHelper<Annotated>.GetProperty(obj => obj.UsesPropertyAttribute); var provider = this.CreateDoubleProvider(); // Act var handler = provider.Create(property); // Assert Assert.IsType<DoublePropertyHandler>(handler); } [Theory] [InlineData(nameof(Fake.ObjectProperty))] [InlineData(nameof(Fake.Int32Property))] public void Create_NonDoubleProperties(String propertyName) { // Arrange var property = typeof(Fake).GetProperty(propertyName); var provider = this.CreateProvider(); // Act var exception = Record.Exception( () => provider.Create(property) ); // Assert Assert.IsType<NotSupportedException>(exception); } private static PropertyInfo UsesPropertyAttributeProperty { get; } = ReflectionHelper<Annotated>.GetProperty(obj => obj.UsesPropertyAttribute); private static PropertyInfo AncestorUsesClassAttribute { get; } = ReflectionHelper<Ancestor>.GetProperty(obj => obj.UsesClassAttribute); private static PropertyInfo AncestorVirtualUsesClassAttribute { get; } = ReflectionHelper<Ancestor>.GetProperty(obj => obj.VirtualUsesClassAttribute); private static PropertyInfo AncestorUsesPropertyAttribute { get; } = ReflectionHelper<Ancestor>.GetProperty(obj => obj.UsesPropertyAttribute); private static PropertyInfo AncestorVirtualUsesPropertyAttribute { get; } = ReflectionHelper<Ancestor>.GetProperty(obj => obj.VirtualUsesPropertyAttribute); // ReflectionHelper does not get the correct PropertyInfo for virtual properties private static PropertyInfo DescendantUsesClassAttribute { get; } = typeof(Descendant).GetProperty(nameof(Descendant.UsesClassAttribute)); private static PropertyInfo DescendantVirtualUsesClassAttribute { get; } = typeof(Descendant).GetProperty(nameof(Descendant.VirtualUsesClassAttribute)); private static PropertyInfo DescendantUsesPropertyAttribute { get; } = typeof(Descendant).GetProperty(nameof(Descendant.UsesPropertyAttribute)); private static PropertyInfo DescendantVirtualUsesPropertyAttribute { get; } = typeof(Descendant).GetProperty(nameof(Descendant.VirtualUsesPropertyAttribute)); public static IEnumerable<Object[]> Create_PropertyHandler_MemberData { get; } = ImmutableList.Create( new Object[] { nameof(Annotated), UsesPropertyAttributeProperty, 5, PrecisionStyle.DecimalPlaces }, new Object[] { nameof(Ancestor), AncestorUsesClassAttribute, 8, PrecisionStyle.DecimalPlaces }, new Object[] { nameof(Ancestor), AncestorVirtualUsesClassAttribute, 8, PrecisionStyle.DecimalPlaces }, new Object[] { nameof(Ancestor), AncestorUsesPropertyAttribute, 6, PrecisionStyle.SignificantFigures }, new Object[] { nameof(Ancestor), AncestorVirtualUsesPropertyAttribute, 4, PrecisionStyle.SignificantFigures }, new Object[] { nameof(Descendant), DescendantUsesClassAttribute, 10, PrecisionStyle.SignificantFigures }, new Object[] { nameof(Descendant), DescendantVirtualUsesClassAttribute, 10, PrecisionStyle.SignificantFigures }, new Object[] { nameof(Descendant), DescendantUsesPropertyAttribute, 6, PrecisionStyle.SignificantFigures }, new Object[] { nameof(Descendant), DescendantVirtualUsesPropertyAttribute, 5, PrecisionStyle.DecimalPlaces } ); [Theory] [MemberData(nameof(Create_PropertyHandler_MemberData))] public void VerifyPropertyHandlerSettings( String declaringType, PropertyInfo property, Int32 expectedPrecision, PrecisionStyle expectedPrecisionStyle) { // Arrange var provider = this.CreateDoubleProvider(); // Act var handler = provider.Create(property); // Assert var singleHandler = Assert.IsType<DoublePropertyHandler>(handler); Assert.Equal(expectedPrecision, singleHandler.Precision); Assert.Equal(expectedPrecisionStyle, singleHandler.PrecisionStyle); } protected override IPropertyHandlerProvider CreateProvider() { return this.CreateDoubleProvider(); } private DoublePropertyHandlerProvider CreateDoubleProvider() { return new DoublePropertyHandlerProvider(); } public abstract class SettableImmutableBase<TImmutable> : ImmutableBase<TImmutable> where TImmutable : SettableImmutableBase<TImmutable> { public TImmutable SetPropertyValue(string propertyName, object propertyValue) { return this.SetPropertyValueImpl(propertyName, propertyValue); } } private sealed class Fake : SettableImmutableBase<Fake> { public Object ObjectProperty { get; } public Int32 Int32Property { get; } public Fake( Object objectProperty = default(Object), Int32 int32Property = default(Int32)) { this.ObjectProperty = objectProperty; this.Int32Property = int32Property; } } private sealed class Annotated { [DoubleComparison(5, PrecisionStyle = PrecisionStyle.DecimalPlaces)] public Double UsesPropertyAttribute { get; } public Double UsesDefaultHandler { get; } public Annotated( Double usesPropertyAttribute = default(Double), Double usesDefaultHandler = default(Double)) { this.UsesPropertyAttribute = usesPropertyAttribute; this.UsesDefaultHandler = usesDefaultHandler; } } [DoubleComparison(8)] private class Ancestor { public Double UsesClassAttribute { get; } public virtual Double VirtualUsesClassAttribute { get; } [DoubleComparison(6, PrecisionStyle.SignificantFigures)] public Double UsesPropertyAttribute { get; } [DoubleComparison(4, PrecisionStyle.SignificantFigures)] public virtual Double VirtualUsesPropertyAttribute { get; } public Ancestor( Double usesClassAttribute = default(Double), Double virtualUsesClassAttribute = default(Double), Double usesPropertyAttribute = default(Double), Double virtualUsesPropertyAttribute = default(Double)) { this.UsesClassAttribute = usesClassAttribute; this.VirtualUsesClassAttribute = virtualUsesClassAttribute; this.UsesPropertyAttribute = usesPropertyAttribute; this.VirtualUsesPropertyAttribute = virtualUsesPropertyAttribute; } } [DoubleComparison(10, PrecisionStyle.SignificantFigures)] private sealed class Descendant : Ancestor { public override Double VirtualUsesClassAttribute => base.VirtualUsesClassAttribute; [DoubleComparison(5)] public override Double VirtualUsesPropertyAttribute => base.VirtualUsesPropertyAttribute; public Descendant( Double usesClassAttribute = default(Double), Double virtualUsesClassAttribute = default(Double), Double usesPropertyAttribute = default(Double), Double virtualUsesPropertyAttribute = default(Double)) : base(usesClassAttribute, virtualUsesClassAttribute, usesPropertyAttribute, virtualUsesPropertyAttribute) { } } } }
/* * Copyright 2014, 2015 Dominick Baier, Brock Allen * * 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 FluentAssertions; using IdentityModel; using IdentityModel.Client; using IdentityServer3.Core.Models; using IdentityServer3.Tests.Conformance; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Text; using Xunit; namespace IdentityServer3.Tests.Endpoints.Connect.PoP { public class PoP_Asymmetrc_Tests_Refresh : IdentityServerHostTest { const string Category = "Endpoints.PoP.Asymmetric.RefreshToken"; string client_id = "code_client"; string client_id_reference = "code_client_reference"; string redirect_uri = "https://code_client/callback"; string client_secret = "secret"; protected override void PreInit() { var api = new Scope { Name = "api", Type = ScopeType.Resource, ScopeSecrets = new List<Secret> { new Secret("secret".Sha256()) } }; host.Scopes.Add(StandardScopes.OpenId); host.Scopes.Add(StandardScopes.OfflineAccess); host.Scopes.Add(api); host.Clients.Add(new Client { Enabled = true, ClientId = client_id, ClientSecrets = new List<Secret> { new Secret(client_secret.Sha256()) }, Flow = Flows.AuthorizationCode, AllowAccessToAllScopes = true, RequireConsent = false, RedirectUris = new List<string> { redirect_uri } }); host.Clients.Add(new Client { Enabled = true, ClientId = client_id_reference, ClientSecrets = new List<Secret> { new Secret(client_secret.Sha256()) }, Flow = Flows.AuthorizationCode, AllowAccessToAllScopes = true, AccessTokenType = AccessTokenType.Reference, UpdateAccessTokenClaimsOnRefresh = false, RequireConsent = false, RedirectUris = new List<string> { redirect_uri } }); } [Fact] [Trait("Category", Category)] public void Valid_Asymmetric_Key() { host.Login(); // request code var nonce = Guid.NewGuid().ToString(); var query = host.RequestAuthorizationCode(client_id, redirect_uri, "openid api offline_access", nonce); var code = query["code"]; host.NewRequest(); host.Client.SetBasicAuthentication(client_id, client_secret); // request tokens using code var jwk = Helper.CreateJwk(); var key = Helper.CreateJwkString(jwk); var result = host.PostForm(host.GetTokenUrl(), new { grant_type = "authorization_code", code, redirect_uri, token_type = "pop", alg = "RS256", key } ); result.StatusCode.Should().Be(HttpStatusCode.OK); result.Headers.CacheControl.NoCache.Should().BeTrue(); result.Headers.CacheControl.NoStore.Should().BeTrue(); var data = result.ReadJsonObject(); data["token_type"].Should().NotBeNull(); data["token_type"].ToString().Should().Be("pop"); data["alg"].ToString().Should().NotBeNull(); data["alg"].ToString().Should().Be("RS256"); data["access_token"].Should().NotBeNull(); data["refresh_token"].Should().NotBeNull(); data["expires_in"].Should().NotBeNull(); data["id_token"].Should().NotBeNull(); var payload = data["access_token"].ToString().Split('.')[1]; var json = Encoding.UTF8.GetString(Base64Url.Decode(payload)); var claims = JObject.Parse(json); claims["cnf"].Should().NotBeNull(); var jjwk = claims["cnf"]["jwk"]; jjwk["kty"].ToString().Should().Be("RSA"); jjwk["e"].ToString().Should().Be(jwk.e); jjwk["n"].ToString().Should().Be(jwk.n); jjwk["alg"].ToString().Should().Be("RS256"); // request new token using refresh token var refresh_token = data["refresh_token"].ToString(); jwk = Helper.CreateJwk(); key = Helper.CreateJwkString(jwk); host.NewRequest(); host.Client.SetBasicAuthentication(client_id, client_secret); result = host.PostForm(host.GetTokenUrl(), new { grant_type = "refresh_token", refresh_token, token_type = "pop", alg = "RS256", key } ); result.StatusCode.Should().Be(HttpStatusCode.OK); result.Headers.CacheControl.NoCache.Should().BeTrue(); result.Headers.CacheControl.NoStore.Should().BeTrue(); data = result.ReadJsonObject(); data["token_type"].Should().NotBeNull(); data["token_type"].ToString().Should().Be("pop"); data["alg"].ToString().Should().NotBeNull(); data["alg"].ToString().Should().Be("RS256"); data["access_token"].Should().NotBeNull(); data["refresh_token"].Should().NotBeNull(); data["expires_in"].Should().NotBeNull(); payload = data["access_token"].ToString().Split('.')[1]; json = Encoding.UTF8.GetString(Base64Url.Decode(payload)); claims = JObject.Parse(json); claims["cnf"].Should().NotBeNull(); jjwk = claims["cnf"]["jwk"]; jjwk["kty"].ToString().Should().Be("RSA"); jjwk["e"].ToString().Should().Be(jwk.e); jjwk["n"].ToString().Should().Be(jwk.n); jjwk["alg"].ToString().Should().Be("RS256"); } [Fact] [Trait("Category", Category)] public void Valid_Asymmetric_Key_Reference() { host.Login(); var nonce = Guid.NewGuid().ToString(); var query = host.RequestAuthorizationCode(client_id_reference, redirect_uri, "openid api offline_access", nonce); var code = query["code"]; host.NewRequest(); host.Client.SetBasicAuthentication(client_id_reference, client_secret); var jwk = Helper.CreateJwk(); var key = Helper.CreateJwkString(jwk); var result = host.PostForm(host.GetTokenUrl(), new { grant_type = "authorization_code", code, redirect_uri, token_type = "pop", alg = "RS256", key } ); result.StatusCode.Should().Be(HttpStatusCode.OK); result.Headers.CacheControl.NoCache.Should().BeTrue(); result.Headers.CacheControl.NoStore.Should().BeTrue(); var data = result.ReadJsonObject(); data["token_type"].Should().NotBeNull(); data["token_type"].ToString().Should().Be("pop"); data["alg"].ToString().Should().NotBeNull(); data["alg"].ToString().Should().Be("RS256"); data["access_token"].Should().NotBeNull(); data["expires_in"].Should().NotBeNull(); data["id_token"].Should().NotBeNull(); data["refresh_token"].ToString().Should().NotBeNull(); var refresh_token = data["refresh_token"].ToString(); var referenceToken = data["access_token"].ToString(); host.NewRequest(); var introspectionResponse = host.Introspect("api", "secret", referenceToken); introspectionResponse.StatusCode.Should().Be(HttpStatusCode.OK); data = introspectionResponse.ReadJsonObject(); data["cnf"].Should().NotBeNull(); var jjwk = data["cnf"]["jwk"]; jjwk["kty"].ToString().Should().Be("RSA"); jjwk["e"].ToString().Should().Be(jwk.e); jjwk["n"].ToString().Should().Be(jwk.n); jjwk["alg"].ToString().Should().Be("RS256"); // request new token using refresh token jwk = Helper.CreateJwk(); key = Helper.CreateJwkString(jwk); host.NewRequest(); host.Client.SetBasicAuthentication(client_id_reference, client_secret); result = host.PostForm(host.GetTokenUrl(), new { grant_type = "refresh_token", refresh_token, token_type = "pop", alg = "RS256", key } ); result.StatusCode.Should().Be(HttpStatusCode.OK); result.Headers.CacheControl.NoCache.Should().BeTrue(); result.Headers.CacheControl.NoStore.Should().BeTrue(); data = result.ReadJsonObject(); data["token_type"].Should().NotBeNull(); data["token_type"].ToString().Should().Be("pop"); data["alg"].ToString().Should().NotBeNull(); data["alg"].ToString().Should().Be("RS256"); data["access_token"].Should().NotBeNull(); data["refresh_token"].Should().NotBeNull(); data["expires_in"].Should().NotBeNull(); referenceToken = data["access_token"].ToString(); host.NewRequest(); introspectionResponse = host.Introspect("api", "secret", referenceToken); introspectionResponse.StatusCode.Should().Be(HttpStatusCode.OK); data = introspectionResponse.ReadJsonObject(); data["cnf"].Should().NotBeNull(); jjwk = data["cnf"]["jwk"]; jjwk["kty"].ToString().Should().Be("RSA"); jjwk["e"].ToString().Should().Be(jwk.e); jjwk["n"].ToString().Should().Be(jwk.n); jjwk["alg"].ToString().Should().Be("RS256"); } } }
using Microsoft.EntityFrameworkCore.Migrations; namespace DevIO.Data.Migrations { public partial class inicial : Migration { protected override void Up(MigrationBuilder migrationBuilder) { } protected override void Down(MigrationBuilder migrationBuilder) { } } }
using System; namespace _16.TrickyStrings { public class TrickyStrings { public static void Main(string[] args) { string delimiter = Console.ReadLine(); int numberN = int.Parse(Console.ReadLine()); string lastPartOfString = ""; string finalString = ""; for (int i = 0; i < numberN; i++) { if (i == numberN-1) { lastPartOfString = Console.ReadLine(); break; } string newString = Console.ReadLine(); finalString = finalString + (newString + delimiter); } Console.WriteLine(finalString + lastPartOfString); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Oppenheimer { public class CheckedListItem<T> : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private bool isChecked; private T item; public CheckedListItem() { } public CheckedListItem(T item, bool isChecked = false) { this.item = item; this.isChecked = isChecked; } public T Item { get { return item; } set { item = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Item")); } } public bool IsChecked { get { return isChecked; } set { isChecked = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("IsChecked")); } } } }
#region copyright // // Copyright (c) DOT Consulting scrl. All rights reserved. // Licensed under the provided EULA. See EULA file in the solution root for full license information. // #endregion using System; using System.Xml; using Dotc.MQ; using Dotc.Wpf.Controls.HexViewer; using Newtonsoft.Json.Linq; namespace Dotc.MQExplorerPlus.Core.Models { public class MessageInfo : SelectableItem//, IMessage { public IMessage MessageSource { get; } public IByteCharConverter CurrentConverter { get; private set; } private Lazy<HexViewerModel> HexLoader; private Lazy<XmlDocument> XmlLoader; private Lazy<JToken> JsonLoader; public MessageInfo(IMessage message, IByteCharConverter converter, int indexOffset = 0) { CurrentConverter = converter; MessageSource = message; BuildData(indexOffset); } private void BuildData(int indexOffset) { if (MessageSource.Index.HasValue) { _index = MessageSource.Index.Value + indexOffset; } _preview = Text?.Replace("\n", "").Replace("\r", ""); HexLoader = new Lazy<HexViewerModel>(() => new HexViewerModel(MessageSource.Bytes, CurrentConverter), true); XmlLoader = new Lazy<XmlDocument>( () => { try { var x = new XmlDocument(); x.LoadXml(MessageSource.Text ?? "<not_an_xml_structure />"); return x; } catch (XmlException) { var x = new XmlDocument(); x.LoadXml("<not_an_xml_structure />"); return x; } }, true); JsonLoader = new Lazy<JToken>( () => { if (!string.IsNullOrEmpty((MessageSource.Text))) { try { return JToken.Parse(MessageSource.Text); } catch (Exception) { } } return null; }, true); ProcessExtendedProperties(); } private void ProcessExtendedProperties() { if (MessageId != null) { MessageIdHexString = MessageId.ToHexString(); MessageIdString = CurrentConverter.ToString(MessageId); } if (MessageSource.ExtendedProperties.GroupId != null) { var b = (byte[])MessageSource.ExtendedProperties.GroupId; GroupIdHexString = b.ToHexString(); GroupIdString = CurrentConverter.ToString(b); } if (MessageSource.ExtendedProperties.CorrelationId != null) { var b = (byte[])MessageSource.ExtendedProperties.CorrelationId; CorrelationIdHexString = b.ToHexString(); CorrelationIdString = CurrentConverter.ToString(b); } } public void ChangeConverter (IByteCharConverter newConverter) { if( newConverter != CurrentConverter) { CurrentConverter = newConverter; if (MessageId != null) { MessageIdString = CurrentConverter.ToString(MessageId); OnPropertyChanged(nameof(MessageIdString)); } if (MessageSource.ExtendedProperties.GroupId != null) { var b = (byte[])MessageSource.ExtendedProperties.GroupId; GroupIdString = CurrentConverter.ToString(b); OnPropertyChanged(nameof(GroupIdString)); } if (MessageSource.ExtendedProperties.CorrelationId != null) { var b = (byte[])MessageSource.ExtendedProperties.CorrelationId; CorrelationIdString = CurrentConverter.ToString(b); OnPropertyChanged(nameof(CorrelationIdString)); } if (HexLoader.IsValueCreated) { HexLoader.Value.CharConverter = newConverter; } } } private int? _index; public int? Index => _index; public IQueue Queue => MessageSource.Queue; public dynamic ExtendedProperties => MessageSource.ExtendedProperties; public byte[] MessageId => MessageSource.MessageId; public string MessageIdHexString { get; private set; } public string MessageIdString { get; private set; } public string CorrelationIdHexString { get; private set; } public string CorrelationIdString { get; private set; } public string GroupIdHexString { get; private set; } public string GroupIdString { get; private set; } public string Text => MessageSource.Text; public DateTime PutTimestamp => MessageSource.PutTimestamp; public int Length => MessageSource.Length; private string _preview; public string PreviewText => _preview; public HexViewerModel Hex { get { return HexLoader.Value; } } public XmlDocument Xml { get { return XmlLoader.Value; } } public JToken JsonToken { get { return JsonLoader.Value; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestConsole { class Program { static void Main(string[] args) { string localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); Console.WriteLine("localAppData: "+localAppData); Console.ReadLine(); } } }
using System; using System.Threading.Tasks; namespace TestContainers.Container.Abstractions.Utilities { /// <summary> /// Worker that batches up requests /// </summary> public abstract class BatchWorker { private readonly object _lockable = new object(); private bool _startingCurrentWorkCycle; private DateTime? _scheduledNotify; // Task for the current work cycle, or null if idle private volatile Task _currentWorkCycle; // Flag is set to indicate that more work has arrived during execution of the task private volatile bool _moreWork; private volatile bool _isDisposed; // Used to communicate the task for the next work cycle to waiters. // This value is non-null only if there are waiters. private TaskCompletionSource<Task> _nextWorkCyclePromise; /// <summary>Implement this member in derived classes to define what constitutes a work cycle</summary> protected abstract Task Work(); /// <summary> /// Notify the worker that there is more work. /// </summary> public void Notify() { lock (_lockable) { if (_currentWorkCycle != null || _startingCurrentWorkCycle) { // lets the current work cycle know that there is more work _moreWork = true; } else { // start a work cycle Start(); } } } /// <summary> /// Instructs the batch worker to run again to check for work, if /// it has not run again already by then, at specified <paramref name="utcTime"/>. /// </summary> /// <param name="utcTime"></param> public void Notify(DateTime utcTime) { var now = DateTime.UtcNow; if (now >= utcTime) { Notify(); } else { lock (_lockable) { if (!_scheduledNotify.HasValue || _scheduledNotify.Value > utcTime) { _scheduledNotify = utcTime; ScheduleNotify(utcTime, now).Ignore(); } } } } private async Task ScheduleNotify(DateTime time, DateTime now) { await Task.Delay(time - now); if (_scheduledNotify == time) { Notify(); } } private void Start() { if (_isDisposed) { return; } // Indicate that we are starting the worker (to prevent double-starts) _startingCurrentWorkCycle = true; // Clear any scheduled runs _scheduledNotify = null; try { // Start the task that is doing the work _currentWorkCycle = Work(); } finally { // By now we have started, and stored the task in currentWorkCycle _startingCurrentWorkCycle = false; // chain a continuation that checks for more work, on the same scheduler _currentWorkCycle.ContinueWith(t => this.CheckForMoreWork(), TaskScheduler.Current); } } /// <summary> /// Executes at the end of each work cycle on the same task scheduler. /// </summary> private void CheckForMoreWork() { TaskCompletionSource<Task> signal = null; Task taskToSignal = null; lock (_lockable) { if (_moreWork) { _moreWork = false; // see if someone created a promise for waiting for the next work cycle // if so, take it and remove it signal = this._nextWorkCyclePromise; this._nextWorkCyclePromise = null; // start the next work cycle Start(); // the current cycle is what we need to signal taskToSignal = _currentWorkCycle; } else { _currentWorkCycle = null; } } // to be safe, must do the signalling out here so it is not under the lock signal?.SetResult(taskToSignal); } /// <summary> /// Check if this worker is idle. /// </summary> public bool IsIdle() { // no lock needed for reading volatile field return _currentWorkCycle == null; } /// <summary> /// Wait for the current work cycle, and also the next work cycle if there is currently unserviced work. /// </summary> /// <returns></returns> public async Task WaitForCurrentWorkToBeServiced() { Task<Task> waitfortasktask = null; Task waitfortask = null; // Figure out exactly what we need to wait for lock (_lockable) { if (!_moreWork) { // Just wait for current work cycle waitfortask = _currentWorkCycle; } else { // we need to wait for the next work cycle // but that task does not exist yet, so we use a promise that signals when the next work cycle is launched if (_nextWorkCyclePromise == null) { _nextWorkCyclePromise = new TaskCompletionSource<Task>(); } waitfortasktask = _nextWorkCyclePromise.Task; } } // Do the actual waiting outside of the lock if (waitfortasktask != null) { await await waitfortasktask; } else if (waitfortask != null) { await waitfortask; } } /// <summary> /// Notify the worker that there is more work, and wait for the current work cycle, and also the next work cycle if there is currently unserviced work. /// </summary> public async Task NotifyAndWaitForWorkToBeServiced() { Task<Task> waitForTaskTask = null; Task waitForTask = null; lock (_lockable) { if (_currentWorkCycle != null || _startingCurrentWorkCycle) { _moreWork = true; if (_nextWorkCyclePromise == null) { _nextWorkCyclePromise = new TaskCompletionSource<Task>(); } waitForTaskTask = _nextWorkCyclePromise.Task; } else { Start(); waitForTask = _currentWorkCycle; } } if (waitForTaskTask != null) { await await waitForTaskTask; } else if (waitForTask != null) { await waitForTask; } } internal void Dispose() { _isDisposed = true; } } }
/* * Bybit API * * ## REST API for the Bybit Exchange. Base URI: [https://api.bybit.com] * * OpenAPI spec version: 0.2.10 * Contact: [email protected] * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; namespace IO.Swagger.Model { /// <summary> /// Create Linear Stop Order /// </summary> [DataContract] public partial class LinearCreateStopOrderResult : IEquatable<LinearCreateStopOrderResult>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="LinearCreateStopOrderResult" /> class. /// </summary> /// <param name="stopOrderId">stopOrderId.</param> /// <param name="userId">userId.</param> /// <param name="side">side.</param> /// <param name="symbol">symbol.</param> /// <param name="orderType">orderType.</param> /// <param name="price">price.</param> /// <param name="qty">qty.</param> /// <param name="timeInForce">timeInForce.</param> /// <param name="orderStatus">orderStatus.</param> /// <param name="triggerPrice">triggerPrice.</param> /// <param name="orderLinkId">orderLinkId.</param> /// <param name="createdAt">createdAt.</param> /// <param name="updatedAt">updatedAt.</param> /// <param name="takeProfit">takeProfit.</param> /// <param name="stopLoss">stopLoss.</param> /// <param name="tpTriggerBy">tpTriggerBy.</param> /// <param name="slTriggerBy">slTriggerBy.</param> public LinearCreateStopOrderResult(string stopOrderId = default(string), long? userId = default(long?), string side = default(string), string symbol = default(string), string orderType = default(string), double? price = default(double?), double? qty = default(double?), string timeInForce = default(string), string orderStatus = default(string), double? triggerPrice = default(double?), string orderLinkId = default(string), string createdAt = default(string), string updatedAt = default(string), double? takeProfit = default(double?), double? stopLoss = default(double?), string tpTriggerBy = default(string), string slTriggerBy = default(string)) { this.StopOrderId = stopOrderId; this.UserId = userId; this.Side = side; this.Symbol = symbol; this.OrderType = orderType; this.Price = price; this.Qty = qty; this.TimeInForce = timeInForce; this.OrderStatus = orderStatus; this.TriggerPrice = triggerPrice; this.OrderLinkId = orderLinkId; this.CreatedAt = createdAt; this.UpdatedAt = updatedAt; this.TakeProfit = takeProfit; this.StopLoss = stopLoss; this.TpTriggerBy = tpTriggerBy; this.SlTriggerBy = slTriggerBy; } /// <summary> /// Gets or Sets StopOrderId /// </summary> [DataMember(Name="stop_order_id", EmitDefaultValue=false)] public string StopOrderId { get; set; } /// <summary> /// Gets or Sets UserId /// </summary> [DataMember(Name="user_id", EmitDefaultValue=false)] public long? UserId { get; set; } /// <summary> /// Gets or Sets Side /// </summary> [DataMember(Name="side", EmitDefaultValue=false)] public string Side { get; set; } /// <summary> /// Gets or Sets Symbol /// </summary> [DataMember(Name="symbol", EmitDefaultValue=false)] public string Symbol { get; set; } /// <summary> /// Gets or Sets OrderType /// </summary> [DataMember(Name="order_type", EmitDefaultValue=false)] public string OrderType { get; set; } /// <summary> /// Gets or Sets Price /// </summary> [DataMember(Name="price", EmitDefaultValue=false)] public double? Price { get; set; } /// <summary> /// Gets or Sets Qty /// </summary> [DataMember(Name="qty", EmitDefaultValue=false)] public double? Qty { get; set; } /// <summary> /// Gets or Sets TimeInForce /// </summary> [DataMember(Name="time_in_force", EmitDefaultValue=false)] public string TimeInForce { get; set; } /// <summary> /// Gets or Sets OrderStatus /// </summary> [DataMember(Name="order_status", EmitDefaultValue=false)] public string OrderStatus { get; set; } /// <summary> /// Gets or Sets TriggerPrice /// </summary> [DataMember(Name="trigger_price", EmitDefaultValue=false)] public double? TriggerPrice { get; set; } /// <summary> /// Gets or Sets OrderLinkId /// </summary> [DataMember(Name="order_link_id", EmitDefaultValue=false)] public string OrderLinkId { get; set; } /// <summary> /// Gets or Sets CreatedAt /// </summary> [DataMember(Name="created_at", EmitDefaultValue=false)] public string CreatedAt { get; set; } /// <summary> /// Gets or Sets UpdatedAt /// </summary> [DataMember(Name="updated_at", EmitDefaultValue=false)] public string UpdatedAt { get; set; } /// <summary> /// Gets or Sets TakeProfit /// </summary> [DataMember(Name="take_profit", EmitDefaultValue=false)] public double? TakeProfit { get; set; } /// <summary> /// Gets or Sets StopLoss /// </summary> [DataMember(Name="stop_loss", EmitDefaultValue=false)] public double? StopLoss { get; set; } /// <summary> /// Gets or Sets TpTriggerBy /// </summary> [DataMember(Name="tp_trigger_by", EmitDefaultValue=false)] public string TpTriggerBy { get; set; } /// <summary> /// Gets or Sets SlTriggerBy /// </summary> [DataMember(Name="sl_trigger_by", EmitDefaultValue=false)] public string SlTriggerBy { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class LinearCreateStopOrderResult {\n"); sb.Append(" StopOrderId: ").Append(StopOrderId).Append("\n"); sb.Append(" UserId: ").Append(UserId).Append("\n"); sb.Append(" Side: ").Append(Side).Append("\n"); sb.Append(" Symbol: ").Append(Symbol).Append("\n"); sb.Append(" OrderType: ").Append(OrderType).Append("\n"); sb.Append(" Price: ").Append(Price).Append("\n"); sb.Append(" Qty: ").Append(Qty).Append("\n"); sb.Append(" TimeInForce: ").Append(TimeInForce).Append("\n"); sb.Append(" OrderStatus: ").Append(OrderStatus).Append("\n"); sb.Append(" TriggerPrice: ").Append(TriggerPrice).Append("\n"); sb.Append(" OrderLinkId: ").Append(OrderLinkId).Append("\n"); sb.Append(" CreatedAt: ").Append(CreatedAt).Append("\n"); sb.Append(" UpdatedAt: ").Append(UpdatedAt).Append("\n"); sb.Append(" TakeProfit: ").Append(TakeProfit).Append("\n"); sb.Append(" StopLoss: ").Append(StopLoss).Append("\n"); sb.Append(" TpTriggerBy: ").Append(TpTriggerBy).Append("\n"); sb.Append(" SlTriggerBy: ").Append(SlTriggerBy).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as LinearCreateStopOrderResult); } /// <summary> /// Returns true if LinearCreateStopOrderResult instances are equal /// </summary> /// <param name="input">Instance of LinearCreateStopOrderResult to be compared</param> /// <returns>Boolean</returns> public bool Equals(LinearCreateStopOrderResult input) { if (input == null) return false; return ( this.StopOrderId == input.StopOrderId || (this.StopOrderId != null && this.StopOrderId.Equals(input.StopOrderId)) ) && ( this.UserId == input.UserId || (this.UserId != null && this.UserId.Equals(input.UserId)) ) && ( this.Side == input.Side || (this.Side != null && this.Side.Equals(input.Side)) ) && ( this.Symbol == input.Symbol || (this.Symbol != null && this.Symbol.Equals(input.Symbol)) ) && ( this.OrderType == input.OrderType || (this.OrderType != null && this.OrderType.Equals(input.OrderType)) ) && ( this.Price == input.Price || (this.Price != null && this.Price.Equals(input.Price)) ) && ( this.Qty == input.Qty || (this.Qty != null && this.Qty.Equals(input.Qty)) ) && ( this.TimeInForce == input.TimeInForce || (this.TimeInForce != null && this.TimeInForce.Equals(input.TimeInForce)) ) && ( this.OrderStatus == input.OrderStatus || (this.OrderStatus != null && this.OrderStatus.Equals(input.OrderStatus)) ) && ( this.TriggerPrice == input.TriggerPrice || (this.TriggerPrice != null && this.TriggerPrice.Equals(input.TriggerPrice)) ) && ( this.OrderLinkId == input.OrderLinkId || (this.OrderLinkId != null && this.OrderLinkId.Equals(input.OrderLinkId)) ) && ( this.CreatedAt == input.CreatedAt || (this.CreatedAt != null && this.CreatedAt.Equals(input.CreatedAt)) ) && ( this.UpdatedAt == input.UpdatedAt || (this.UpdatedAt != null && this.UpdatedAt.Equals(input.UpdatedAt)) ) && ( this.TakeProfit == input.TakeProfit || (this.TakeProfit != null && this.TakeProfit.Equals(input.TakeProfit)) ) && ( this.StopLoss == input.StopLoss || (this.StopLoss != null && this.StopLoss.Equals(input.StopLoss)) ) && ( this.TpTriggerBy == input.TpTriggerBy || (this.TpTriggerBy != null && this.TpTriggerBy.Equals(input.TpTriggerBy)) ) && ( this.SlTriggerBy == input.SlTriggerBy || (this.SlTriggerBy != null && this.SlTriggerBy.Equals(input.SlTriggerBy)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.StopOrderId != null) hashCode = hashCode * 59 + this.StopOrderId.GetHashCode(); if (this.UserId != null) hashCode = hashCode * 59 + this.UserId.GetHashCode(); if (this.Side != null) hashCode = hashCode * 59 + this.Side.GetHashCode(); if (this.Symbol != null) hashCode = hashCode * 59 + this.Symbol.GetHashCode(); if (this.OrderType != null) hashCode = hashCode * 59 + this.OrderType.GetHashCode(); if (this.Price != null) hashCode = hashCode * 59 + this.Price.GetHashCode(); if (this.Qty != null) hashCode = hashCode * 59 + this.Qty.GetHashCode(); if (this.TimeInForce != null) hashCode = hashCode * 59 + this.TimeInForce.GetHashCode(); if (this.OrderStatus != null) hashCode = hashCode * 59 + this.OrderStatus.GetHashCode(); if (this.TriggerPrice != null) hashCode = hashCode * 59 + this.TriggerPrice.GetHashCode(); if (this.OrderLinkId != null) hashCode = hashCode * 59 + this.OrderLinkId.GetHashCode(); if (this.CreatedAt != null) hashCode = hashCode * 59 + this.CreatedAt.GetHashCode(); if (this.UpdatedAt != null) hashCode = hashCode * 59 + this.UpdatedAt.GetHashCode(); if (this.TakeProfit != null) hashCode = hashCode * 59 + this.TakeProfit.GetHashCode(); if (this.StopLoss != null) hashCode = hashCode * 59 + this.StopLoss.GetHashCode(); if (this.TpTriggerBy != null) hashCode = hashCode * 59 + this.TpTriggerBy.GetHashCode(); if (this.SlTriggerBy != null) hashCode = hashCode * 59 + this.SlTriggerBy.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
using GherkinSpec.TestModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; using System.Threading.Tasks; namespace GherkinSpec.TestAdapter.Execution { public interface IStepsExecutor { Task<TestResult> Execute(TestCase testCase, DiscoveredTestData testData, TestRunContext testRunContext, IMessageLogger logger); } }
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Mistakes.Journal.Api; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; namespace Mistakes.Journal.Api.Migrations { [DbContext(typeof(MistakesJournalContext))] [Migration("20211125203013_RemoveFirstLastNameAddAgeCountryToUser")] partial class RemoveFirstLastNameAddAgeCountryToUser { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn) .HasAnnotation("ProductVersion", "3.1.18") .HasAnnotation("Relational:MaxIdentifierLength", 63); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole<System.Guid>", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("id") .HasColumnType("uuid"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("concurrency_stamp") .HasColumnType("text"); b.Property<string>("Name") .HasColumnName("name") .HasColumnType("character varying(256)") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasColumnName("normalized_name") .HasColumnType("character varying(256)") .HasMaxLength(256); b.HasKey("Id") .HasName("pk_roles"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex"); b.ToTable("role"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnName("id") .HasColumnType("integer") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<string>("ClaimType") .HasColumnName("claim_type") .HasColumnType("text"); b.Property<string>("ClaimValue") .HasColumnName("claim_value") .HasColumnType("text"); b.Property<Guid>("RoleId") .HasColumnName("role_id") .HasColumnType("uuid"); b.HasKey("Id") .HasName("pk_role_claims"); b.HasIndex("RoleId") .HasName("ix_role_claims_role_id"); b.ToTable("role_claim"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnName("id") .HasColumnType("integer") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<string>("ClaimType") .HasColumnName("claim_type") .HasColumnType("text"); b.Property<string>("ClaimValue") .HasColumnName("claim_value") .HasColumnType("text"); b.Property<Guid>("UserId") .HasColumnName("user_id") .HasColumnType("uuid"); b.HasKey("Id") .HasName("pk_user_claims"); b.HasIndex("UserId") .HasName("ix_user_claims_user_id"); b.ToTable("user_claim"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b => { b.Property<string>("LoginProvider") .HasColumnName("login_provider") .HasColumnType("text"); b.Property<string>("ProviderKey") .HasColumnName("provider_key") .HasColumnType("text"); b.Property<string>("ProviderDisplayName") .HasColumnName("provider_display_name") .HasColumnType("text"); b.Property<Guid>("UserId") .HasColumnName("user_id") .HasColumnType("uuid"); b.HasKey("LoginProvider", "ProviderKey") .HasName("pk_user_logins"); b.HasIndex("UserId") .HasName("ix_user_logins_user_id"); b.ToTable("user_login"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b => { b.Property<Guid>("UserId") .HasColumnName("user_id") .HasColumnType("uuid"); b.Property<Guid>("RoleId") .HasColumnName("role_id") .HasColumnType("uuid"); b.HasKey("UserId", "RoleId") .HasName("pk_user_roles"); b.HasIndex("RoleId") .HasName("ix_user_roles_role_id"); b.ToTable("user_role"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b => { b.Property<Guid>("UserId") .HasColumnName("user_id") .HasColumnType("uuid"); b.Property<string>("LoginProvider") .HasColumnName("login_provider") .HasColumnType("text"); b.Property<string>("Name") .HasColumnName("name") .HasColumnType("text"); b.Property<string>("Value") .HasColumnName("value") .HasColumnType("text"); b.HasKey("UserId", "LoginProvider", "Name") .HasName("pk_user_tokens"); b.ToTable("user_token"); }); modelBuilder.Entity("Mistakes.Journal.Api.Logic.Identity.Models.MistakesJournalUser", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("id") .HasColumnType("uuid"); b.Property<int>("AccessFailedCount") .HasColumnName("access_failed_count") .HasColumnType("integer"); b.Property<int>("Age") .HasColumnName("age") .HasColumnType("integer"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnName("concurrency_stamp") .HasColumnType("text"); b.Property<string>("Country") .IsRequired() .HasColumnName("country") .HasColumnType("text"); b.Property<string>("Email") .HasColumnName("email") .HasColumnType("character varying(256)") .HasMaxLength(256); b.Property<bool>("EmailConfirmed") .HasColumnName("email_confirmed") .HasColumnType("boolean"); b.Property<string>("Group") .IsRequired() .ValueGeneratedOnAdd() .HasColumnName("group") .HasColumnType("text") .HasDefaultValue("Default"); b.Property<string>("Language") .IsRequired() .ValueGeneratedOnAdd() .HasColumnName("language") .HasColumnType("text") .HasDefaultValue("EN"); b.Property<bool>("LockoutEnabled") .HasColumnName("lockout_enabled") .HasColumnType("boolean"); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnName("lockout_end") .HasColumnType("timestamp with time zone"); b.Property<string>("NormalizedEmail") .HasColumnName("normalized_email") .HasColumnType("character varying(256)") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasColumnName("normalized_user_name") .HasColumnType("character varying(256)") .HasMaxLength(256); b.Property<string>("PasswordHash") .HasColumnName("password_hash") .HasColumnType("text"); b.Property<string>("PhoneNumber") .HasColumnName("phone_number") .HasColumnType("text"); b.Property<bool>("PhoneNumberConfirmed") .HasColumnName("phone_number_confirmed") .HasColumnType("boolean"); b.Property<string>("SecurityStamp") .HasColumnName("security_stamp") .HasColumnType("text"); b.Property<bool>("TwoFactorEnabled") .HasColumnName("two_factor_enabled") .HasColumnType("boolean"); b.Property<string>("UserName") .HasColumnName("user_name") .HasColumnType("character varying(256)") .HasMaxLength(256); b.Property<bool>("WatchedTutorial") .ValueGeneratedOnAdd() .HasColumnName("watched_tutorial") .HasColumnType("boolean") .HasDefaultValue(false); b.HasKey("Id") .HasName("pk_users"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex"); b.ToTable("user"); }); modelBuilder.Entity("Mistakes.Journal.Api.Logic.Mistakes.Models.Label", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("id") .HasColumnType("uuid"); b.Property<string>("Color") .IsRequired() .HasColumnName("color") .HasColumnType("text"); b.Property<string>("Name") .IsRequired() .HasColumnName("name") .HasColumnType("text"); b.Property<Guid>("UserId") .HasColumnName("user_id") .HasColumnType("uuid"); b.HasKey("Id") .HasName("pk_label"); b.HasIndex("UserId") .HasName("ix_label_user_id"); b.ToTable("label"); }); modelBuilder.Entity("Mistakes.Journal.Api.Logic.Mistakes.Models.Mistake", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("id") .HasColumnType("uuid"); b.Property<DateTime>("CreatedAt") .HasColumnName("created_at") .HasColumnType("timestamp without time zone"); b.Property<string>("Goal") .HasColumnName("goal") .HasColumnType("text"); b.Property<bool>("IsSolved") .ValueGeneratedOnAdd() .HasColumnName("is_solved") .HasColumnType("boolean") .HasDefaultValue(false); b.Property<string>("Name") .IsRequired() .HasColumnName("name") .HasColumnType("text"); b.Property<string>("Priority") .IsRequired() .HasColumnName("priority") .HasColumnType("text"); b.Property<Guid>("UserId") .HasColumnName("user_id") .HasColumnType("uuid"); b.HasKey("Id") .HasName("pk_mistake"); b.HasIndex("UserId") .HasName("ix_mistake_user_id"); b.ToTable("mistake"); }); modelBuilder.Entity("Mistakes.Journal.Api.Logic.Mistakes.Models.MistakeLabel", b => { b.Property<Guid>("MistakeId") .HasColumnName("mistake_id") .HasColumnType("uuid"); b.Property<Guid>("LabelId") .HasColumnName("label_id") .HasColumnType("uuid"); b.HasKey("MistakeId", "LabelId") .HasName("pk_mistake_label"); b.HasIndex("LabelId") .HasName("ix_mistake_label_label_id"); b.ToTable("mistake_label"); }); modelBuilder.Entity("Mistakes.Journal.Api.Logic.Mistakes.Models.Repetition", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("id") .HasColumnType("uuid"); b.Property<Guid>("MistakeId") .HasColumnName("mistake_id") .HasColumnType("uuid"); b.Property<DateTime>("OccurredAt") .HasColumnName("occurred_at") .HasColumnType("timestamp without time zone"); b.HasKey("Id") .HasName("pk_repetition"); b.HasIndex("MistakeId") .HasName("ix_repetition_mistake_id"); b.ToTable("repetition"); }); modelBuilder.Entity("Mistakes.Journal.Api.Logic.Mistakes.Models.Tip", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("id") .HasColumnType("uuid"); b.Property<string>("Content") .IsRequired() .HasColumnName("content") .HasColumnType("text"); b.Property<Guid?>("MistakeId") .HasColumnName("mistake_id") .HasColumnType("uuid"); b.Property<Guid>("UserId") .HasColumnName("user_id") .HasColumnType("uuid"); b.HasKey("Id") .HasName("pk_tip"); b.HasIndex("MistakeId") .HasName("ix_tip_mistake_id"); b.HasIndex("UserId") .HasName("ix_tip_user_id"); b.ToTable("tip"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole<System.Guid>", null) .WithMany() .HasForeignKey("RoleId") .HasConstraintName("fk_role_claims_asp_net_roles_identity_role_guid_id") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b => { b.HasOne("Mistakes.Journal.Api.Logic.Identity.Models.MistakesJournalUser", null) .WithMany() .HasForeignKey("UserId") .HasConstraintName("fk_user_claims_asp_net_users_mistakes_journal_user_id") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b => { b.HasOne("Mistakes.Journal.Api.Logic.Identity.Models.MistakesJournalUser", null) .WithMany() .HasForeignKey("UserId") .HasConstraintName("fk_user_logins_asp_net_users_mistakes_journal_user_id") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole<System.Guid>", null) .WithMany() .HasForeignKey("RoleId") .HasConstraintName("fk_user_roles_asp_net_roles_identity_role_guid_id") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Mistakes.Journal.Api.Logic.Identity.Models.MistakesJournalUser", null) .WithMany() .HasForeignKey("UserId") .HasConstraintName("fk_user_roles_asp_net_users_mistakes_journal_user_id") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b => { b.HasOne("Mistakes.Journal.Api.Logic.Identity.Models.MistakesJournalUser", null) .WithMany() .HasForeignKey("UserId") .HasConstraintName("fk_user_tokens_asp_net_users_mistakes_journal_user_id") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Mistakes.Journal.Api.Logic.Mistakes.Models.Label", b => { b.HasOne("Mistakes.Journal.Api.Logic.Identity.Models.MistakesJournalUser", "User") .WithMany("Labels") .HasForeignKey("UserId") .HasConstraintName("fk_label_users_user_id") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Mistakes.Journal.Api.Logic.Mistakes.Models.Mistake", b => { b.HasOne("Mistakes.Journal.Api.Logic.Identity.Models.MistakesJournalUser", "User") .WithMany("Mistakes") .HasForeignKey("UserId") .HasConstraintName("fk_mistake_users_user_id") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.OwnsOne("Mistakes.Journal.Api.Logic.Mistakes.Models.Mistake+MistakeAdditionalQuestions", "AdditonalQuestions", b1 => { b1.Property<Guid>("MistakeId") .HasColumnName("id") .HasColumnType("uuid"); b1.Property<string>("CanIFixIt") .HasColumnName("can_i_fix_it") .HasColumnType("text"); b1.Property<string>("Consequences") .HasColumnName("consequences") .HasColumnType("text"); b1.Property<string>("OnlyResponsible") .HasColumnName("only_responsible") .HasColumnType("text"); b1.Property<string>("WhatCanIDoBetter") .HasColumnName("what_can_i_do_better") .HasColumnType("text"); b1.Property<string>("WhatDidILearn") .HasColumnName("what_did_i_learn") .HasColumnType("text"); b1.HasKey("MistakeId") .HasName("pk_mistake"); b1.ToTable("mistake"); b1.WithOwner() .HasForeignKey("MistakeId") .HasConstraintName("fk_mistake_additional_questions_mistake_mistake_id"); }); }); modelBuilder.Entity("Mistakes.Journal.Api.Logic.Mistakes.Models.MistakeLabel", b => { b.HasOne("Mistakes.Journal.Api.Logic.Mistakes.Models.Label", "Label") .WithMany("MistakeLabels") .HasForeignKey("LabelId") .HasConstraintName("fk_mistake_label_label_label_id") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Mistakes.Journal.Api.Logic.Mistakes.Models.Mistake", "Mistake") .WithMany("MistakeLabels") .HasForeignKey("MistakeId") .HasConstraintName("fk_mistake_label_mistake_mistake_id") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Mistakes.Journal.Api.Logic.Mistakes.Models.Repetition", b => { b.HasOne("Mistakes.Journal.Api.Logic.Mistakes.Models.Mistake", "Mistake") .WithMany("Repetitions") .HasForeignKey("MistakeId") .HasConstraintName("fk_repetition_mistake_mistake_id1") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Mistakes.Journal.Api.Logic.Mistakes.Models.Tip", b => { b.HasOne("Mistakes.Journal.Api.Logic.Mistakes.Models.Mistake", "Mistake") .WithMany("Tips") .HasForeignKey("MistakeId") .HasConstraintName("fk_tip_mistake_mistake_id1") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Mistakes.Journal.Api.Logic.Identity.Models.MistakesJournalUser", "User") .WithMany("Tips") .HasForeignKey("UserId") .HasConstraintName("fk_tip_users_user_id") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); #pragma warning restore 612, 618 } } }
// 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. using System.Drawing; using System.Runtime.InteropServices; namespace System.Windows.Forms { public partial class Control { /// <summary> /// This is a marshaler object that knows how to marshal IFont to Font /// and back. /// </summary> private class ActiveXFontMarshaler : ICustomMarshaler { private static ActiveXFontMarshaler s_instance; public void CleanUpManagedData(object obj) { } public void CleanUpNativeData(IntPtr pObj) { Marshal.Release(pObj); } internal static ICustomMarshaler GetInstance(string cookie) { if (s_instance == null) { s_instance = new ActiveXFontMarshaler(); } return s_instance; } public int GetNativeDataSize() => -1; // not a value type, so use -1 public IntPtr MarshalManagedToNative(object obj) { Font font = (Font)obj; NativeMethods.tagFONTDESC fontDesc = new NativeMethods.tagFONTDESC(); NativeMethods.LOGFONTW logFont = NativeMethods.LOGFONTW.FromFont(font); fontDesc.lpstrName = font.Name; fontDesc.cySize = (long)(font.SizeInPoints * 10000); fontDesc.sWeight = (short)logFont.lfWeight; fontDesc.sCharset = logFont.lfCharSet; fontDesc.fItalic = font.Italic; fontDesc.fUnderline = font.Underline; fontDesc.fStrikethrough = font.Strikeout; Guid iid = typeof(UnsafeNativeMethods.IFont).GUID; UnsafeNativeMethods.IFont oleFont = UnsafeNativeMethods.OleCreateFontIndirect(fontDesc, ref iid); IntPtr pFont = Marshal.GetIUnknownForObject(oleFont); int hr = Marshal.QueryInterface(pFont, ref iid, out IntPtr pIFont); Marshal.Release(pFont); if (NativeMethods.Failed(hr)) { Marshal.ThrowExceptionForHR(hr); } return pIFont; } public object MarshalNativeToManaged(IntPtr pObj) { UnsafeNativeMethods.IFont nativeFont = (UnsafeNativeMethods.IFont)Marshal.GetObjectForIUnknown(pObj); IntPtr hfont = nativeFont.GetHFont(); Font font; try { font = Font.FromHfont(hfont); } catch (Exception e) { if (ClientUtils.IsSecurityOrCriticalException(e)) { throw; } font = DefaultFont; } return font; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Telerik.Sitefinity.Frontend.Search { /// <summary> /// Defines different word mode for indexing service to search within /// </summary> public enum WordsMode { AllWords = 0, AnyWord = 1 } }
//---------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation. // All rights reserved. // // This code is licensed under the MIT License. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files(the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and / or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // //------------------------------------------------------------------------------ using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Flows; using System; using System.Collections.Generic; using System.Globalization; using System.Threading.Tasks; using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Helpers; using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.OAuth2; using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Platform; namespace Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Flows { internal class AcquireTokenInteractiveHandler : AcquireTokenHandlerBase { internal AuthorizationResult authorizationResult; private readonly Uri redirectUri; private readonly string redirectUriRequestParameter; private readonly IPlatformParameters authorizationParameters; private readonly string extraQueryParameters; private readonly IWebUI webUi; private readonly UserIdentifier userId; private readonly string claims; public AcquireTokenInteractiveHandler(RequestData requestData, Uri redirectUri, IPlatformParameters parameters, UserIdentifier userId, string extraQueryParameters, IWebUI webUI, string claims) : base(requestData) { this.redirectUri = platformInformation.ValidateRedirectUri(redirectUri, this.CallState); if (!string.IsNullOrWhiteSpace(this.redirectUri.Fragment)) { throw new ArgumentException(AdalErrorMessage.RedirectUriContainsFragment, "redirectUri"); } this.authorizationParameters = parameters; this.redirectUriRequestParameter = platformInformation.GetRedirectUriAsString(this.redirectUri, this.CallState); if (userId == null) { throw new ArgumentNullException("userId", AdalErrorMessage.SpecifyAnyUser); } this.userId = userId; if (!string.IsNullOrEmpty(extraQueryParameters) && extraQueryParameters[0] == '&') { extraQueryParameters = extraQueryParameters.Substring(1); } this.extraQueryParameters = extraQueryParameters; this.webUi = webUI; this.UniqueId = userId.UniqueId; this.DisplayableId = userId.DisplayableId; this.UserIdentifierType = userId.Type; this.SupportADFS = true; if (!String.IsNullOrEmpty(claims)) { this.LoadFromCache = false; var msg = "Claims present. Skip cache lookup."; CallState.Logger.Verbose(CallState, msg); CallState.Logger.VerbosePii(CallState, msg); this.claims = claims; this.brokerParameters[BrokerParameter.Claims] = claims; } else { this.LoadFromCache = (requestData.TokenCache != null && parameters != null && platformInformation.GetCacheLoadPolicy(parameters)); } this.brokerParameters[BrokerParameter.Force] = "NO"; if (userId != UserIdentifier.AnyUser) { this.brokerParameters[BrokerParameter.Username] = userId.Id; } else { this.brokerParameters[BrokerParameter.Username] = string.Empty; } this.brokerParameters[BrokerParameter.UsernameType] = userId.Type.ToString(); this.brokerParameters[BrokerParameter.RedirectUri] = this.redirectUri.AbsoluteUri; this.brokerParameters[BrokerParameter.ExtraQp] = extraQueryParameters; brokerHelper.PlatformParameters = authorizationParameters; } private static string ReplaceHost(string original, string newHost) { return new UriBuilder(original) { Host = newHost }.Uri.ToString(); } protected override async Task PreTokenRequestAsync() { await base.PreTokenRequestAsync().ConfigureAwait(false); // We do not have async interactive API in .NET, so we call this synchronous method instead. await this.AcquireAuthorizationAsync().ConfigureAwait(false); this.VerifyAuthorizationResult(); if(!string.IsNullOrEmpty(authorizationResult.CloudInstanceHost)) { var updatedAuthority = ReplaceHost(Authenticator.Authority, authorizationResult.CloudInstanceHost); await UpdateAuthorityAsync(updatedAuthority).ConfigureAwait(false); } } internal async Task AcquireAuthorizationAsync() { Uri authorizationUri = this.CreateAuthorizationUri(); this.authorizationResult = await this.webUi.AcquireAuthorizationAsync(authorizationUri, this.redirectUri, this.CallState).ConfigureAwait(false); } internal async Task<Uri> CreateAuthorizationUriAsync(Guid correlationId) { this.CallState.CorrelationId = correlationId; await this.Authenticator.UpdateFromTemplateAsync(this.CallState).ConfigureAwait(false); return this.CreateAuthorizationUri(); } protected override void AddAditionalRequestParameters(DictionaryRequestParameters requestParameters) { requestParameters[OAuthParameter.GrantType] = OAuthGrantType.AuthorizationCode; requestParameters[OAuthParameter.Code] = this.authorizationResult.Code; requestParameters[OAuthParameter.RedirectUri] = this.redirectUriRequestParameter; } protected override async Task PostTokenRequestAsync(AuthenticationResultEx resultEx) { await base.PostTokenRequestAsync(resultEx).ConfigureAwait(false); if ((this.DisplayableId == null && this.UniqueId == null) || this.UserIdentifierType == UserIdentifierType.OptionalDisplayableId) { return; } string uniqueId = (resultEx.Result.UserInfo != null && resultEx.Result.UserInfo.UniqueId != null) ? resultEx.Result.UserInfo.UniqueId : "NULL"; string displayableId = (resultEx.Result.UserInfo != null) ? resultEx.Result.UserInfo.DisplayableId : "NULL"; if (this.UserIdentifierType == UserIdentifierType.UniqueId && string.Compare(uniqueId, this.UniqueId, StringComparison.Ordinal) != 0) { throw new AdalUserMismatchException(this.UniqueId, uniqueId); } if (this.UserIdentifierType == UserIdentifierType.RequiredDisplayableId && string.Compare(displayableId, this.DisplayableId, StringComparison.OrdinalIgnoreCase) != 0) { throw new AdalUserMismatchException(this.DisplayableId, displayableId); } } private Uri CreateAuthorizationUri() { string loginHint = null; if (!userId.IsAnyUser && (userId.Type == UserIdentifierType.OptionalDisplayableId || userId.Type == UserIdentifierType.RequiredDisplayableId)) { loginHint = userId.Id; } IRequestParameters requestParameters = this.CreateAuthorizationRequest(loginHint); return new Uri(new Uri(this.Authenticator.AuthorizationUri), "?" + requestParameters); } private DictionaryRequestParameters CreateAuthorizationRequest(string loginHint) { var authorizationRequestParameters = new DictionaryRequestParameters(this.Resource, this.ClientKey); authorizationRequestParameters[OAuthParameter.ResponseType] = OAuthResponseType.Code; authorizationRequestParameters[OAuthParameter.HasChrome] = "1"; authorizationRequestParameters[OAuthParameter.RedirectUri] = this.redirectUriRequestParameter; if (!string.IsNullOrWhiteSpace(loginHint)) { authorizationRequestParameters[OAuthParameter.LoginHint] = loginHint; } if (!string.IsNullOrWhiteSpace(claims)) { authorizationRequestParameters["claims"] = claims; } if (this.CallState != null && this.CallState.CorrelationId != Guid.Empty) { authorizationRequestParameters[OAuthParameter.CorrelationId] = this.CallState.CorrelationId.ToString(); } if (this.authorizationParameters != null) { platformInformation.AddPromptBehaviorQueryParameter(this.authorizationParameters, authorizationRequestParameters); } IDictionary<string, string> adalIdParameters = AdalIdHelper.GetAdalIdParameters(); foreach (KeyValuePair<string, string> kvp in adalIdParameters) { authorizationRequestParameters[kvp.Key] = kvp.Value; } if (!string.IsNullOrWhiteSpace(extraQueryParameters)) { // Checks for extraQueryParameters duplicating standard parameters Dictionary<string, string> kvps = EncodingHelper.ParseKeyValueList(extraQueryParameters, '&', false, this.CallState); foreach (KeyValuePair<string, string> kvp in kvps) { if (authorizationRequestParameters.ContainsKey(kvp.Key)) { throw new AdalException(AdalError.DuplicateQueryParameter, string.Format(CultureInfo.CurrentCulture, AdalErrorMessage.DuplicateQueryParameterTemplate, kvp.Key)); } } authorizationRequestParameters.ExtraQueryParameter = extraQueryParameters; } return authorizationRequestParameters; } private void VerifyAuthorizationResult() { if (this.authorizationResult.Error == OAuthError.LoginRequired) { throw new AdalException(AdalError.UserInteractionRequired); } if (this.authorizationResult.Status != AuthorizationStatus.Success) { throw new AdalServiceException(this.authorizationResult.Error, this.authorizationResult.ErrorDescription); } } protected override void UpdateBrokerParameters(IDictionary<string, string> parameters) { Uri uri = new Uri(this.authorizationResult.Code); string query = EncodingHelper.UrlDecode(uri.Query); Dictionary<string, string> kvps = EncodingHelper.ParseKeyValueList(query, '&', false, this.CallState); parameters["username"] = kvps["username"]; } protected override bool BrokerInvocationRequired() { if (this.authorizationResult != null && !string.IsNullOrEmpty(this.authorizationResult.Code) && this.authorizationResult.Code.StartsWith("msauth://", StringComparison.OrdinalIgnoreCase)) { this.brokerParameters[BrokerParameter.BrokerInstallUrl] = this.authorizationResult.Code; return true; } return false; } } }
/* * Copyright 2010-2013 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. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.CloudFront.Model { /// <summary> /// Container for the parameters to the CreateDistribution operation. /// <para> Create a new distribution. </para> /// </summary> public partial class CreateDistributionRequest : AmazonCloudFrontRequest { private DistributionConfig distributionConfig; /// <summary> /// The distribution's configuration information. /// /// </summary> public DistributionConfig DistributionConfig { get { return this.distributionConfig; } set { this.distributionConfig = value; } } // Check to see if DistributionConfig property is set internal bool IsSetDistributionConfig() { return this.distributionConfig != null; } } }
using System; using GalaSoft.MvvmLight; namespace TEditXNA.Terraria { [Serializable] public class TileEntity : ObservableObject { private byte _type; private int _id; private Int16 _x; private Int16 _y; //data for when this is a dummy private Int16 _npc; //data for this is a item frame private int _netId; private byte _prefix; private Int16 _stackSize; //data for Logic Sensor private byte _logicCheck; private bool _on; public byte Type { get { return _type; } set { Set("Type", ref _type, value); } } public int Id { get { return _id; } set { Set("Id", ref _id, value); } } public Int16 PosX { get { return _x; } set { Set("PosX", ref _x, value); } } public Int16 PosY { get { return _y; } set { Set("PosY", ref _y, value); } } public Int16 Npc { get { return _npc; } set { Set("Npc", ref _npc, value); } } public int NetId { get { return _netId; } set { Set("NetId", ref _netId, value); } } public byte Prefix { get { return _prefix; } set { Set("Prefix", ref _prefix, value); } } public Int16 StackSize { get { return _stackSize; } set { Set("StackSize", ref _stackSize, value); } } public byte LogicCheck { get { return _logicCheck; } set { Set("LogicCheck", ref _logicCheck, value); } } public bool On { get { return _on; } set { Set("On", ref _on, value); } } public TileEntity Copy() { var frame = new TileEntity(); frame.Type = Type; frame.PosX = PosX; frame.PosY = PosY; switch (Type) { case 0: frame.Npc = Npc; break; case 1: frame.NetId = NetId; frame.StackSize = StackSize; frame.Prefix = Prefix; break; case 2: frame.LogicCheck = LogicCheck; frame.On = On; break; } return frame; } } }
/* * 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 appstream-2016-12-01.normal.json service model. */ using System; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.AppStream.Model; using Amazon.AppStream.Model.Internal.MarshallTransformations; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Transform; namespace Amazon.AppStream { /// <summary> /// Implementation for accessing AppStream /// /// Amazon AppStream 2.0 /// <para> /// You can use Amazon AppStream 2.0 to stream desktop applications to any device running /// a web browser, without rewriting them. /// </para> /// </summary> public partial class AmazonAppStreamClient : AmazonServiceClient, IAmazonAppStream { #region Constructors /// <summary> /// Constructs AmazonAppStreamClient 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 AmazonAppStreamClient() : base(FallbackCredentialsFactory.GetCredentials(), new AmazonAppStreamConfig()) { } /// <summary> /// Constructs AmazonAppStreamClient 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 AmazonAppStreamClient(RegionEndpoint region) : base(FallbackCredentialsFactory.GetCredentials(), new AmazonAppStreamConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonAppStreamClient 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 AmazonAppStreamClient Configuration Object</param> public AmazonAppStreamClient(AmazonAppStreamConfig config) : base(FallbackCredentialsFactory.GetCredentials(), config) { } /// <summary> /// Constructs AmazonAppStreamClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> public AmazonAppStreamClient(AWSCredentials credentials) : this(credentials, new AmazonAppStreamConfig()) { } /// <summary> /// Constructs AmazonAppStreamClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="region">The region to connect.</param> public AmazonAppStreamClient(AWSCredentials credentials, RegionEndpoint region) : this(credentials, new AmazonAppStreamConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonAppStreamClient with AWS Credentials and an /// AmazonAppStreamClient Configuration object. /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="clientConfig">The AmazonAppStreamClient Configuration Object</param> public AmazonAppStreamClient(AWSCredentials credentials, AmazonAppStreamConfig clientConfig) : base(credentials, clientConfig) { } /// <summary> /// Constructs AmazonAppStreamClient 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 AmazonAppStreamClient(string awsAccessKeyId, string awsSecretAccessKey) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonAppStreamConfig()) { } /// <summary> /// Constructs AmazonAppStreamClient 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 AmazonAppStreamClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonAppStreamConfig() {RegionEndpoint=region}) { } /// <summary> /// Constructs AmazonAppStreamClient with AWS Access Key ID, AWS Secret Key and an /// AmazonAppStreamClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="clientConfig">The AmazonAppStreamClient Configuration Object</param> public AmazonAppStreamClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonAppStreamConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, clientConfig) { } /// <summary> /// Constructs AmazonAppStreamClient 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 AmazonAppStreamClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonAppStreamConfig()) { } /// <summary> /// Constructs AmazonAppStreamClient 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 AmazonAppStreamClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonAppStreamConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonAppStreamClient with AWS Access Key ID, AWS Secret Key and an /// AmazonAppStreamClient 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 AmazonAppStreamClient Configuration Object</param> public AmazonAppStreamClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonAppStreamConfig 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 AssociateFleet /// <summary> /// Associates the specified fleet with the specified stack. /// </summary> /// <param name="request">Container for the necessary parameters to execute the AssociateFleet service method.</param> /// /// <returns>The response from the AssociateFleet service method, as returned by AppStream.</returns> /// <exception cref="Amazon.AppStream.Model.ConcurrentModificationException"> /// An API error occurred. Wait a few minutes and try again. /// </exception> /// <exception cref="Amazon.AppStream.Model.IncompatibleImageException"> /// The image does not support storage connectors. /// </exception> /// <exception cref="Amazon.AppStream.Model.InvalidAccountStatusException"> /// The resource cannot be created because your AWS account is suspended. For assistance, /// contact AWS Support. /// </exception> /// <exception cref="Amazon.AppStream.Model.LimitExceededException"> /// The requested limit exceeds the permitted limit for an account. /// </exception> /// <exception cref="Amazon.AppStream.Model.OperationNotPermittedException"> /// The attempted operation is not permitted. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceNotFoundException"> /// The specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/AssociateFleet">REST API Reference for AssociateFleet Operation</seealso> public virtual AssociateFleetResponse AssociateFleet(AssociateFleetRequest request) { var marshaller = AssociateFleetRequestMarshaller.Instance; var unmarshaller = AssociateFleetResponseUnmarshaller.Instance; return Invoke<AssociateFleetRequest,AssociateFleetResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the AssociateFleet operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AssociateFleet 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/appstream-2016-12-01/AssociateFleet">REST API Reference for AssociateFleet Operation</seealso> public virtual Task<AssociateFleetResponse> AssociateFleetAsync(AssociateFleetRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = AssociateFleetRequestMarshaller.Instance; var unmarshaller = AssociateFleetResponseUnmarshaller.Instance; return InvokeAsync<AssociateFleetRequest,AssociateFleetResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CopyImage /// <summary> /// Copies the image within the same region or to a new region within the same AWS account. /// Note that any tags you added to the image will not be copied. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CopyImage service method.</param> /// /// <returns>The response from the CopyImage service method, as returned by AppStream.</returns> /// <exception cref="Amazon.AppStream.Model.IncompatibleImageException"> /// The image does not support storage connectors. /// </exception> /// <exception cref="Amazon.AppStream.Model.InvalidAccountStatusException"> /// The resource cannot be created because your AWS account is suspended. For assistance, /// contact AWS Support. /// </exception> /// <exception cref="Amazon.AppStream.Model.LimitExceededException"> /// The requested limit exceeds the permitted limit for an account. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceAlreadyExistsException"> /// The specified resource already exists. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceNotAvailableException"> /// The specified resource exists and is not in use, but isn't available. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceNotFoundException"> /// The specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/CopyImage">REST API Reference for CopyImage Operation</seealso> public virtual CopyImageResponse CopyImage(CopyImageRequest request) { var marshaller = CopyImageRequestMarshaller.Instance; var unmarshaller = CopyImageResponseUnmarshaller.Instance; return Invoke<CopyImageRequest,CopyImageResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CopyImage operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CopyImage 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/appstream-2016-12-01/CopyImage">REST API Reference for CopyImage Operation</seealso> public virtual Task<CopyImageResponse> CopyImageAsync(CopyImageRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = CopyImageRequestMarshaller.Instance; var unmarshaller = CopyImageResponseUnmarshaller.Instance; return InvokeAsync<CopyImageRequest,CopyImageResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateDirectoryConfig /// <summary> /// Creates a directory configuration. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateDirectoryConfig service method.</param> /// /// <returns>The response from the CreateDirectoryConfig service method, as returned by AppStream.</returns> /// <exception cref="Amazon.AppStream.Model.InvalidAccountStatusException"> /// The resource cannot be created because your AWS account is suspended. For assistance, /// contact AWS Support. /// </exception> /// <exception cref="Amazon.AppStream.Model.LimitExceededException"> /// The requested limit exceeds the permitted limit for an account. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceAlreadyExistsException"> /// The specified resource already exists. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/CreateDirectoryConfig">REST API Reference for CreateDirectoryConfig Operation</seealso> public virtual CreateDirectoryConfigResponse CreateDirectoryConfig(CreateDirectoryConfigRequest request) { var marshaller = CreateDirectoryConfigRequestMarshaller.Instance; var unmarshaller = CreateDirectoryConfigResponseUnmarshaller.Instance; return Invoke<CreateDirectoryConfigRequest,CreateDirectoryConfigResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateDirectoryConfig operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateDirectoryConfig 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/appstream-2016-12-01/CreateDirectoryConfig">REST API Reference for CreateDirectoryConfig Operation</seealso> public virtual Task<CreateDirectoryConfigResponse> CreateDirectoryConfigAsync(CreateDirectoryConfigRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = CreateDirectoryConfigRequestMarshaller.Instance; var unmarshaller = CreateDirectoryConfigResponseUnmarshaller.Instance; return InvokeAsync<CreateDirectoryConfigRequest,CreateDirectoryConfigResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateFleet /// <summary> /// Creates a fleet. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateFleet service method.</param> /// /// <returns>The response from the CreateFleet service method, as returned by AppStream.</returns> /// <exception cref="Amazon.AppStream.Model.ConcurrentModificationException"> /// An API error occurred. Wait a few minutes and try again. /// </exception> /// <exception cref="Amazon.AppStream.Model.IncompatibleImageException"> /// The image does not support storage connectors. /// </exception> /// <exception cref="Amazon.AppStream.Model.InvalidAccountStatusException"> /// The resource cannot be created because your AWS account is suspended. For assistance, /// contact AWS Support. /// </exception> /// <exception cref="Amazon.AppStream.Model.InvalidParameterCombinationException"> /// Indicates an incorrect combination of parameters, or a missing parameter. /// </exception> /// <exception cref="Amazon.AppStream.Model.InvalidRoleException"> /// The specified role is invalid. /// </exception> /// <exception cref="Amazon.AppStream.Model.LimitExceededException"> /// The requested limit exceeds the permitted limit for an account. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceAlreadyExistsException"> /// The specified resource already exists. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceNotAvailableException"> /// The specified resource exists and is not in use, but isn't available. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceNotFoundException"> /// The specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/CreateFleet">REST API Reference for CreateFleet Operation</seealso> public virtual CreateFleetResponse CreateFleet(CreateFleetRequest request) { var marshaller = CreateFleetRequestMarshaller.Instance; var unmarshaller = CreateFleetResponseUnmarshaller.Instance; return Invoke<CreateFleetRequest,CreateFleetResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateFleet operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateFleet 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/appstream-2016-12-01/CreateFleet">REST API Reference for CreateFleet Operation</seealso> public virtual Task<CreateFleetResponse> CreateFleetAsync(CreateFleetRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = CreateFleetRequestMarshaller.Instance; var unmarshaller = CreateFleetResponseUnmarshaller.Instance; return InvokeAsync<CreateFleetRequest,CreateFleetResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateImageBuilder /// <summary> /// Creates an image builder. /// /// /// <para> /// The initial state of the builder is <code>PENDING</code>. When it is ready, the state /// is <code>RUNNING</code>. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateImageBuilder service method.</param> /// /// <returns>The response from the CreateImageBuilder service method, as returned by AppStream.</returns> /// <exception cref="Amazon.AppStream.Model.ConcurrentModificationException"> /// An API error occurred. Wait a few minutes and try again. /// </exception> /// <exception cref="Amazon.AppStream.Model.IncompatibleImageException"> /// The image does not support storage connectors. /// </exception> /// <exception cref="Amazon.AppStream.Model.InvalidAccountStatusException"> /// The resource cannot be created because your AWS account is suspended. For assistance, /// contact AWS Support. /// </exception> /// <exception cref="Amazon.AppStream.Model.InvalidParameterCombinationException"> /// Indicates an incorrect combination of parameters, or a missing parameter. /// </exception> /// <exception cref="Amazon.AppStream.Model.InvalidRoleException"> /// The specified role is invalid. /// </exception> /// <exception cref="Amazon.AppStream.Model.LimitExceededException"> /// The requested limit exceeds the permitted limit for an account. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceAlreadyExistsException"> /// The specified resource already exists. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceNotAvailableException"> /// The specified resource exists and is not in use, but isn't available. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceNotFoundException"> /// The specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/CreateImageBuilder">REST API Reference for CreateImageBuilder Operation</seealso> public virtual CreateImageBuilderResponse CreateImageBuilder(CreateImageBuilderRequest request) { var marshaller = CreateImageBuilderRequestMarshaller.Instance; var unmarshaller = CreateImageBuilderResponseUnmarshaller.Instance; return Invoke<CreateImageBuilderRequest,CreateImageBuilderResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateImageBuilder operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateImageBuilder 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/appstream-2016-12-01/CreateImageBuilder">REST API Reference for CreateImageBuilder Operation</seealso> public virtual Task<CreateImageBuilderResponse> CreateImageBuilderAsync(CreateImageBuilderRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = CreateImageBuilderRequestMarshaller.Instance; var unmarshaller = CreateImageBuilderResponseUnmarshaller.Instance; return InvokeAsync<CreateImageBuilderRequest,CreateImageBuilderResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateImageBuilderStreamingURL /// <summary> /// Creates a URL to start an image builder streaming session. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateImageBuilderStreamingURL service method.</param> /// /// <returns>The response from the CreateImageBuilderStreamingURL service method, as returned by AppStream.</returns> /// <exception cref="Amazon.AppStream.Model.OperationNotPermittedException"> /// The attempted operation is not permitted. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceNotFoundException"> /// The specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/CreateImageBuilderStreamingURL">REST API Reference for CreateImageBuilderStreamingURL Operation</seealso> public virtual CreateImageBuilderStreamingURLResponse CreateImageBuilderStreamingURL(CreateImageBuilderStreamingURLRequest request) { var marshaller = CreateImageBuilderStreamingURLRequestMarshaller.Instance; var unmarshaller = CreateImageBuilderStreamingURLResponseUnmarshaller.Instance; return Invoke<CreateImageBuilderStreamingURLRequest,CreateImageBuilderStreamingURLResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateImageBuilderStreamingURL operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateImageBuilderStreamingURL 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/appstream-2016-12-01/CreateImageBuilderStreamingURL">REST API Reference for CreateImageBuilderStreamingURL Operation</seealso> public virtual Task<CreateImageBuilderStreamingURLResponse> CreateImageBuilderStreamingURLAsync(CreateImageBuilderStreamingURLRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = CreateImageBuilderStreamingURLRequestMarshaller.Instance; var unmarshaller = CreateImageBuilderStreamingURLResponseUnmarshaller.Instance; return InvokeAsync<CreateImageBuilderStreamingURLRequest,CreateImageBuilderStreamingURLResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateStack /// <summary> /// Creates a stack. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateStack service method.</param> /// /// <returns>The response from the CreateStack service method, as returned by AppStream.</returns> /// <exception cref="Amazon.AppStream.Model.ConcurrentModificationException"> /// An API error occurred. Wait a few minutes and try again. /// </exception> /// <exception cref="Amazon.AppStream.Model.InvalidAccountStatusException"> /// The resource cannot be created because your AWS account is suspended. For assistance, /// contact AWS Support. /// </exception> /// <exception cref="Amazon.AppStream.Model.InvalidParameterCombinationException"> /// Indicates an incorrect combination of parameters, or a missing parameter. /// </exception> /// <exception cref="Amazon.AppStream.Model.InvalidRoleException"> /// The specified role is invalid. /// </exception> /// <exception cref="Amazon.AppStream.Model.LimitExceededException"> /// The requested limit exceeds the permitted limit for an account. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceAlreadyExistsException"> /// The specified resource already exists. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceNotFoundException"> /// The specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/CreateStack">REST API Reference for CreateStack Operation</seealso> public virtual CreateStackResponse CreateStack(CreateStackRequest request) { var marshaller = CreateStackRequestMarshaller.Instance; var unmarshaller = CreateStackResponseUnmarshaller.Instance; return Invoke<CreateStackRequest,CreateStackResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateStack operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateStack 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/appstream-2016-12-01/CreateStack">REST API Reference for CreateStack Operation</seealso> public virtual Task<CreateStackResponse> CreateStackAsync(CreateStackRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = CreateStackRequestMarshaller.Instance; var unmarshaller = CreateStackResponseUnmarshaller.Instance; return InvokeAsync<CreateStackRequest,CreateStackResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateStreamingURL /// <summary> /// Creates a URL to start a streaming session for the specified user. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateStreamingURL service method.</param> /// /// <returns>The response from the CreateStreamingURL service method, as returned by AppStream.</returns> /// <exception cref="Amazon.AppStream.Model.InvalidParameterCombinationException"> /// Indicates an incorrect combination of parameters, or a missing parameter. /// </exception> /// <exception cref="Amazon.AppStream.Model.OperationNotPermittedException"> /// The attempted operation is not permitted. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceNotAvailableException"> /// The specified resource exists and is not in use, but isn't available. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceNotFoundException"> /// The specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/CreateStreamingURL">REST API Reference for CreateStreamingURL Operation</seealso> public virtual CreateStreamingURLResponse CreateStreamingURL(CreateStreamingURLRequest request) { var marshaller = CreateStreamingURLRequestMarshaller.Instance; var unmarshaller = CreateStreamingURLResponseUnmarshaller.Instance; return Invoke<CreateStreamingURLRequest,CreateStreamingURLResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateStreamingURL operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateStreamingURL 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/appstream-2016-12-01/CreateStreamingURL">REST API Reference for CreateStreamingURL Operation</seealso> public virtual Task<CreateStreamingURLResponse> CreateStreamingURLAsync(CreateStreamingURLRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = CreateStreamingURLRequestMarshaller.Instance; var unmarshaller = CreateStreamingURLResponseUnmarshaller.Instance; return InvokeAsync<CreateStreamingURLRequest,CreateStreamingURLResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteDirectoryConfig /// <summary> /// Deletes the specified directory configuration. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteDirectoryConfig service method.</param> /// /// <returns>The response from the DeleteDirectoryConfig service method, as returned by AppStream.</returns> /// <exception cref="Amazon.AppStream.Model.ResourceInUseException"> /// The specified resource is in use. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceNotFoundException"> /// The specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/DeleteDirectoryConfig">REST API Reference for DeleteDirectoryConfig Operation</seealso> public virtual DeleteDirectoryConfigResponse DeleteDirectoryConfig(DeleteDirectoryConfigRequest request) { var marshaller = DeleteDirectoryConfigRequestMarshaller.Instance; var unmarshaller = DeleteDirectoryConfigResponseUnmarshaller.Instance; return Invoke<DeleteDirectoryConfigRequest,DeleteDirectoryConfigResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteDirectoryConfig operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteDirectoryConfig 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/appstream-2016-12-01/DeleteDirectoryConfig">REST API Reference for DeleteDirectoryConfig Operation</seealso> public virtual Task<DeleteDirectoryConfigResponse> DeleteDirectoryConfigAsync(DeleteDirectoryConfigRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = DeleteDirectoryConfigRequestMarshaller.Instance; var unmarshaller = DeleteDirectoryConfigResponseUnmarshaller.Instance; return InvokeAsync<DeleteDirectoryConfigRequest,DeleteDirectoryConfigResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteFleet /// <summary> /// Deletes the specified fleet. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteFleet service method.</param> /// /// <returns>The response from the DeleteFleet service method, as returned by AppStream.</returns> /// <exception cref="Amazon.AppStream.Model.ConcurrentModificationException"> /// An API error occurred. Wait a few minutes and try again. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceInUseException"> /// The specified resource is in use. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceNotFoundException"> /// The specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/DeleteFleet">REST API Reference for DeleteFleet Operation</seealso> public virtual DeleteFleetResponse DeleteFleet(DeleteFleetRequest request) { var marshaller = DeleteFleetRequestMarshaller.Instance; var unmarshaller = DeleteFleetResponseUnmarshaller.Instance; return Invoke<DeleteFleetRequest,DeleteFleetResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteFleet operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteFleet 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/appstream-2016-12-01/DeleteFleet">REST API Reference for DeleteFleet Operation</seealso> public virtual Task<DeleteFleetResponse> DeleteFleetAsync(DeleteFleetRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = DeleteFleetRequestMarshaller.Instance; var unmarshaller = DeleteFleetResponseUnmarshaller.Instance; return InvokeAsync<DeleteFleetRequest,DeleteFleetResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteImage /// <summary> /// Deletes the specified image. You cannot delete an image that is currently in use. /// After you delete an image, you cannot provision new capacity using the image. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteImage service method.</param> /// /// <returns>The response from the DeleteImage service method, as returned by AppStream.</returns> /// <exception cref="Amazon.AppStream.Model.ConcurrentModificationException"> /// An API error occurred. Wait a few minutes and try again. /// </exception> /// <exception cref="Amazon.AppStream.Model.OperationNotPermittedException"> /// The attempted operation is not permitted. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceInUseException"> /// The specified resource is in use. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceNotFoundException"> /// The specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/DeleteImage">REST API Reference for DeleteImage Operation</seealso> public virtual DeleteImageResponse DeleteImage(DeleteImageRequest request) { var marshaller = DeleteImageRequestMarshaller.Instance; var unmarshaller = DeleteImageResponseUnmarshaller.Instance; return Invoke<DeleteImageRequest,DeleteImageResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteImage operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteImage 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/appstream-2016-12-01/DeleteImage">REST API Reference for DeleteImage Operation</seealso> public virtual Task<DeleteImageResponse> DeleteImageAsync(DeleteImageRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = DeleteImageRequestMarshaller.Instance; var unmarshaller = DeleteImageResponseUnmarshaller.Instance; return InvokeAsync<DeleteImageRequest,DeleteImageResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteImageBuilder /// <summary> /// Deletes the specified image builder and releases the capacity. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteImageBuilder service method.</param> /// /// <returns>The response from the DeleteImageBuilder service method, as returned by AppStream.</returns> /// <exception cref="Amazon.AppStream.Model.ConcurrentModificationException"> /// An API error occurred. Wait a few minutes and try again. /// </exception> /// <exception cref="Amazon.AppStream.Model.OperationNotPermittedException"> /// The attempted operation is not permitted. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceNotFoundException"> /// The specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/DeleteImageBuilder">REST API Reference for DeleteImageBuilder Operation</seealso> public virtual DeleteImageBuilderResponse DeleteImageBuilder(DeleteImageBuilderRequest request) { var marshaller = DeleteImageBuilderRequestMarshaller.Instance; var unmarshaller = DeleteImageBuilderResponseUnmarshaller.Instance; return Invoke<DeleteImageBuilderRequest,DeleteImageBuilderResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteImageBuilder operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteImageBuilder 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/appstream-2016-12-01/DeleteImageBuilder">REST API Reference for DeleteImageBuilder Operation</seealso> public virtual Task<DeleteImageBuilderResponse> DeleteImageBuilderAsync(DeleteImageBuilderRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = DeleteImageBuilderRequestMarshaller.Instance; var unmarshaller = DeleteImageBuilderResponseUnmarshaller.Instance; return InvokeAsync<DeleteImageBuilderRequest,DeleteImageBuilderResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteStack /// <summary> /// Deletes the specified stack. After this operation completes, the environment can no /// longer be activated and any reservations made for the stack are released. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteStack service method.</param> /// /// <returns>The response from the DeleteStack service method, as returned by AppStream.</returns> /// <exception cref="Amazon.AppStream.Model.ConcurrentModificationException"> /// An API error occurred. Wait a few minutes and try again. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceInUseException"> /// The specified resource is in use. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceNotFoundException"> /// The specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/DeleteStack">REST API Reference for DeleteStack Operation</seealso> public virtual DeleteStackResponse DeleteStack(DeleteStackRequest request) { var marshaller = DeleteStackRequestMarshaller.Instance; var unmarshaller = DeleteStackResponseUnmarshaller.Instance; return Invoke<DeleteStackRequest,DeleteStackResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteStack operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteStack 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/appstream-2016-12-01/DeleteStack">REST API Reference for DeleteStack Operation</seealso> public virtual Task<DeleteStackResponse> DeleteStackAsync(DeleteStackRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = DeleteStackRequestMarshaller.Instance; var unmarshaller = DeleteStackResponseUnmarshaller.Instance; return InvokeAsync<DeleteStackRequest,DeleteStackResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeDirectoryConfigs /// <summary> /// Describes the specified directory configurations. Note that although the response /// syntax in this topic includes the account password, this password is not returned /// in the actual response. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeDirectoryConfigs service method.</param> /// /// <returns>The response from the DescribeDirectoryConfigs service method, as returned by AppStream.</returns> /// <exception cref="Amazon.AppStream.Model.ResourceNotFoundException"> /// The specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/DescribeDirectoryConfigs">REST API Reference for DescribeDirectoryConfigs Operation</seealso> public virtual DescribeDirectoryConfigsResponse DescribeDirectoryConfigs(DescribeDirectoryConfigsRequest request) { var marshaller = DescribeDirectoryConfigsRequestMarshaller.Instance; var unmarshaller = DescribeDirectoryConfigsResponseUnmarshaller.Instance; return Invoke<DescribeDirectoryConfigsRequest,DescribeDirectoryConfigsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeDirectoryConfigs operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeDirectoryConfigs 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/appstream-2016-12-01/DescribeDirectoryConfigs">REST API Reference for DescribeDirectoryConfigs Operation</seealso> public virtual Task<DescribeDirectoryConfigsResponse> DescribeDirectoryConfigsAsync(DescribeDirectoryConfigsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = DescribeDirectoryConfigsRequestMarshaller.Instance; var unmarshaller = DescribeDirectoryConfigsResponseUnmarshaller.Instance; return InvokeAsync<DescribeDirectoryConfigsRequest,DescribeDirectoryConfigsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeFleets /// <summary> /// Describes the specified fleets or all fleets in the account. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeFleets service method.</param> /// /// <returns>The response from the DescribeFleets service method, as returned by AppStream.</returns> /// <exception cref="Amazon.AppStream.Model.ResourceNotFoundException"> /// The specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/DescribeFleets">REST API Reference for DescribeFleets Operation</seealso> public virtual DescribeFleetsResponse DescribeFleets(DescribeFleetsRequest request) { var marshaller = DescribeFleetsRequestMarshaller.Instance; var unmarshaller = DescribeFleetsResponseUnmarshaller.Instance; return Invoke<DescribeFleetsRequest,DescribeFleetsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeFleets operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeFleets 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/appstream-2016-12-01/DescribeFleets">REST API Reference for DescribeFleets Operation</seealso> public virtual Task<DescribeFleetsResponse> DescribeFleetsAsync(DescribeFleetsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = DescribeFleetsRequestMarshaller.Instance; var unmarshaller = DescribeFleetsResponseUnmarshaller.Instance; return InvokeAsync<DescribeFleetsRequest,DescribeFleetsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeImageBuilders /// <summary> /// Describes the specified image builders or all image builders in the account. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeImageBuilders service method.</param> /// /// <returns>The response from the DescribeImageBuilders service method, as returned by AppStream.</returns> /// <exception cref="Amazon.AppStream.Model.ResourceNotFoundException"> /// The specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/DescribeImageBuilders">REST API Reference for DescribeImageBuilders Operation</seealso> public virtual DescribeImageBuildersResponse DescribeImageBuilders(DescribeImageBuildersRequest request) { var marshaller = DescribeImageBuildersRequestMarshaller.Instance; var unmarshaller = DescribeImageBuildersResponseUnmarshaller.Instance; return Invoke<DescribeImageBuildersRequest,DescribeImageBuildersResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeImageBuilders operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeImageBuilders 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/appstream-2016-12-01/DescribeImageBuilders">REST API Reference for DescribeImageBuilders Operation</seealso> public virtual Task<DescribeImageBuildersResponse> DescribeImageBuildersAsync(DescribeImageBuildersRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = DescribeImageBuildersRequestMarshaller.Instance; var unmarshaller = DescribeImageBuildersResponseUnmarshaller.Instance; return InvokeAsync<DescribeImageBuildersRequest,DescribeImageBuildersResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeImages /// <summary> /// Describes the specified images or all images in the account. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeImages service method.</param> /// /// <returns>The response from the DescribeImages service method, as returned by AppStream.</returns> /// <exception cref="Amazon.AppStream.Model.ResourceNotFoundException"> /// The specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/DescribeImages">REST API Reference for DescribeImages Operation</seealso> public virtual DescribeImagesResponse DescribeImages(DescribeImagesRequest request) { var marshaller = DescribeImagesRequestMarshaller.Instance; var unmarshaller = DescribeImagesResponseUnmarshaller.Instance; return Invoke<DescribeImagesRequest,DescribeImagesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeImages operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeImages 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/appstream-2016-12-01/DescribeImages">REST API Reference for DescribeImages Operation</seealso> public virtual Task<DescribeImagesResponse> DescribeImagesAsync(DescribeImagesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = DescribeImagesRequestMarshaller.Instance; var unmarshaller = DescribeImagesResponseUnmarshaller.Instance; return InvokeAsync<DescribeImagesRequest,DescribeImagesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeSessions /// <summary> /// Describes the streaming sessions for the specified stack and fleet. If a user ID is /// provided, only the streaming sessions for only that user are returned. If an authentication /// type is not provided, the default is to authenticate users using a streaming URL. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeSessions service method.</param> /// /// <returns>The response from the DescribeSessions service method, as returned by AppStream.</returns> /// <exception cref="Amazon.AppStream.Model.InvalidParameterCombinationException"> /// Indicates an incorrect combination of parameters, or a missing parameter. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/DescribeSessions">REST API Reference for DescribeSessions Operation</seealso> public virtual DescribeSessionsResponse DescribeSessions(DescribeSessionsRequest request) { var marshaller = DescribeSessionsRequestMarshaller.Instance; var unmarshaller = DescribeSessionsResponseUnmarshaller.Instance; return Invoke<DescribeSessionsRequest,DescribeSessionsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeSessions operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeSessions 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/appstream-2016-12-01/DescribeSessions">REST API Reference for DescribeSessions Operation</seealso> public virtual Task<DescribeSessionsResponse> DescribeSessionsAsync(DescribeSessionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = DescribeSessionsRequestMarshaller.Instance; var unmarshaller = DescribeSessionsResponseUnmarshaller.Instance; return InvokeAsync<DescribeSessionsRequest,DescribeSessionsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeStacks /// <summary> /// Describes the specified stacks or all stacks in the account. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeStacks service method.</param> /// /// <returns>The response from the DescribeStacks service method, as returned by AppStream.</returns> /// <exception cref="Amazon.AppStream.Model.ResourceNotFoundException"> /// The specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/DescribeStacks">REST API Reference for DescribeStacks Operation</seealso> public virtual DescribeStacksResponse DescribeStacks(DescribeStacksRequest request) { var marshaller = DescribeStacksRequestMarshaller.Instance; var unmarshaller = DescribeStacksResponseUnmarshaller.Instance; return Invoke<DescribeStacksRequest,DescribeStacksResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeStacks operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeStacks 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/appstream-2016-12-01/DescribeStacks">REST API Reference for DescribeStacks Operation</seealso> public virtual Task<DescribeStacksResponse> DescribeStacksAsync(DescribeStacksRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = DescribeStacksRequestMarshaller.Instance; var unmarshaller = DescribeStacksResponseUnmarshaller.Instance; return InvokeAsync<DescribeStacksRequest,DescribeStacksResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DisassociateFleet /// <summary> /// Disassociates the specified fleet from the specified stack. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DisassociateFleet service method.</param> /// /// <returns>The response from the DisassociateFleet service method, as returned by AppStream.</returns> /// <exception cref="Amazon.AppStream.Model.ConcurrentModificationException"> /// An API error occurred. Wait a few minutes and try again. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceInUseException"> /// The specified resource is in use. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceNotFoundException"> /// The specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/DisassociateFleet">REST API Reference for DisassociateFleet Operation</seealso> public virtual DisassociateFleetResponse DisassociateFleet(DisassociateFleetRequest request) { var marshaller = DisassociateFleetRequestMarshaller.Instance; var unmarshaller = DisassociateFleetResponseUnmarshaller.Instance; return Invoke<DisassociateFleetRequest,DisassociateFleetResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DisassociateFleet operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DisassociateFleet 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/appstream-2016-12-01/DisassociateFleet">REST API Reference for DisassociateFleet Operation</seealso> public virtual Task<DisassociateFleetResponse> DisassociateFleetAsync(DisassociateFleetRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = DisassociateFleetRequestMarshaller.Instance; var unmarshaller = DisassociateFleetResponseUnmarshaller.Instance; return InvokeAsync<DisassociateFleetRequest,DisassociateFleetResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ExpireSession /// <summary> /// Stops the specified streaming session. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ExpireSession service method.</param> /// /// <returns>The response from the ExpireSession service method, as returned by AppStream.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/ExpireSession">REST API Reference for ExpireSession Operation</seealso> public virtual ExpireSessionResponse ExpireSession(ExpireSessionRequest request) { var marshaller = ExpireSessionRequestMarshaller.Instance; var unmarshaller = ExpireSessionResponseUnmarshaller.Instance; return Invoke<ExpireSessionRequest,ExpireSessionResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ExpireSession operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ExpireSession 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/appstream-2016-12-01/ExpireSession">REST API Reference for ExpireSession Operation</seealso> public virtual Task<ExpireSessionResponse> ExpireSessionAsync(ExpireSessionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = ExpireSessionRequestMarshaller.Instance; var unmarshaller = ExpireSessionResponseUnmarshaller.Instance; return InvokeAsync<ExpireSessionRequest,ExpireSessionResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListAssociatedFleets /// <summary> /// Lists the fleets associated with the specified stack. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListAssociatedFleets service method.</param> /// /// <returns>The response from the ListAssociatedFleets service method, as returned by AppStream.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/ListAssociatedFleets">REST API Reference for ListAssociatedFleets Operation</seealso> public virtual ListAssociatedFleetsResponse ListAssociatedFleets(ListAssociatedFleetsRequest request) { var marshaller = ListAssociatedFleetsRequestMarshaller.Instance; var unmarshaller = ListAssociatedFleetsResponseUnmarshaller.Instance; return Invoke<ListAssociatedFleetsRequest,ListAssociatedFleetsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ListAssociatedFleets operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListAssociatedFleets 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/appstream-2016-12-01/ListAssociatedFleets">REST API Reference for ListAssociatedFleets Operation</seealso> public virtual Task<ListAssociatedFleetsResponse> ListAssociatedFleetsAsync(ListAssociatedFleetsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = ListAssociatedFleetsRequestMarshaller.Instance; var unmarshaller = ListAssociatedFleetsResponseUnmarshaller.Instance; return InvokeAsync<ListAssociatedFleetsRequest,ListAssociatedFleetsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListAssociatedStacks /// <summary> /// Lists the stacks associated with the specified fleet. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListAssociatedStacks service method.</param> /// /// <returns>The response from the ListAssociatedStacks service method, as returned by AppStream.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/ListAssociatedStacks">REST API Reference for ListAssociatedStacks Operation</seealso> public virtual ListAssociatedStacksResponse ListAssociatedStacks(ListAssociatedStacksRequest request) { var marshaller = ListAssociatedStacksRequestMarshaller.Instance; var unmarshaller = ListAssociatedStacksResponseUnmarshaller.Instance; return Invoke<ListAssociatedStacksRequest,ListAssociatedStacksResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ListAssociatedStacks operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListAssociatedStacks 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/appstream-2016-12-01/ListAssociatedStacks">REST API Reference for ListAssociatedStacks Operation</seealso> public virtual Task<ListAssociatedStacksResponse> ListAssociatedStacksAsync(ListAssociatedStacksRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = ListAssociatedStacksRequestMarshaller.Instance; var unmarshaller = ListAssociatedStacksResponseUnmarshaller.Instance; return InvokeAsync<ListAssociatedStacksRequest,ListAssociatedStacksResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListTagsForResource /// <summary> /// Lists the tags for the specified AppStream 2.0 resource. You can tag AppStream 2.0 /// image builders, images, fleets, and stacks. /// /// /// <para> /// For more information about tags, see <a href="http://docs.aws.amazon.com/appstream2/latest/developerguide/tagging-basic.html">Tagging /// Your Resources</a> in the <i>Amazon AppStream 2.0 Developer Guide</i>. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListTagsForResource service method.</param> /// /// <returns>The response from the ListTagsForResource service method, as returned by AppStream.</returns> /// <exception cref="Amazon.AppStream.Model.ResourceNotFoundException"> /// The specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso> public virtual ListTagsForResourceResponse ListTagsForResource(ListTagsForResourceRequest request) { var marshaller = ListTagsForResourceRequestMarshaller.Instance; var unmarshaller = ListTagsForResourceResponseUnmarshaller.Instance; return Invoke<ListTagsForResourceRequest,ListTagsForResourceResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ListTagsForResource operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListTagsForResource 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/appstream-2016-12-01/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso> public virtual Task<ListTagsForResourceResponse> ListTagsForResourceAsync(ListTagsForResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = ListTagsForResourceRequestMarshaller.Instance; var unmarshaller = ListTagsForResourceResponseUnmarshaller.Instance; return InvokeAsync<ListTagsForResourceRequest,ListTagsForResourceResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region StartFleet /// <summary> /// Starts the specified fleet. /// </summary> /// <param name="request">Container for the necessary parameters to execute the StartFleet service method.</param> /// /// <returns>The response from the StartFleet service method, as returned by AppStream.</returns> /// <exception cref="Amazon.AppStream.Model.ConcurrentModificationException"> /// An API error occurred. Wait a few minutes and try again. /// </exception> /// <exception cref="Amazon.AppStream.Model.InvalidAccountStatusException"> /// The resource cannot be created because your AWS account is suspended. For assistance, /// contact AWS Support. /// </exception> /// <exception cref="Amazon.AppStream.Model.LimitExceededException"> /// The requested limit exceeds the permitted limit for an account. /// </exception> /// <exception cref="Amazon.AppStream.Model.OperationNotPermittedException"> /// The attempted operation is not permitted. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceNotFoundException"> /// The specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/StartFleet">REST API Reference for StartFleet Operation</seealso> public virtual StartFleetResponse StartFleet(StartFleetRequest request) { var marshaller = StartFleetRequestMarshaller.Instance; var unmarshaller = StartFleetResponseUnmarshaller.Instance; return Invoke<StartFleetRequest,StartFleetResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the StartFleet operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the StartFleet 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/appstream-2016-12-01/StartFleet">REST API Reference for StartFleet Operation</seealso> public virtual Task<StartFleetResponse> StartFleetAsync(StartFleetRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = StartFleetRequestMarshaller.Instance; var unmarshaller = StartFleetResponseUnmarshaller.Instance; return InvokeAsync<StartFleetRequest,StartFleetResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region StartImageBuilder /// <summary> /// Starts the specified image builder. /// </summary> /// <param name="request">Container for the necessary parameters to execute the StartImageBuilder service method.</param> /// /// <returns>The response from the StartImageBuilder service method, as returned by AppStream.</returns> /// <exception cref="Amazon.AppStream.Model.ConcurrentModificationException"> /// An API error occurred. Wait a few minutes and try again. /// </exception> /// <exception cref="Amazon.AppStream.Model.IncompatibleImageException"> /// The image does not support storage connectors. /// </exception> /// <exception cref="Amazon.AppStream.Model.InvalidAccountStatusException"> /// The resource cannot be created because your AWS account is suspended. For assistance, /// contact AWS Support. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceNotAvailableException"> /// The specified resource exists and is not in use, but isn't available. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceNotFoundException"> /// The specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/StartImageBuilder">REST API Reference for StartImageBuilder Operation</seealso> public virtual StartImageBuilderResponse StartImageBuilder(StartImageBuilderRequest request) { var marshaller = StartImageBuilderRequestMarshaller.Instance; var unmarshaller = StartImageBuilderResponseUnmarshaller.Instance; return Invoke<StartImageBuilderRequest,StartImageBuilderResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the StartImageBuilder operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the StartImageBuilder 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/appstream-2016-12-01/StartImageBuilder">REST API Reference for StartImageBuilder Operation</seealso> public virtual Task<StartImageBuilderResponse> StartImageBuilderAsync(StartImageBuilderRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = StartImageBuilderRequestMarshaller.Instance; var unmarshaller = StartImageBuilderResponseUnmarshaller.Instance; return InvokeAsync<StartImageBuilderRequest,StartImageBuilderResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region StopFleet /// <summary> /// Stops the specified fleet. /// </summary> /// <param name="request">Container for the necessary parameters to execute the StopFleet service method.</param> /// /// <returns>The response from the StopFleet service method, as returned by AppStream.</returns> /// <exception cref="Amazon.AppStream.Model.ConcurrentModificationException"> /// An API error occurred. Wait a few minutes and try again. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceNotFoundException"> /// The specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/StopFleet">REST API Reference for StopFleet Operation</seealso> public virtual StopFleetResponse StopFleet(StopFleetRequest request) { var marshaller = StopFleetRequestMarshaller.Instance; var unmarshaller = StopFleetResponseUnmarshaller.Instance; return Invoke<StopFleetRequest,StopFleetResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the StopFleet operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the StopFleet 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/appstream-2016-12-01/StopFleet">REST API Reference for StopFleet Operation</seealso> public virtual Task<StopFleetResponse> StopFleetAsync(StopFleetRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = StopFleetRequestMarshaller.Instance; var unmarshaller = StopFleetResponseUnmarshaller.Instance; return InvokeAsync<StopFleetRequest,StopFleetResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region StopImageBuilder /// <summary> /// Stops the specified image builder. /// </summary> /// <param name="request">Container for the necessary parameters to execute the StopImageBuilder service method.</param> /// /// <returns>The response from the StopImageBuilder service method, as returned by AppStream.</returns> /// <exception cref="Amazon.AppStream.Model.ConcurrentModificationException"> /// An API error occurred. Wait a few minutes and try again. /// </exception> /// <exception cref="Amazon.AppStream.Model.OperationNotPermittedException"> /// The attempted operation is not permitted. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceNotFoundException"> /// The specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/StopImageBuilder">REST API Reference for StopImageBuilder Operation</seealso> public virtual StopImageBuilderResponse StopImageBuilder(StopImageBuilderRequest request) { var marshaller = StopImageBuilderRequestMarshaller.Instance; var unmarshaller = StopImageBuilderResponseUnmarshaller.Instance; return Invoke<StopImageBuilderRequest,StopImageBuilderResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the StopImageBuilder operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the StopImageBuilder 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/appstream-2016-12-01/StopImageBuilder">REST API Reference for StopImageBuilder Operation</seealso> public virtual Task<StopImageBuilderResponse> StopImageBuilderAsync(StopImageBuilderRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = StopImageBuilderRequestMarshaller.Instance; var unmarshaller = StopImageBuilderResponseUnmarshaller.Instance; return InvokeAsync<StopImageBuilderRequest,StopImageBuilderResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region TagResource /// <summary> /// Adds or overwrites one or more tags for the specified AppStream 2.0 resource. You /// can tag AppStream 2.0 image builders, images, fleets, and stacks. /// /// /// <para> /// Each tag consists of a key and an optional value. If a resource already has a tag /// with the same key, this operation updates its value. /// </para> /// /// <para> /// To list the current tags for your resources, use <a>ListTagsForResource</a>. To disassociate /// tags from your resources, use <a>UntagResource</a>. /// </para> /// /// <para> /// For more information about tags, see <a href="http://docs.aws.amazon.com/appstream2/latest/developerguide/tagging-basic.html">Tagging /// Your Resources</a> in the <i>Amazon AppStream 2.0 Developer Guide</i>. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the TagResource service method.</param> /// /// <returns>The response from the TagResource service method, as returned by AppStream.</returns> /// <exception cref="Amazon.AppStream.Model.InvalidAccountStatusException"> /// The resource cannot be created because your AWS account is suspended. For assistance, /// contact AWS Support. /// </exception> /// <exception cref="Amazon.AppStream.Model.LimitExceededException"> /// The requested limit exceeds the permitted limit for an account. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceNotFoundException"> /// The specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/TagResource">REST API Reference for TagResource Operation</seealso> public virtual TagResourceResponse TagResource(TagResourceRequest request) { var marshaller = TagResourceRequestMarshaller.Instance; var unmarshaller = TagResourceResponseUnmarshaller.Instance; return Invoke<TagResourceRequest,TagResourceResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the TagResource operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the TagResource 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/appstream-2016-12-01/TagResource">REST API Reference for TagResource Operation</seealso> public virtual Task<TagResourceResponse> TagResourceAsync(TagResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = TagResourceRequestMarshaller.Instance; var unmarshaller = TagResourceResponseUnmarshaller.Instance; return InvokeAsync<TagResourceRequest,TagResourceResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region UntagResource /// <summary> /// Disassociates the specified tags from the specified AppStream 2.0 resource. /// /// /// <para> /// To list the current tags for your resources, use <a>ListTagsForResource</a>. /// </para> /// /// <para> /// For more information about tags, see <a href="http://docs.aws.amazon.com/appstream2/latest/developerguide/tagging-basic.html">Tagging /// Your Resources</a> in the <i>Amazon AppStream 2.0 Developer Guide</i>. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the UntagResource service method.</param> /// /// <returns>The response from the UntagResource service method, as returned by AppStream.</returns> /// <exception cref="Amazon.AppStream.Model.ResourceNotFoundException"> /// The specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/UntagResource">REST API Reference for UntagResource Operation</seealso> public virtual UntagResourceResponse UntagResource(UntagResourceRequest request) { var marshaller = UntagResourceRequestMarshaller.Instance; var unmarshaller = UntagResourceResponseUnmarshaller.Instance; return Invoke<UntagResourceRequest,UntagResourceResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the UntagResource operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UntagResource 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/appstream-2016-12-01/UntagResource">REST API Reference for UntagResource Operation</seealso> public virtual Task<UntagResourceResponse> UntagResourceAsync(UntagResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = UntagResourceRequestMarshaller.Instance; var unmarshaller = UntagResourceResponseUnmarshaller.Instance; return InvokeAsync<UntagResourceRequest,UntagResourceResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region UpdateDirectoryConfig /// <summary> /// Updates the specified directory configuration. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateDirectoryConfig service method.</param> /// /// <returns>The response from the UpdateDirectoryConfig service method, as returned by AppStream.</returns> /// <exception cref="Amazon.AppStream.Model.ConcurrentModificationException"> /// An API error occurred. Wait a few minutes and try again. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceInUseException"> /// The specified resource is in use. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceNotFoundException"> /// The specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/UpdateDirectoryConfig">REST API Reference for UpdateDirectoryConfig Operation</seealso> public virtual UpdateDirectoryConfigResponse UpdateDirectoryConfig(UpdateDirectoryConfigRequest request) { var marshaller = UpdateDirectoryConfigRequestMarshaller.Instance; var unmarshaller = UpdateDirectoryConfigResponseUnmarshaller.Instance; return Invoke<UpdateDirectoryConfigRequest,UpdateDirectoryConfigResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the UpdateDirectoryConfig operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateDirectoryConfig 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/appstream-2016-12-01/UpdateDirectoryConfig">REST API Reference for UpdateDirectoryConfig Operation</seealso> public virtual Task<UpdateDirectoryConfigResponse> UpdateDirectoryConfigAsync(UpdateDirectoryConfigRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = UpdateDirectoryConfigRequestMarshaller.Instance; var unmarshaller = UpdateDirectoryConfigResponseUnmarshaller.Instance; return InvokeAsync<UpdateDirectoryConfigRequest,UpdateDirectoryConfigResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region UpdateFleet /// <summary> /// Updates the specified fleet. /// /// /// <para> /// If the fleet is in the <code>STOPPED</code> state, you can update any attribute except /// the fleet name. If the fleet is in the <code>RUNNING</code> state, you can update /// the <code>DisplayName</code> and <code>ComputeCapacity</code> attributes. If the fleet /// is in the <code>STARTING</code> or <code>STOPPING</code> state, you can't update it. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateFleet service method.</param> /// /// <returns>The response from the UpdateFleet service method, as returned by AppStream.</returns> /// <exception cref="Amazon.AppStream.Model.ConcurrentModificationException"> /// An API error occurred. Wait a few minutes and try again. /// </exception> /// <exception cref="Amazon.AppStream.Model.IncompatibleImageException"> /// The image does not support storage connectors. /// </exception> /// <exception cref="Amazon.AppStream.Model.InvalidAccountStatusException"> /// The resource cannot be created because your AWS account is suspended. For assistance, /// contact AWS Support. /// </exception> /// <exception cref="Amazon.AppStream.Model.InvalidParameterCombinationException"> /// Indicates an incorrect combination of parameters, or a missing parameter. /// </exception> /// <exception cref="Amazon.AppStream.Model.InvalidRoleException"> /// The specified role is invalid. /// </exception> /// <exception cref="Amazon.AppStream.Model.LimitExceededException"> /// The requested limit exceeds the permitted limit for an account. /// </exception> /// <exception cref="Amazon.AppStream.Model.OperationNotPermittedException"> /// The attempted operation is not permitted. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceInUseException"> /// The specified resource is in use. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceNotAvailableException"> /// The specified resource exists and is not in use, but isn't available. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceNotFoundException"> /// The specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/UpdateFleet">REST API Reference for UpdateFleet Operation</seealso> public virtual UpdateFleetResponse UpdateFleet(UpdateFleetRequest request) { var marshaller = UpdateFleetRequestMarshaller.Instance; var unmarshaller = UpdateFleetResponseUnmarshaller.Instance; return Invoke<UpdateFleetRequest,UpdateFleetResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the UpdateFleet operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateFleet 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/appstream-2016-12-01/UpdateFleet">REST API Reference for UpdateFleet Operation</seealso> public virtual Task<UpdateFleetResponse> UpdateFleetAsync(UpdateFleetRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = UpdateFleetRequestMarshaller.Instance; var unmarshaller = UpdateFleetResponseUnmarshaller.Instance; return InvokeAsync<UpdateFleetRequest,UpdateFleetResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region UpdateStack /// <summary> /// Updates the specified stack. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateStack service method.</param> /// /// <returns>The response from the UpdateStack service method, as returned by AppStream.</returns> /// <exception cref="Amazon.AppStream.Model.IncompatibleImageException"> /// The image does not support storage connectors. /// </exception> /// <exception cref="Amazon.AppStream.Model.InvalidAccountStatusException"> /// The resource cannot be created because your AWS account is suspended. For assistance, /// contact AWS Support. /// </exception> /// <exception cref="Amazon.AppStream.Model.InvalidParameterCombinationException"> /// Indicates an incorrect combination of parameters, or a missing parameter. /// </exception> /// <exception cref="Amazon.AppStream.Model.InvalidRoleException"> /// The specified role is invalid. /// </exception> /// <exception cref="Amazon.AppStream.Model.LimitExceededException"> /// The requested limit exceeds the permitted limit for an account. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceInUseException"> /// The specified resource is in use. /// </exception> /// <exception cref="Amazon.AppStream.Model.ResourceNotFoundException"> /// The specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/appstream-2016-12-01/UpdateStack">REST API Reference for UpdateStack Operation</seealso> public virtual UpdateStackResponse UpdateStack(UpdateStackRequest request) { var marshaller = UpdateStackRequestMarshaller.Instance; var unmarshaller = UpdateStackResponseUnmarshaller.Instance; return Invoke<UpdateStackRequest,UpdateStackResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the UpdateStack operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateStack 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/appstream-2016-12-01/UpdateStack">REST API Reference for UpdateStack Operation</seealso> public virtual Task<UpdateStackResponse> UpdateStackAsync(UpdateStackRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = UpdateStackRequestMarshaller.Instance; var unmarshaller = UpdateStackResponseUnmarshaller.Instance; return InvokeAsync<UpdateStackRequest,UpdateStackResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion } }
 // AboutPage.xaml.cs // Copyright (c) 2014+ by Michael Penner. All rights reserved. using Xamarin.Forms; namespace Eamon.Mobile.Views { public partial class AboutPage : ContentPage { public AboutPage() { InitializeComponent(); } } }
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL) // <NameSpace>Mim.V6301</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields> // </auto-generated> // ------------------------------------------------------------------------------ namespace Mim.V6301 { using System; using System.Diagnostics; using System.Xml.Serialization; using System.Collections; using System.Xml.Schema; using System.ComponentModel; using System.IO; using System.Text; [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")] [System.SerializableAttribute()] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="urn:hl7-org:v3")] public enum POLB_MT001000UK01Component1TemplateIdRoot { /// <remarks/> [System.Xml.Serialization.XmlEnumAttribute("2.16.840.1.113883.2.1.3.2.4.18.2")] Item216840111388321324182, } }
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; using MyProject.Admin.EntityFramework.Shared.DbContexts; namespace MyProject.Admin.EntityFramework.PostgreSQL.Migrations.Logging { [DbContext(typeof(AdminLogDbContext))] [Migration("20191120100104_DbInit")] partial class DbInit { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn) .HasAnnotation("ProductVersion", "3.0.0") .HasAnnotation("Relational:MaxIdentifierLength", 63); modelBuilder.Entity("Skoruba.IdentityServer4.Admin.EntityFramework.Entities.Log", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<string>("Exception") .HasColumnType("text"); b.Property<string>("Level") .HasColumnType("character varying(128)") .HasMaxLength(128); b.Property<string>("LogEvent") .HasColumnType("text"); b.Property<string>("Message") .HasColumnType("text"); b.Property<string>("MessageTemplate") .HasColumnType("text"); b.Property<string>("Properties") .HasColumnType("text"); b.Property<DateTimeOffset>("TimeStamp") .HasColumnType("timestamp with time zone"); b.HasKey("Id"); b.ToTable("Log"); }); #pragma warning restore 612, 618 } } }
using System; using System.Threading.Tasks; using CliFx; using CliFx.Attributes; using CliFx.Infrastructure; using DrfLikePaginations; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.ApplicationModels; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.OpenApi.Models; using Serilog; using TicTacToeCSharpPlayground.Api.Configs; using TicTacToeCSharpPlayground.Core.Business; using TicTacToeCSharpPlayground.Core.Repository; using TicTacToeCSharpPlayground.Core.Services; using TicTacToeCSharpPlayground.Infrastructure.Database; using TicTacToeCSharpPlayground.Infrastructure.Database.Repositories; namespace TicTacToeCSharpPlayground.EntryCommands { [Command("api")] public class ApiCommand : ICommand { public async ValueTask ExecuteAsync(IConsole console) { Log.Information("Initializing API..."); // We create our host and run our web api! await Program.CreateHostBuilder(Array.Empty<string>()).Build().RunAsync(); } public class Startup { public IConfiguration Configuration { get; } public Startup(IConfiguration configuration) { Configuration = configuration; } public void ConfigureServices(IServiceCollection services) { // APIs services.AddControllers(options => { options.Filters.Add(new HttpExceptionFilter()); }); services.AddControllers(options => { options.Conventions.Add(new RouteTokenTransformerConvention(new SlugifyParameterTransformer())); }); services.AddSwaggerGen(swaggerGenOptions => { swaggerGenOptions.SwaggerDoc("v1", new OpenApiInfo { Title = "TicTacToeCSharpPlayground", Version = "v1" }); }); // Database var connectionString = Configuration.GetConnectionString("AppDbContext"); services.AddHttpContextAccessor().AddDbContext<AppDbContext>(optionsBuilder => { optionsBuilder.UseNpgsql(connectionString); }); // Helpers // https://docs.automapper.org/en/latest/Dependency-injection.html#asp-net-core services.AddAutoMapper(typeof(Startup)); services.AddHealthChecks().AddNpgSql(connectionString); var paginationSize = int.Parse(Configuration["Pagination:Size"]); services.AddSingleton<IPagination>(new LimitOffsetPagination(paginationSize)); // Repositories services.AddScoped<ITicTacToeRepository, TicTacToeRepository>(); // Services services.AddScoped<IGameService, GameService>(); // Businesses services.AddSingleton<IBoardJudge, BoardJudge>(); services.AddSingleton<IPositionDecider, PositionDecider>(); services.AddScoped<IBoardDealer, BoardDealer>(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "TicTacToeCSharpPlayground v1")); } app.UseSerilogRequestLogging(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapHealthChecks("/health-check"); }); Log.Information("'Configure' step is done! Ready to go!"); } } } }
// Standard using System.Collections; using System.Collections.Generic; namespace BagherMusic.Core.Structures { public class ResultSet<T> { public ResultSet(double delay, int count, HashSet<T> hits) { Delay = delay; Count = count; Hits = hits; } public double Delay { get; } public int Count { get; } public HashSet<T> Hits { get; } public override string ToString() { return $"ResultSet(Delay: {Delay}, Count: {Count}, HitsCount: {Hits.Count})"; } } }
using PFM.DataAccessLayer.Repositories.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PFM.DataAccessLayer.Entities; namespace PFM.DataAccessLayer.Repositories.Implementations { public class AtmWithdrawRepository : BaseRepository<AtmWithdraw>, IAtmWithdrawRepository { public AtmWithdrawRepository(PFMContext db) : base(db) { } } }
using System; using Xamarin.Forms; using ZXing.Net.Mobile.Forms; using ZXing.Net.Mobile.Forms.WindowsUniversal; using Xamarin.Forms.Platform.UWP; using System.ComponentModel; using System.Reflection; [assembly: ExportRenderer(typeof(ZXingScannerView), typeof(ZXingScannerViewRenderer))] namespace ZXing.Net.Mobile.Forms.WindowsUniversal { //[Preserve(AllMembers = true)] public class ZXingScannerViewRenderer : ViewRenderer<ZXingScannerView, ZXing.Mobile.ZXingScannerControl> { public static void Init () { // Cause the assembly to load } ZXingScannerView formsView; ZXing.Mobile.ZXingScannerControl zxingControl; protected override void OnElementChanged(ElementChangedEventArgs<ZXingScannerView> e) { formsView = Element; if (zxingControl == null) { formsView.AutoFocusRequested += FormsView_AutoFocusRequested; zxingControl = new ZXing.Mobile.ZXingScannerControl(); zxingControl.ContinuousScanning = true; zxingControl.UseCustomOverlay = true; base.SetNativeControl(zxingControl); if (formsView.IsScanning) zxingControl.StartScanning(formsView.RaiseScanResult, formsView.Options); if (!formsView.IsAnalyzing) zxingControl.PauseAnalysis(); if (formsView.IsTorchOn) zxingControl.Torch(formsView.IsTorchOn); } base.OnElementChanged(e); } protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); if (zxingControl == null) return; switch (e.PropertyName) { case nameof(ZXingScannerView.IsTorchOn): zxingControl.Torch(formsView.IsTorchOn); break; case nameof(ZXingScannerView.IsScanning): if (formsView.IsScanning) zxingControl.StartScanning(formsView.RaiseScanResult, formsView.Options); else zxingControl.StopScanning(); break; case nameof(ZXingScannerView.IsAnalyzing): if (formsView.IsAnalyzing) zxingControl.ResumeAnalysis(); else zxingControl.PauseAnalysis(); break; } } private void FormsView_AutoFocusRequested(int x, int y) { zxingControl.AutoFocus(x, y); } } }
// 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.Buffers; using System.Collections.Generic; using System.IO; using System.Runtime.ExceptionServices; using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.Internal; using Microsoft.AspNetCore.SignalR.Internal; using Microsoft.Extensions.Options; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; namespace Microsoft.AspNetCore.SignalR.Protocol { /// <summary> /// Implements the SignalR Hub Protocol using Newtonsoft.Json. /// </summary> public class NewtonsoftJsonHubProtocol : IHubProtocol { private const string ResultPropertyName = "result"; private const string ItemPropertyName = "item"; private const string InvocationIdPropertyName = "invocationId"; private const string StreamIdsPropertyName = "streamIds"; private const string TypePropertyName = "type"; private const string ErrorPropertyName = "error"; private const string TargetPropertyName = "target"; private const string ArgumentsPropertyName = "arguments"; private const string HeadersPropertyName = "headers"; private const string AllowReconnectPropertyName = "allowReconnect"; private static readonly string ProtocolName = "json"; private static readonly int ProtocolVersion = 1; /// <summary> /// Gets the serializer used to serialize invocation arguments and return values. /// </summary> public JsonSerializer PayloadSerializer { get; } /// <summary> /// Initializes a new instance of the <see cref="NewtonsoftJsonHubProtocol"/> class. /// </summary> public NewtonsoftJsonHubProtocol() : this(Options.Create(new NewtonsoftJsonHubProtocolOptions())) { } /// <summary> /// Initializes a new instance of the <see cref="NewtonsoftJsonHubProtocol"/> class. /// </summary> /// <param name="options">The options used to initialize the protocol.</param> public NewtonsoftJsonHubProtocol(IOptions<NewtonsoftJsonHubProtocolOptions> options) { PayloadSerializer = JsonSerializer.Create(options.Value.PayloadSerializerSettings); } /// <inheritdoc /> public string Name => ProtocolName; /// <inheritdoc /> public int Version => ProtocolVersion; /// <inheritdoc /> public TransferFormat TransferFormat => TransferFormat.Text; /// <inheritdoc /> public bool IsVersionSupported(int version) { return version == Version; } /// <inheritdoc /> public bool TryParseMessage(ref ReadOnlySequence<byte> input, IInvocationBinder binder, out HubMessage message) { if (!TextMessageParser.TryParseMessage(ref input, out var payload)) { message = null; return false; } var textReader = Utf8BufferTextReader.Get(payload); try { message = ParseMessage(textReader, binder); } finally { Utf8BufferTextReader.Return(textReader); } return message != null; } /// <inheritdoc /> public void WriteMessage(HubMessage message, IBufferWriter<byte> output) { WriteMessageCore(message, output); TextMessageFormatter.WriteRecordSeparator(output); } /// <inheritdoc /> public ReadOnlyMemory<byte> GetMessageBytes(HubMessage message) { return HubProtocolExtensions.GetMessageBytes(this, message); } private HubMessage ParseMessage(Utf8BufferTextReader textReader, IInvocationBinder binder) { try { // We parse using the JsonTextReader directly but this has a problem. Some of our properties are dependent on other properties // and since reading the json might be unordered, we need to store the parsed content as JToken to re-parse when true types are known. // if we're lucky and the state we need to directly parse is available, then we'll use it. int? type = null; string invocationId = null; string target = null; string error = null; var hasItem = false; object item = null; JToken itemToken = null; var hasResult = false; object result = null; JToken resultToken = null; var hasArguments = false; object[] arguments = null; string[] streamIds = null; JArray argumentsToken = null; ExceptionDispatchInfo argumentBindingException = null; Dictionary<string, string> headers = null; var completed = false; var allowReconnect = false; using (var reader = JsonUtils.CreateJsonTextReader(textReader)) { reader.DateParseHandling = DateParseHandling.None; JsonUtils.CheckRead(reader); // We're always parsing a JSON object JsonUtils.EnsureObjectStart(reader); do { switch (reader.TokenType) { case JsonToken.PropertyName: var memberName = reader.Value.ToString(); switch (memberName) { case TypePropertyName: var messageType = JsonUtils.ReadAsInt32(reader, TypePropertyName); if (messageType == null) { throw new InvalidDataException($"Missing required property '{TypePropertyName}'."); } type = messageType.Value; break; case InvocationIdPropertyName: invocationId = JsonUtils.ReadAsString(reader, InvocationIdPropertyName); break; case StreamIdsPropertyName: JsonUtils.CheckRead(reader); if (reader.TokenType != JsonToken.StartArray) { throw new InvalidDataException($"Expected '{StreamIdsPropertyName}' to be of type {JTokenType.Array}."); } var newStreamIds = new List<string>(); reader.Read(); while (reader.TokenType != JsonToken.EndArray) { newStreamIds.Add(reader.Value?.ToString()); reader.Read(); } streamIds = newStreamIds.ToArray(); break; case TargetPropertyName: target = JsonUtils.ReadAsString(reader, TargetPropertyName); break; case ErrorPropertyName: error = JsonUtils.ReadAsString(reader, ErrorPropertyName); break; case AllowReconnectPropertyName: allowReconnect = JsonUtils.ReadAsBoolean(reader, AllowReconnectPropertyName); break; case ResultPropertyName: hasResult = true; if (string.IsNullOrEmpty(invocationId)) { JsonUtils.CheckRead(reader); // If we don't have an invocation id then we need to store it as a JToken so we can parse it later resultToken = JToken.Load(reader); } else { // If we have an invocation id already we can parse the end result var returnType = binder.GetReturnType(invocationId); if (!JsonUtils.ReadForType(reader, returnType)) { throw new JsonReaderException("Unexpected end when reading JSON"); } result = PayloadSerializer.Deserialize(reader, returnType); } break; case ItemPropertyName: JsonUtils.CheckRead(reader); hasItem = true; string id = null; if (!string.IsNullOrEmpty(invocationId)) { id = invocationId; } else { // If we don't have an id yet then we need to store it as a JToken to parse later itemToken = JToken.Load(reader); break; } try { var itemType = binder.GetStreamItemType(id); item = PayloadSerializer.Deserialize(reader, itemType); } catch (Exception ex) { return new StreamBindingFailureMessage(id, ExceptionDispatchInfo.Capture(ex)); } break; case ArgumentsPropertyName: JsonUtils.CheckRead(reader); int initialDepth = reader.Depth; if (reader.TokenType != JsonToken.StartArray) { throw new InvalidDataException($"Expected '{ArgumentsPropertyName}' to be of type {JTokenType.Array}."); } hasArguments = true; if (string.IsNullOrEmpty(target)) { // We don't know the method name yet so just parse an array of generic JArray argumentsToken = JArray.Load(reader); } else { try { var paramTypes = binder.GetParameterTypes(target); arguments = BindArguments(reader, paramTypes); } catch (Exception ex) { argumentBindingException = ExceptionDispatchInfo.Capture(ex); // Could be at any point in argument array JSON when an error is thrown // Read until the end of the argument JSON array while (reader.Depth == initialDepth && reader.TokenType == JsonToken.StartArray || reader.Depth > initialDepth) { JsonUtils.CheckRead(reader); } } } break; case HeadersPropertyName: JsonUtils.CheckRead(reader); headers = ReadHeaders(reader); break; default: // Skip read the property name JsonUtils.CheckRead(reader); // Skip the value for this property reader.Skip(); break; } break; case JsonToken.EndObject: completed = true; break; } } while (!completed && JsonUtils.CheckRead(reader)); } HubMessage message; switch (type) { case HubProtocolConstants.InvocationMessageType: { if (argumentsToken != null) { // We weren't able to bind the arguments because they came before the 'target', so try to bind now that we've read everything. try { var paramTypes = binder.GetParameterTypes(target); arguments = BindArguments(argumentsToken, paramTypes); } catch (Exception ex) { argumentBindingException = ExceptionDispatchInfo.Capture(ex); } } message = argumentBindingException != null ? new InvocationBindingFailureMessage(invocationId, target, argumentBindingException) : BindInvocationMessage(invocationId, target, arguments, hasArguments, streamIds, binder); } break; case HubProtocolConstants.StreamInvocationMessageType: { if (argumentsToken != null) { // We weren't able to bind the arguments because they came before the 'target', so try to bind now that we've read everything. try { var paramTypes = binder.GetParameterTypes(target); arguments = BindArguments(argumentsToken, paramTypes); } catch (Exception ex) { argumentBindingException = ExceptionDispatchInfo.Capture(ex); } } message = argumentBindingException != null ? new InvocationBindingFailureMessage(invocationId, target, argumentBindingException) : BindStreamInvocationMessage(invocationId, target, arguments, hasArguments, streamIds, binder); } break; case HubProtocolConstants.StreamItemMessageType: if (itemToken != null) { try { var itemType = binder.GetStreamItemType(invocationId); item = itemToken.ToObject(itemType, PayloadSerializer); } catch (Exception ex) { message = new StreamBindingFailureMessage(invocationId, ExceptionDispatchInfo.Capture(ex)); break; }; } message = BindStreamItemMessage(invocationId, item, hasItem, binder); break; case HubProtocolConstants.CompletionMessageType: if (resultToken != null) { var returnType = binder.GetReturnType(invocationId); result = resultToken.ToObject(returnType, PayloadSerializer); } message = BindCompletionMessage(invocationId, error, result, hasResult, binder); break; case HubProtocolConstants.CancelInvocationMessageType: message = BindCancelInvocationMessage(invocationId); break; case HubProtocolConstants.PingMessageType: return PingMessage.Instance; case HubProtocolConstants.CloseMessageType: return BindCloseMessage(error, allowReconnect); case null: throw new InvalidDataException($"Missing required property '{TypePropertyName}'."); default: // Future protocol changes can add message types, old clients can ignore them return null; } return ApplyHeaders(message, headers); } catch (JsonReaderException jrex) { throw new InvalidDataException("Error reading JSON.", jrex); } } private Dictionary<string, string> ReadHeaders(JsonTextReader reader) { var headers = new Dictionary<string, string>(StringComparer.Ordinal); if (reader.TokenType != JsonToken.StartObject) { throw new InvalidDataException($"Expected '{HeadersPropertyName}' to be of type {JTokenType.Object}."); } while (reader.Read()) { switch (reader.TokenType) { case JsonToken.PropertyName: var propertyName = reader.Value.ToString(); JsonUtils.CheckRead(reader); if (reader.TokenType != JsonToken.String) { throw new InvalidDataException($"Expected header '{propertyName}' to be of type {JTokenType.String}."); } headers[propertyName] = reader.Value?.ToString(); break; case JsonToken.Comment: break; case JsonToken.EndObject: return headers; } } throw new JsonReaderException("Unexpected end when reading message headers"); } private void WriteMessageCore(HubMessage message, IBufferWriter<byte> stream) { var textWriter = Utf8BufferTextWriter.Get(stream); try { using (var writer = JsonUtils.CreateJsonTextWriter(textWriter)) { writer.WriteStartObject(); switch (message) { case InvocationMessage m: WriteMessageType(writer, HubProtocolConstants.InvocationMessageType); WriteHeaders(writer, m); WriteInvocationMessage(m, writer); break; case StreamInvocationMessage m: WriteMessageType(writer, HubProtocolConstants.StreamInvocationMessageType); WriteHeaders(writer, m); WriteStreamInvocationMessage(m, writer); break; case StreamItemMessage m: WriteMessageType(writer, HubProtocolConstants.StreamItemMessageType); WriteHeaders(writer, m); WriteStreamItemMessage(m, writer); break; case CompletionMessage m: WriteMessageType(writer, HubProtocolConstants.CompletionMessageType); WriteHeaders(writer, m); WriteCompletionMessage(m, writer); break; case CancelInvocationMessage m: WriteMessageType(writer, HubProtocolConstants.CancelInvocationMessageType); WriteHeaders(writer, m); WriteCancelInvocationMessage(m, writer); break; case PingMessage _: WriteMessageType(writer, HubProtocolConstants.PingMessageType); break; case CloseMessage m: WriteMessageType(writer, HubProtocolConstants.CloseMessageType); WriteCloseMessage(m, writer); break; default: throw new InvalidOperationException($"Unsupported message type: {message.GetType().FullName}"); } writer.WriteEndObject(); writer.Flush(); } } finally { Utf8BufferTextWriter.Return(textWriter); } } private void WriteHeaders(JsonTextWriter writer, HubInvocationMessage message) { if (message.Headers != null && message.Headers.Count > 0) { writer.WritePropertyName(HeadersPropertyName); writer.WriteStartObject(); foreach (var value in message.Headers) { writer.WritePropertyName(value.Key); writer.WriteValue(value.Value); } writer.WriteEndObject(); } } private void WriteCompletionMessage(CompletionMessage message, JsonTextWriter writer) { WriteInvocationId(message, writer); if (!string.IsNullOrEmpty(message.Error)) { writer.WritePropertyName(ErrorPropertyName); writer.WriteValue(message.Error); } else if (message.HasResult) { writer.WritePropertyName(ResultPropertyName); PayloadSerializer.Serialize(writer, message.Result); } } private void WriteCancelInvocationMessage(CancelInvocationMessage message, JsonTextWriter writer) { WriteInvocationId(message, writer); } private void WriteStreamItemMessage(StreamItemMessage message, JsonTextWriter writer) { WriteInvocationId(message, writer); writer.WritePropertyName(ItemPropertyName); PayloadSerializer.Serialize(writer, message.Item); } private void WriteInvocationMessage(InvocationMessage message, JsonTextWriter writer) { WriteInvocationId(message, writer); writer.WritePropertyName(TargetPropertyName); writer.WriteValue(message.Target); WriteArguments(message.Arguments, writer); WriteStreamIds(message.StreamIds, writer); } private void WriteStreamInvocationMessage(StreamInvocationMessage message, JsonTextWriter writer) { WriteInvocationId(message, writer); writer.WritePropertyName(TargetPropertyName); writer.WriteValue(message.Target); WriteArguments(message.Arguments, writer); WriteStreamIds(message.StreamIds, writer); } private void WriteCloseMessage(CloseMessage message, JsonTextWriter writer) { if (message.Error != null) { writer.WritePropertyName(ErrorPropertyName); writer.WriteValue(message.Error); } if (message.AllowReconnect) { writer.WritePropertyName(AllowReconnectPropertyName); writer.WriteValue(true); } } private void WriteArguments(object[] arguments, JsonTextWriter writer) { writer.WritePropertyName(ArgumentsPropertyName); writer.WriteStartArray(); foreach (var argument in arguments) { PayloadSerializer.Serialize(writer, argument); } writer.WriteEndArray(); } private void WriteStreamIds(string[] streamIds, JsonTextWriter writer) { if (streamIds == null) { return; } writer.WritePropertyName(StreamIdsPropertyName); writer.WriteStartArray(); foreach (var streamId in streamIds) { writer.WriteValue(streamId); } writer.WriteEndArray(); } private static void WriteInvocationId(HubInvocationMessage message, JsonTextWriter writer) { if (!string.IsNullOrEmpty(message.InvocationId)) { writer.WritePropertyName(InvocationIdPropertyName); writer.WriteValue(message.InvocationId); } } private static void WriteMessageType(JsonTextWriter writer, int type) { writer.WritePropertyName(TypePropertyName); writer.WriteValue(type); } private HubMessage BindCancelInvocationMessage(string invocationId) { if (string.IsNullOrEmpty(invocationId)) { throw new InvalidDataException($"Missing required property '{InvocationIdPropertyName}'."); } return new CancelInvocationMessage(invocationId); } private HubMessage BindCompletionMessage(string invocationId, string error, object result, bool hasResult, IInvocationBinder binder) { if (string.IsNullOrEmpty(invocationId)) { throw new InvalidDataException($"Missing required property '{InvocationIdPropertyName}'."); } if (error != null && hasResult) { throw new InvalidDataException("The 'error' and 'result' properties are mutually exclusive."); } if (hasResult) { return new CompletionMessage(invocationId, error, result, hasResult: true); } return new CompletionMessage(invocationId, error, result: null, hasResult: false); } private HubMessage BindStreamItemMessage(string invocationId, object item, bool hasItem, IInvocationBinder binder) { if (string.IsNullOrEmpty(invocationId)) { throw new InvalidDataException($"Missing required property '{InvocationIdPropertyName}'."); } if (!hasItem) { throw new InvalidDataException($"Missing required property '{ItemPropertyName}'."); } return new StreamItemMessage(invocationId, item); } private HubMessage BindStreamInvocationMessage(string invocationId, string target, object[] arguments, bool hasArguments, string[] streamIds, IInvocationBinder binder) { if (string.IsNullOrEmpty(invocationId)) { throw new InvalidDataException($"Missing required property '{InvocationIdPropertyName}'."); } if (!hasArguments) { throw new InvalidDataException($"Missing required property '{ArgumentsPropertyName}'."); } if (string.IsNullOrEmpty(target)) { throw new InvalidDataException($"Missing required property '{TargetPropertyName}'."); } return new StreamInvocationMessage(invocationId, target, arguments, streamIds); } private HubMessage BindInvocationMessage(string invocationId, string target, object[] arguments, bool hasArguments, string[] streamIds, IInvocationBinder binder) { if (string.IsNullOrEmpty(target)) { throw new InvalidDataException($"Missing required property '{TargetPropertyName}'."); } if (!hasArguments) { throw new InvalidDataException($"Missing required property '{ArgumentsPropertyName}'."); } return new InvocationMessage(invocationId, target, arguments, streamIds); } private bool ReadArgumentAsType(JsonTextReader reader, IReadOnlyList<Type> paramTypes, int paramIndex) { if (paramIndex < paramTypes.Count) { var paramType = paramTypes[paramIndex]; return JsonUtils.ReadForType(reader, paramType); } return reader.Read(); } private object[] BindArguments(JsonTextReader reader, IReadOnlyList<Type> paramTypes) { object[] arguments = null; var paramIndex = 0; var argumentsCount = 0; var paramCount = paramTypes.Count; while (ReadArgumentAsType(reader, paramTypes, paramIndex)) { if (reader.TokenType == JsonToken.EndArray) { if (argumentsCount != paramCount) { throw new InvalidDataException($"Invocation provides {argumentsCount} argument(s) but target expects {paramCount}."); } return arguments ?? Array.Empty<object>(); } if (arguments == null) { arguments = new object[paramCount]; } try { if (paramIndex < paramCount) { arguments[paramIndex] = PayloadSerializer.Deserialize(reader, paramTypes[paramIndex]); } else { reader.Skip(); } argumentsCount++; paramIndex++; } catch (Exception ex) { throw new InvalidDataException("Error binding arguments. Make sure that the types of the provided values match the types of the hub method being invoked.", ex); } } throw new JsonReaderException("Unexpected end when reading JSON"); } private CloseMessage BindCloseMessage(string error, bool allowReconnect) { // An empty string is still an error if (error == null && !allowReconnect) { return CloseMessage.Empty; } return new CloseMessage(error, allowReconnect); } private object[] BindArguments(JArray args, IReadOnlyList<Type> paramTypes) { var paramCount = paramTypes.Count; var argCount = args.Count; if (paramCount != argCount) { throw new InvalidDataException($"Invocation provides {argCount} argument(s) but target expects {paramCount}."); } if (paramCount == 0) { return Array.Empty<object>(); } var arguments = new object[argCount]; try { for (var i = 0; i < paramCount; i++) { var paramType = paramTypes[i]; arguments[i] = args[i].ToObject(paramType, PayloadSerializer); } return arguments; } catch (Exception ex) { throw new InvalidDataException("Error binding arguments. Make sure that the types of the provided values match the types of the hub method being invoked.", ex); } } private HubMessage ApplyHeaders(HubMessage message, Dictionary<string, string> headers) { if (headers != null && message is HubInvocationMessage invocationMessage) { invocationMessage.Headers = headers; } return message; } internal static JsonSerializerSettings CreateDefaultSerializerSettings() { return new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; } } }
using System; using System.Net.Http; using System.Threading.Tasks; using System.Web.Http; using Microsoft.Bot.Connector; using System.Diagnostics; using Microsoft.Bot.Builder.Dialogs; using SellerNotesBot.Dialogs; namespace SellerNotesBot { [BotAuthentication] public class MessagesController : ApiController { /// <summary> /// POST: api/Messages /// Receive a message from a user and reply to it /// </summary> public async Task<HttpResponseMessage> Post([FromBody]Activity activity) { try { if (activity != null) { switch (activity.GetActivityType()) { case ActivityTypes.Message: activity.Locale = "cs-CZ"; await Conversation.SendAsync(activity, () => new MainDialog()); //await Conversation.SendAsync(activity, () => new ContactDialog()); break; case ActivityTypes.ConversationUpdate: break; case ActivityTypes.ContactRelationUpdate: case ActivityTypes.Typing: case ActivityTypes.DeleteUserData: case ActivityTypes.Ping: default: Trace.TraceError($"Unknown activity type ignored: {activity.GetActivityType()}"); break; } } } catch (Exception ex) { ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl)); Activity reply = activity.CreateReply(ex.Message); await connector.Conversations.ReplyToActivityAsync(reply); } return new HttpResponseMessage(System.Net.HttpStatusCode.Accepted); } private Activity HandleSystemMessage(Activity message) { if (message.Type == ActivityTypes.DeleteUserData) { // Implement user deletion here // If we handle user deletion, return a real message } else if (message.Type == ActivityTypes.ConversationUpdate) { // Handle conversation state changes, like members being added and removed // Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info // Not available in all channels } else if (message.Type == ActivityTypes.ContactRelationUpdate) { // Handle add/remove from contact lists // Activity.From + Activity.Action represent what happened } else if (message.Type == ActivityTypes.Typing) { // Handle knowing tha the user is typing } else if (message.Type == ActivityTypes.Ping) { } return null; } } }
@model Aiursoft.Developer.Models.SitesViewModels.CreateSiteViewModel @{ ViewData["Title"] = "Create New Site"; } <div class="container-fluid"> <ol class="breadcrumb"> <li class="breadcrumb-item"> <a asp-controller="Apps" asp-action="Index">@Localizer["Dashboard"]</a> </li> <li class="breadcrumb-item"> <a asp-controller="Apps" asp-action="AllApps">@Localizer["All Apps"]</a> </li> <li class="breadcrumb-item"> <a asp-controller="Apps" asp-action="ViewApp" asp-route-id="@Model.AppId">@Model.AppName</a> </li> <li class="breadcrumb-item active"> Create site </li> </ol> @if (!ViewData.ModelState.IsValid) { <div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">x</span></button> <strong>@Localizer["Invalid Input!"]</strong> <div asp-validation-summary="All"></div> </div> } <div class="card mb-3"> <div class="card-header"> <i class="fa fa-inbox"></i> @Localizer["New Site Info"] </div> <div class="card-body"> <div class="col-12"> <form asp-controller="Sites" asp-action="CreateSite" asp-route-id="@Model.AppId" method="post" class="row"> <div class="col-md-4"> <div class="form-group"> <label asp-for="SiteName"></label> <input asp-for="SiteName" type="text" class="form-control" placeholder="Enter your new site name..."> <span asp-validation-for="SiteName" class="text-danger"></span> </div> </div> <div class="form-check col-12 pl-5"> <label class="form-check-label"> <input type="checkbox" class="form-check-input" asp-for="OpenToUpload" /> <label asp-for="OpenToUpload"></label> </label> <p class="text-muted">If you wanna allow users to upload files to your site anonymously and without permission, check this.</p> </div> <div class="form-check col-12 pl-5"> <label class="form-check-label"> <input type="checkbox" class="form-check-input" asp-for="OpenToDownload" /> <label asp-for="OpenToDownload"></label> </label> <p class="text-muted">If you wanna allow users to upload files to your site anonymously and without permission, check this.</p> </div> <div class="col-md-12 margin-top-30"> <button type="submit" data-disable-with="Creating..." class="btn btn-primary btn">@Localizer["Create"]</button> <input type="reset" class="btn btn-danger btn" id="cleartoasts" value="@Localizer["Clear"]" /> @if (!string.IsNullOrEmpty(Model.AppId)) { <a class="btn btn-info btn" asp-controller="Apps" asp-action="ViewApp" asp-route-id="@Model.AppId">@Localizer["Back to app"]</a> } <a class="btn btn-info secondary" asp-controller="Sites" asp-action="Index">@Localizer["Back to all sites"]</a> </div> </form> </div> </div> </div> </div>
/* * Copyright 2018 JDCLOUD.COM * * 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. * * Authentication * 用户认证相关接口 * * OpenAPI spec version: v1 * Contact: * * NOTE: This class is auto generated by the jdcloud code generator program. */ using System; using System.Collections.Generic; using System.Text; using JDCloudSDK.Core.Service; namespace JDCloudSDK.Containerregistry.Apis { /// <summary> /// &lt;p&gt;批量查询令牌。&lt;/p&gt; /// /// &lt;p&gt;暂时不支持分页和过滤条件。&lt;/p&gt; /// /// /// </summary> public class DescribeAuthorizationTokensResponse : JdcloudResponse<DescribeAuthorizationTokensResult> { } }
using System.Runtime.CompilerServices; namespace CulverinEditor.Debug { public enum Color { NONE = -1, BLUE, GREEN, YELLOW, ORANGE, PINK, RED } public enum Department { GENERAL = 0, PLAYER, IA, STAGE, PHYSICS } public class Debug { [MethodImpl(MethodImplOptions.InternalCall)] public static extern void Log(object message); public static void Log(object message, Department department = Department.GENERAL, Color color = Color.NONE) { // ADD COLOR FILTER ----------------------------------- switch (color) { case Color.NONE: { break; } case Color.BLUE: { message += "[blue]"; break; } case Color.GREEN: { message += "[green]"; break; } case Color.YELLOW: { message += "[yellow]"; break; } case Color.ORANGE: { message += "[orange]"; break; } case Color.PINK: { message += "[pink]"; break; } case Color.RED: { message += "[red]"; break; } default: break; } // ----------------------------------------------------- // ADD DEPARTMENT FILTER -------------------------------- switch (department) { case Department.GENERAL: { break; } case Department.PLAYER: { message = "[Player] " + message; break; } case Department.IA: { message = "[IA] " + message; break; } case Department.STAGE: { message = "[Stage] " + message; break; } case Department.PHYSICS: { message = "[Physics] " + message; break; } default: break; } // ---------------------------------------------------- //Call inEngine function Log(message); } } }
/* This file is part of the iText (R) project. Copyright (c) 1998-2021 iText Group NV Authors: iText Software. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License version 3 as published by the Free Software Foundation with the addition of the following permission added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program; if not, see http://www.gnu.org/licenses or write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA, 02110-1301 USA, or download the license from the following URL: http://itextpdf.com/terms-of-use/ The interactive user interfaces in modified source and object code versions of this program must display Appropriate Legal Notices, as required under Section 5 of the GNU Affero General Public License. In accordance with Section 7(b) of the GNU Affero General Public License, a covered work must retain the producer line in every PDF that is created or manipulated using iText. You can be released from the requirements of the license by purchasing a commercial license. Buying such a license is mandatory as soon as you develop commercial activities involving the iText software without disclosing the source code of your own applications. These activities include: offering paid services to customers as an ASP, serving PDFs on the fly in a web application, shipping iText with a closed source product. For more information, please contact iText Software Corp. at this address: [email protected] */ using System; using System.Collections.Generic; using System.IO; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.X509; using iText.IO.Util; using iText.Signatures; using iText.Signatures.Testutils; using iText.Signatures.Testutils.Builder; using iText.Signatures.Testutils.Client; using iText.Test; using iText.Test.Signutils; namespace iText.Signatures.Verify { public class CrlVerifierTest : ExtendedITextTest { private static readonly String certsSrc = iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext .CurrentContext.TestDirectory) + "/resources/itext/signatures/certs/"; private static readonly char[] password = "testpass".ToCharArray(); [NUnit.Framework.OneTimeSetUp] public static void Before() { } [NUnit.Framework.Test] public virtual void ValidCrl01() { X509Certificate caCert = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(certsSrc + "rootRsa.p12", password )[0]; TestCrlBuilder crlBuilder = new TestCrlBuilder(caCert, DateTimeUtil.GetCurrentUtcTime().AddDays(-1)); NUnit.Framework.Assert.IsTrue(VerifyTest(crlBuilder)); } [NUnit.Framework.Test] public virtual void InvalidRevokedCrl01() { NUnit.Framework.Assert.That(() => { X509Certificate caCert = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(certsSrc + "rootRsa.p12", password )[0]; TestCrlBuilder crlBuilder = new TestCrlBuilder(caCert, DateTimeUtil.GetCurrentUtcTime().AddDays(-1)); String checkCertFileName = certsSrc + "signCertRsa01.p12"; X509Certificate checkCert = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(checkCertFileName, password)[ 0]; crlBuilder.AddCrlEntry(checkCert, DateTimeUtil.GetCurrentUtcTime().AddDays(-40), Org.BouncyCastle.Asn1.X509.CrlReason.KeyCompromise ); VerifyTest(crlBuilder); } , NUnit.Framework.Throws.InstanceOf<VerificationException>()) ; } [NUnit.Framework.Test] public virtual void InvalidOutdatedCrl01() { X509Certificate caCert = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(certsSrc + "rootRsa.p12", password )[0]; TestCrlBuilder crlBuilder = new TestCrlBuilder(caCert, DateTimeUtil.GetCurrentUtcTime().AddDays(-2)); crlBuilder.SetNextUpdate(DateTimeUtil.GetCurrentUtcTime().AddDays(-1)); NUnit.Framework.Assert.IsFalse(VerifyTest(crlBuilder)); } private bool VerifyTest(TestCrlBuilder crlBuilder) { String caCertFileName = certsSrc + "rootRsa.p12"; X509Certificate caCert = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(caCertFileName, password)[0]; ICipherParameters caPrivateKey = Pkcs12FileHelper.ReadFirstKey(caCertFileName, password, password); String checkCertFileName = certsSrc + "signCertRsa01.p12"; X509Certificate checkCert = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(checkCertFileName, password)[ 0]; TestCrlClient crlClient = new TestCrlClient(crlBuilder, caPrivateKey); ICollection<byte[]> crlBytesCollection = crlClient.GetEncoded(checkCert, null); bool verify = false; foreach (byte[] crlBytes in crlBytesCollection) { X509Crl crl = (X509Crl)SignTestPortUtil.ParseCrlFromStream(new MemoryStream(crlBytes)); CRLVerifier verifier = new CRLVerifier(null, null); verify = verifier.Verify(crl, checkCert, caCert, DateTimeUtil.GetCurrentUtcTime()); break; } return verify; } } }
/******************************************************************************************* * * raylib [text] example - Draw text inside a rectangle * * This example has been created using raylib 2.3 (www.raylib.com) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * * Example contributed by Vlad Adrian (@demizdor) and reviewed by Ramon Santamaria (@raysan5) * * Copyright (c) 2018 Vlad Adrian (@demizdor) and Ramon Santamaria (@raysan5) * ********************************************************************************************/ using System.Numerics; using Raylib_cs; using static Raylib_cs.Raylib; using static Raylib_cs.Color; using static Raylib_cs.KeyboardKey; using static Raylib_cs.MouseButton; namespace Examples { public class text_rectangle_bounds { public static int Main() { // Initialization //-------------------------------------------------------------------------------------- const int screenWidth = 800; const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [text] example - draw text inside a rectangle"); string text = @"Text cannot escape\tthis container\t...word wrap also works when active so here's a long text for testing.\n\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Nec ullamcorper sit amet risus nullam eget felis eget."; bool resizing = false; bool wordWrap = true; Rectangle container = new Rectangle(25, 25, screenWidth - 50, screenHeight - 250); Rectangle resizer = new Rectangle(container.x + container.width - 17, container.y + container.height - 17, 14, 14); // Minimum width and heigh for the container rectangle const int minWidth = 60; const int minHeight = 60; const int maxWidth = screenWidth - 50; const int maxHeight = screenHeight - 160; Vector2 lastMouse = new Vector2(0.0f, 0.0f); // Stores last mouse coordinates Color borderColor = MAROON; // Container border color Font font = GetFontDefault(); // Get default system font SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop while (!WindowShouldClose()) // Detect window close button or ESC key { // Update //---------------------------------------------------------------------------------- if (IsKeyPressed(KEY_SPACE)) wordWrap = !wordWrap; Vector2 mouse = GetMousePosition(); // Check if the mouse is inside the container and toggle border color if (CheckCollisionPointRec(mouse, container)) borderColor = Fade(MAROON, 0.4f); else if (!resizing) borderColor = MAROON; // Container resizing logic if (resizing) { if (IsMouseButtonReleased(MOUSE_LEFT_BUTTON)) resizing = false; int width = (int)(container.width + (mouse.X - lastMouse.X)); container.width = (width > minWidth) ? ((width < maxWidth) ? width : maxWidth) : minWidth; int height = (int)(container.height + (mouse.Y - lastMouse.Y)); container.height = (height > minHeight) ? ((height < maxHeight) ? height : maxHeight) : minHeight; } else { // Check if we're resizing if (IsMouseButtonDown(MOUSE_LEFT_BUTTON) && CheckCollisionPointRec(mouse, resizer)) resizing = true; } // Move resizer rectangle properly resizer.x = container.x + container.width - 17; resizer.y = container.y + container.height - 17; lastMouse = mouse; // Update mouse //---------------------------------------------------------------------------------- // Draw //---------------------------------------------------------------------------------- BeginDrawing(); ClearBackground(RAYWHITE); DrawRectangleLinesEx(container, 3, borderColor); // Draw container border // Draw text in container (add some padding) DrawTextRec(font, text, new Rectangle(container.x + 4, container.y + 4, container.width - 4, container.height - 4), 20.0f, 2.0f, wordWrap, GRAY); DrawRectangleRec(resizer, borderColor); // Draw the resize box // Draw bottom info DrawRectangle(0, screenHeight - 54, screenWidth, 54, GRAY); DrawRectangleRec(new Rectangle(382, screenHeight - 34, 12, 12), MAROON); DrawText("Word Wrap: ", 313, screenHeight - 115, 20, BLACK); if (wordWrap) DrawText("ON", 447, screenHeight - 115, 20, RED); else DrawText("OFF", 447, screenHeight - 115, 20, BLACK); DrawText("Press [SPACE] to toggle word wrap", 218, screenHeight - 86, 20, GRAY); DrawText("Click hold & drag the to resize the container", 155, screenHeight - 38, 20, RAYWHITE); EndDrawing(); //---------------------------------------------------------------------------------- } // De-Initialization //-------------------------------------------------------------------------------------- CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- return 0; } } }
using UnityEngine; using System.Collections; using UnityEngine.UI; [ExecuteInEditMode] public class UITransparent : MonoBehaviour { [Range(0,1)] public float opacity = 1; private void Update() { GetComponent<Graphic>().color = GetComponent<Graphic>().color.Set(a: opacity); GetComponentsInChildren<Graphic>().ForEach(g => g.color = g.color.Set(a: opacity)); } }
using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Options; using Abp.Authorization; using ABPProject.Authorization.Roles; namespace ABPProject.Authorization.Users { public class UserClaimsPrincipalFactory : AbpUserClaimsPrincipalFactory<User, Role> { public UserClaimsPrincipalFactory( UserManager userManager, RoleManager roleManager, IOptions<IdentityOptions> optionsAccessor) : base( userManager, roleManager, optionsAccessor) { } } }
namespace LocalStorage.Paging.Views { internal sealed class TypeListPage : AbstractLinkedListPageView { public TypeListPage(Page page) : base(page) { } } }
// TEMPLATE:.+ 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("DjvuNet.Skia.Tests")] [assembly: AssemblyDescription("DjvuNet.Skia.Tests assembly contains tests for DjvuNet.Skia library.")] [assembly: AssemblyConfiguration("__LIBRARY_CONFIGURATION__")] [assembly: AssemblyPlatform("__LIBRARY_PLATFORM__")] [assembly: AssemblyCulture("")] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("E57F675D-11E7-4435-B376-809E38C77C57")] [assembly: InternalsVisibleTo("DjvuNet.DjvuLibre.Tests,PublicKey=00240000048000009400000006020000002400005253413100040000010001004dc7a384af8b33357ae286a9c208740e12580e26c93cfc529e38460986c19e382c23406f34eca0bf2baae3e9d69157c1f66675ac0d419c39028e070fcb687935aae49ee53cc85ea3faed79aeefe48f25a97ccecf02d983b2d71e92b7ebd71eb109b886b2cafa5cc9c8e915c6b802d0e975b44a7a5252c5693e8fa53a49fc36c2")] [assembly: InternalsVisibleTo("DjvuNet.Helper.Tests,PublicKey=00240000048000009400000006020000002400005253413100040000010001004dc7a384af8b33357ae286a9c208740e12580e26c93cfc529e38460986c19e382c23406f34eca0bf2baae3e9d69157c1f66675ac0d419c39028e070fcb687935aae49ee53cc85ea3faed79aeefe48f25a97ccecf02d983b2d71e92b7ebd71eb109b886b2cafa5cc9c8e915c6b802d0e975b44a7a5252c5693e8fa53a49fc36c2")]
// <auto-generated></auto-generated> #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; #if NET20 using NewtonsoftFork.Json.Utilities.LinqBridge; #else using System.Linq; #endif using NewtonsoftFork.Json.Utilities; using System.Collections; namespace NewtonsoftFork.Json.Linq { /// <summary> /// Represents a collection of <see cref="JToken"/> objects. /// </summary> /// <typeparam name="T">The type of token</typeparam> [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] [System.CodeDom.Compiler.GeneratedCode("OBeautifulCode.Serialization.Json", "See package version number")] public struct JEnumerable<T> : IJEnumerable<T>, IEquatable<JEnumerable<T>> where T : JToken { /// <summary> /// An empty collection of <see cref="JToken"/> objects. /// </summary> public static readonly JEnumerable<T> Empty = new JEnumerable<T>(Enumerable.Empty<T>()); private readonly IEnumerable<T> _enumerable; /// <summary> /// Initializes a new instance of the <see cref="JEnumerable{T}"/> struct. /// </summary> /// <param name="enumerable">The enumerable.</param> public JEnumerable(IEnumerable<T> enumerable) { ValidationUtils.ArgumentNotNull(enumerable, nameof(enumerable)); _enumerable = enumerable; } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection. /// </returns> public IEnumerator<T> GetEnumerator() { if (_enumerable == null) { return Empty.GetEnumerator(); } return _enumerable.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Gets the <see cref="IJEnumerable{JToken}"/> with the specified key. /// </summary> /// <value></value> public IJEnumerable<JToken> this[object key] { get { if (_enumerable == null) { return JEnumerable<JToken>.Empty; } return new JEnumerable<JToken>(_enumerable.Values<T, JToken>(key)); } } /// <summary> /// Determines whether the specified <see cref="JEnumerable{T}"/> is equal to this instance. /// </summary> /// <param name="other">The <see cref="JEnumerable{T}"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="JEnumerable{T}"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public bool Equals(JEnumerable<T> other) { return Equals(_enumerable, other._enumerable); } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { if (obj is JEnumerable<T>) { return Equals((JEnumerable<T>)obj); } return false; } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { if (_enumerable == null) { return 0; } return _enumerable.GetHashCode(); } } }
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: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ReflectionAccessor.Tests")] [assembly: AssemblyTrademark("")] // 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("00275f9e-c885-4264-b68d-ea80fe9b8c5b")]
using System; using System.Collections.Generic; using System.Text; namespace BusinessObjectLayer.Progressive.OnlineShop.V2.Part7 { // Resp: encaps. selected items public class OnlineBasket : List<OnlineBasketItem> { } }
using System; namespace CqrsFramework.Messaging { public interface IEvent { Guid SourceId { get; } } }
using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; using Newtonsoft.Json; using SeguraChain_Desktop_Wallet.InternalForm.Setup; using SeguraChain_Desktop_Wallet.Language.Database; using SeguraChain_Desktop_Wallet.Settings.Enum; using SeguraChain_Desktop_Wallet.Settings.Object; using SeguraChain_Desktop_Wallet.Sync; using SeguraChain_Desktop_Wallet.Wallet.Database; using SeguraChain_Lib.Utility; namespace SeguraChain_Desktop_Wallet.Common { public class ClassDesktopWalletCommonData { public static bool DesktopWalletStarted; public static ClassWalletSettingObject WalletSettingObject; public static ClassLanguageDatabase LanguageDatabase; public static ClassWalletSyncSystem WalletSyncSystem; public static ClassWalletDatabase WalletDatabase; #region On loading the desktop wallet. /// <summary> /// Initialize the language database for the startup form. /// </summary> /// <returns></returns> public static bool InitializeLanguageDatabaseForStartupForm() { // For setup. if (!InitializeLanguageDatabase(true)) { MessageBox.Show("Error on loading language file(s), please reinstall the desktop wallet.", "Language system", MessageBoxButtons.OK); Process.GetCurrentProcess().Kill(); } if (!ReadWalletSetting()) { MessageBox.Show("Error on loading wallet setting file, please reinstall or remove the wallet-setting.json.", "Wallet setting", MessageBoxButtons.OK); Process.GetCurrentProcess().Kill(); } // Once the wallet setting exist. if (!InitializeLanguageDatabase(false)) { MessageBox.Show("Error on loading language file(s), please reinstall the desktop wallet.", "Language system", MessageBoxButtons.OK); Process.GetCurrentProcess().Kill(); } return true; } /// <summary> /// Initialize every common data. /// </summary> /// <returns></returns> public static bool InitializeDesktopWalletCommonData() { if (!InitializeWalletSyncSystem().Result) { MessageBox.Show("Error on start wallet sync system.", "Wallet sync system", MessageBoxButtons.OK); Process.GetCurrentProcess().Kill(); } DesktopWalletStarted = true; InitializeWalletDatabase(); WalletSyncSystem.EnableTaskUpdateSyncCache(); return true; } #region Load/Create Wallet Setting. /// <summary> /// Initialize the wallet setting. /// </summary> /// <returns></returns> private static bool ReadWalletSetting() { string walletSettingFilePath = ClassUtility.ConvertPath(AppContext.BaseDirectory + ClassWalletDefaultSetting.WalletSettingFile); if (File.Exists(walletSettingFilePath)) { using (StreamReader reader = new StreamReader(walletSettingFilePath)) { if (ClassUtility.TryDeserialize(reader.ReadToEnd(), out WalletSettingObject, ObjectCreationHandling.Reuse)) { if (WalletSettingObject != null) return true; } } if (MessageBox.Show("Error on reading the wallet setting file, do you want to initialize it back to the original one ?", "Initialize wallet setting file", MessageBoxButtons.YesNo) == DialogResult.No) return false; return InitializeWalletSetting(walletSettingFilePath); } return InitializeWalletSetting(walletSettingFilePath); } /// <summary> /// Initialize the wallet setting if the file not exist or get an exception on reading it. /// </summary> /// <param name="walletSettingFilePath"></param> /// <returns></returns> private static bool InitializeWalletSetting(string walletSettingFilePath) { try { WalletSettingObject = new ClassWalletSettingObject(); if (LanguageDatabase.SetCurrentLanguageName(WalletSettingObject.WalletLanguageNameSelected)) { using (ClassWalletSetupForm walletSetupForm = new ClassWalletSetupForm()) { walletSetupForm.ShowDialog(); using (StreamWriter writer = new StreamWriter(walletSettingFilePath) { AutoFlush = true }) writer.Write(ClassUtility.SerializeData(WalletSettingObject, Formatting.Indented)); } } } catch { return false; } return true; } #endregion #region Load language database. /// <summary> /// Initialize the language database. /// </summary> /// <returns></returns> private static bool InitializeLanguageDatabase(bool withoutWalletSetting) { if (LanguageDatabase == null) LanguageDatabase = new ClassLanguageDatabase(); if (!LanguageDatabase.LoadLanguageDatabase(withoutWalletSetting)) return false; return true; } #endregion #region Load Wallet Sync System. /// <summary> /// Initialize the Wallet Sync System. /// </summary> /// <returns></returns> private static async Task<bool> InitializeWalletSyncSystem() { WalletSyncSystem = new ClassWalletSyncSystem(); if (!await WalletSyncSystem.LoadSyncDatabaseCache(WalletSettingObject)) return false; return await WalletSyncSystem.StartSync(); } #endregion #region Initialize wallet database. private static void InitializeWalletDatabase() { WalletDatabase = new ClassWalletDatabase(); WalletDatabase.EnableTaskUpdateWalletFileList(); WalletDatabase.EnableTaskUpdateWalletSync(); } #endregion #endregion #region On closing the desktop wallet. /// <summary> /// Close the desktop wallet, save common datas. /// </summary> /// <returns></returns> public static async Task<bool> CloseDesktopWalletCommonData() { DesktopWalletStarted = false; // Stop the sync cache system. WalletSyncSystem.StopTaskUpdateSyncCache(); await WalletSyncSystem.SaveSyncDatabaseCache(WalletSettingObject); // Stop the sync system. await WalletSyncSystem.CloseSync(); #if DEBUG Debug.WriteLine("Task wallet sync stopped."); #endif // Stop each wallet update task(s). WalletDatabase.StopUpdateTaskWallet(); #if DEBUG Debug.WriteLine("Task wallet update stopped."); #endif bool noError = true; if (WalletDatabase.DictionaryWalletData.Count > 0) { foreach (var walletFilename in WalletDatabase.DictionaryWalletData.Keys.ToArray()) noError = await WalletDatabase.SaveWalletFileAsync(walletFilename); } try { // Save wallet setting file. using (StreamWriter writer = new StreamWriter(ClassUtility.ConvertPath(AppContext.BaseDirectory + ClassWalletDefaultSetting.WalletSettingFile)) { AutoFlush = true }) writer.Write(ClassUtility.SerializeData(WalletSettingObject, Formatting.Indented)); #if DEBUG Debug.WriteLine("Wallet setting file saved."); #endif } catch { noError = false; } return noError; } #endregion } }
namespace NWN.FinalFantasy.Core.NWScript.Enum.Item.Property { public enum ImmunityMisc { Backstab = 0, LevelAbilityDrain = 1, Mindspells = 2, Poison = 3, Disease = 4, Fear = 5, Knockdown = 6, Paralysis = 7, CriticalHits = 8, DeathMagic = 9 } }
using System; using System.Collections.Generic; using System.Linq; using FluentAssertions; using Polly.Specs.Helpers; using Xunit; namespace Polly.Specs { public class RetryForeverAsyncSpecs { [Fact] public void Should_not_throw_regardless_of_how_many_times_the_specified_exception_is_raised() { var policy = Policy .Handle<DivideByZeroException>() .RetryForeverAsync(); policy.Awaiting(x => x.RaiseExceptionAsync<DivideByZeroException>(3)) .ShouldNotThrow(); } [Fact] public void Should_not_throw_regardless_of_how_many_times_one_of_the_specified_exception_is_raised() { var policy = Policy .Handle<DivideByZeroException>() .Or<ArgumentException>() .RetryForeverAsync(); policy.Awaiting(x => x.RaiseExceptionAsync<ArgumentException>(3)) .ShouldNotThrow(); } [Fact] public void Should_throw_when_exception_thrown_is_not_the_specified_exception_type() { var policy = Policy .Handle<DivideByZeroException>() .RetryForeverAsync(); policy.Awaiting(x => x.RaiseExceptionAsync<NullReferenceException>()) .ShouldThrow<NullReferenceException>(); } [Fact] public void Should_throw_when_exception_thrown_is_not_one_of_the_specified_exception_types() { var policy = Policy .Handle<DivideByZeroException>() .Or<ArgumentException>() .RetryForeverAsync(); policy.Awaiting(x => x.RaiseExceptionAsync<NullReferenceException>()) .ShouldThrow<NullReferenceException>(); } [Fact] public void Should_throw_when_specified_exception_predicate_is_not_satisfied() { var policy = Policy .Handle<DivideByZeroException>(e => false) .RetryForeverAsync(); policy.Awaiting(x => x.RaiseExceptionAsync<DivideByZeroException>()) .ShouldThrow<DivideByZeroException>(); } [Fact] public void Should_throw_when_none_of_the_specified_exception_predicates_are_satisfied() { var policy = Policy .Handle<DivideByZeroException>(e => false) .Or<ArgumentException>(e => false) .RetryForeverAsync(); policy.Awaiting(x => x.RaiseExceptionAsync<ArgumentException>()) .ShouldThrow<ArgumentException>(); } [Fact] public void Should_not_throw_when_specified_exception_predicate_is_satisfied() { var policy = Policy .Handle<DivideByZeroException>(e => true) .RetryForeverAsync(); policy.Awaiting(x => x.RaiseExceptionAsync<DivideByZeroException>()) .ShouldNotThrow(); } [Fact] public void Should_not_throw_when_one_of_the_specified_exception_predicates_are_satisfied() { var policy = Policy .Handle<DivideByZeroException>(e => true) .Or<ArgumentException>(e => true) .RetryForeverAsync(); policy.Awaiting(x => x.RaiseExceptionAsync<ArgumentException>()) .ShouldNotThrow(); } [Fact] public void Should_call_onretry_on_each_retry_with_the_current_exception() { var expectedExceptions = new object[] {"Exception #1", "Exception #2", "Exception #3"}; var retryExceptions = new List<Exception>(); var policy = Policy .Handle<DivideByZeroException>() .RetryForeverAsync(exception => retryExceptions.Add(exception)); policy.RaiseExceptionAsync<DivideByZeroException>(3, (e, i) => e.HelpLink = "Exception #" + i); retryExceptions .Select(x => x.HelpLink) .Should() .ContainInOrder(expectedExceptions); } [Fact] public void Should_not_call_onretry_when_no_retries_are_performed() { var retryExceptions = new List<Exception>(); var policy = Policy .Handle<DivideByZeroException>() .RetryForeverAsync(exception => retryExceptions.Add(exception)); policy.Awaiting(x => x.RaiseExceptionAsync<ArgumentException>()) .ShouldThrow<ArgumentException>(); retryExceptions.Should() .BeEmpty(); } } }
namespace CompositionTests { partial class frmRefine { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.pb = new System.Windows.Forms.PictureBox(); this.btnNext = new System.Windows.Forms.Button(); this.btnRemove = new System.Windows.Forms.Button(); this.btnSave = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.pb)).BeginInit(); this.SuspendLayout(); // // pb // this.pb.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.pb.BackColor = System.Drawing.Color.DimGray; this.pb.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; this.pb.Location = new System.Drawing.Point(12, 12); this.pb.Name = "pb"; this.pb.Size = new System.Drawing.Size(637, 480); this.pb.TabIndex = 0; this.pb.TabStop = false; // // btnNext // this.btnNext.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnNext.Location = new System.Drawing.Point(574, 502); this.btnNext.Name = "btnNext"; this.btnNext.Size = new System.Drawing.Size(75, 23); this.btnNext.TabIndex = 1; this.btnNext.Text = "Next"; this.btnNext.UseVisualStyleBackColor = true; this.btnNext.Click += new System.EventHandler(this.btnNext_Click); // // btnRemove // this.btnRemove.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnRemove.Location = new System.Drawing.Point(12, 502); this.btnRemove.Name = "btnRemove"; this.btnRemove.Size = new System.Drawing.Size(75, 23); this.btnRemove.TabIndex = 2; this.btnRemove.Text = "Remove"; this.btnRemove.UseVisualStyleBackColor = true; this.btnRemove.Click += new System.EventHandler(this.btnRemove_Click); // // btnSave // this.btnSave.Anchor = System.Windows.Forms.AnchorStyles.Bottom; this.btnSave.Location = new System.Drawing.Point(270, 502); this.btnSave.Name = "btnSave"; this.btnSave.Size = new System.Drawing.Size(75, 23); this.btnSave.TabIndex = 3; this.btnSave.Text = "Save"; this.btnSave.UseVisualStyleBackColor = true; this.btnSave.Click += new System.EventHandler(this.btnSave_Click); // // frmRefine // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(661, 537); this.Controls.Add(this.btnSave); this.Controls.Add(this.btnRemove); this.Controls.Add(this.btnNext); this.Controls.Add(this.pb); this.Name = "frmRefine"; this.Text = "frmRefine"; this.Load += new System.EventHandler(this.frmRefine_Load); ((System.ComponentModel.ISupportInitialize)(this.pb)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.PictureBox pb; private System.Windows.Forms.Button btnNext; private System.Windows.Forms.Button btnRemove; private System.Windows.Forms.Button btnSave; } }
using Pims.Core.Extensions; using Pims.Core.Helpers; using Pims.Dal; using System.Collections.Generic; using Entity = Pims.Dal.Entities; namespace Pims.Core.Test { /// <summary> /// EntityHelper static class, provides helper methods to create test entities. /// </summary> public static partial class EntityHelper { /// <summary> /// Create a new instance of a ProjectStatus. /// </summary> /// <param name="name"></param> /// <param name="code"></param> /// <returns></returns> public static Entity.ProjectStatus CreateProjectStatus(string name, string code) { return CreateProjectStatus(1, name, code); } /// <summary> /// Create a new instance of a ProjectStatus. /// </summary> /// <param name="id"></param> /// <param name="name"></param> /// <param name="code"></param> /// <returns></returns> public static Entity.ProjectStatus CreateProjectStatus(int id, string name, string code) { return new Entity.ProjectStatus(name, code) { Id = id, RowVersion = new byte[] { 12, 13, 14 } }; } /// <summary> /// Creates a random list of ProjectStatus. /// </summary> /// <param name="startId"></param> /// <param name="quantity"></param> /// <returns></returns> public static List<Entity.ProjectStatus> CreateProjectStatus(int startId, int quantity) { var status = new List<Entity.ProjectStatus>(); for (var i = startId; i < quantity; i++) { var name = StringHelper.Generate(10); status.Add(new Entity.ProjectStatus(name, name) { Id = i, SortOrder = 0, RowVersion = new byte[] { 12, 13, 14 } }); } return status; } /// <summary> /// Creates a default list of ProjectStatus. /// </summary> /// <returns></returns> public static List<Entity.ProjectStatus> CreateDefaultProjectStatus() { return new List<Entity.ProjectStatus>() { new Entity.ProjectStatus("Draft", "DR") { Id = 1, SortOrder = 0, Route = "{DR}", RowVersion = new byte[] { 12, 13, 14 } }, new Entity.ProjectStatus("Select Properties", "DR-P") { Id = 2, SortOrder = 1, Route = "{DR}", RowVersion = new byte[] { 12, 13, 14 } }, new Entity.ProjectStatus("Update Information", "DR-I") { Id = 3, SortOrder = 2, Route = "{DR}", RowVersion = new byte[] { 12, 13, 14 } }, new Entity.ProjectStatus("Required Documentation", "DR-D") { Id = 4, SortOrder = 3, Route = "{DR}", RowVersion = new byte[] { 12, 13, 14 } }, new Entity.ProjectStatus("Approval", "DR-A") { Id = 5, SortOrder = 4, Route = "{DR}", RowVersion = new byte[] { 12, 13, 14 } }, new Entity.ProjectStatus("Review", "DR-RE") { Id = 6, SortOrder = 5, Route = "{DR}", RowVersion = new byte[] { 12, 13, 14 } }, new Entity.ProjectStatus("Submitted", "AS-I") { Id = 7, SortOrder = 6, IsMilestone = true, Route = "{AS}", RowVersion = new byte[] { 12, 13, 14 } }, new Entity.ProjectStatus("Submitted Exemption", "AS-EXE") { Id = 8, SortOrder = 6, IsMilestone = true, Route = "{AS-EX}", RowVersion = new byte[] { 12, 13, 14 } }, new Entity.ProjectStatus("Document Review", "AS-D") { Id = 10, SortOrder = 7, Route = "{AS}", RowVersion = new byte[] { 12, 13, 14 } }, new Entity.ProjectStatus("Appraisal Review", "AS-AP") { Id = 11, SortOrder = 8, Route = "{AS}", RowVersion = new byte[] { 12, 13, 14 } }, new Entity.ProjectStatus("First Nations Consultation", "AS-FNC") { Id = 12, SortOrder = 9, Route = "{AS}", RowVersion = new byte[] { 12, 13, 14 } }, new Entity.ProjectStatus("Exemption Review", "AS-EXP") { Id = 13, SortOrder = 10, Route = "{AS-EX}", RowVersion = new byte[] { 12, 13, 14 } }, new Entity.ProjectStatus("Approved for ERP", "AP-ERP") { Id = 14, SortOrder = 11, IsMilestone = true, Route = "{AS}", RowVersion = new byte[] { 12, 13, 14 } }, new Entity.ProjectStatus("Approved for Exemption", "AP-EXE") { Id = 15, SortOrder = 11, IsMilestone = true, Route = "{AS-EX}", RowVersion = new byte[] { 12, 13, 14 } }, new Entity.ProjectStatus("Denied", "DE") { Id = 16, SortOrder = 11, IsMilestone = true, Route = "{AS}, {AS-EX}", RowVersion = new byte[] { 12, 13, 14 } }, new Entity.ProjectStatus("Transferred within GRE", "T-GRE") { Id = 20, SortOrder = 21, IsMilestone = true, Route = "{EX}, {ERP}", RowVersion = new byte[] { 12, 13, 14 } }, new Entity.ProjectStatus("Approved for SPL", "AP-SPL") { Id = 21, SortOrder = 21, IsMilestone = true, Route = "{EX}, {ERP}", RowVersion = new byte[] { 12, 13, 14 } }, new Entity.ProjectStatus("Not in SPL", "AP-!SPL") { Id = 22, SortOrder = 21, IsMilestone = true, Route = "{EX}, {ERP}", RowVersion = new byte[] { 12, 13, 14 } }, new Entity.ProjectStatus("Cancelled", "CA") { Id = 23, SortOrder = 21, IsMilestone = true, Route = "{EX}, {ERP}, {SPL}", RowVersion = new byte[] { 12, 13, 14 } }, new Entity.ProjectStatus("In ERP", "ERP-ON") { Id = 30, SortOrder = 1, Route = "{ERP}", RowVersion = new byte[] { 12, 13, 14 } }, new Entity.ProjectStatus("On Hold", "ERP-OH") { Id = 31, SortOrder = 2, Route = "{ERP}", RowVersion = new byte[] { 12, 13, 14 } }, new Entity.ProjectStatus("Disposed", "DIS") { Id = 32, SortOrder = 21, IsMilestone = true, Route = "{EX}, {ERP}", RowVersion = new byte[] { 12, 13, 14 } }, new Entity.ProjectStatus("Pre-Marketing", "SPL-PM") { Id = 40, SortOrder = 18, Route = "{SPL}", RowVersion = new byte[] { 12, 13, 14 } }, new Entity.ProjectStatus("Marketing", "SPL-M") { Id = 41, SortOrder = 19, Route = "{SPL}", RowVersion = new byte[] { 12, 13, 14 } }, new Entity.ProjectStatus("Contract in Place - Conditional", "SPL-CIP-C") { Id = 42, SortOrder = 20, Route = "{SPL}", RowVersion = new byte[] { 12, 13, 14 } }, new Entity.ProjectStatus("Contract in Place - Unconditional", "SPL-CIP-U") { Id = 43, SortOrder = 21, Route = "{SPL}", RowVersion = new byte[] { 12, 13, 14 } } }; } /// <summary> /// Create a default list of project status and add them to 'context'. /// </summary> /// <param name="context"></param> /// <returns></returns> public static List<Entity.ProjectStatus> CreateDefaultProjectStatus(this PimsContext context) { var status = CreateDefaultProjectStatus(); context.ProjectStatus.AddRange(status); return status; } /// <summary> /// Creates a new project status and adds it to the 'context'. /// </summary> /// <param name="context"></param> /// <param name="id"></param> /// <param name="name"></param> /// <param name="code"></param> /// <returns></returns> public static Entity.ProjectStatus CreateProjectStatus(this PimsContext context, int id, string name, string code) { var status = CreateProjectStatus(id, name, code); context.ProjectStatus.Add(status); return status; } /// <summary> /// Add the specified 'status' to the specified 'workflow'. /// </summary> /// <param name="context"></param> /// <param name="workflow"></param> /// <param name="status"></param> /// <returns></returns> public static PimsContext AddStatusToWorkflow(this PimsContext context, Entity.Workflow workflow, IEnumerable<Entity.ProjectStatus> status) { status.ForEach(s => workflow.Status.Add(new Entity.WorkflowProjectStatus(workflow, s))); return context; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="TypeHelper.cs" company="Catel development team"> // Copyright (c) 2008 - 2015 Catel development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Catel.Reflection { using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Logging; /// <summary> /// <see cref="Type"/> helper class. /// </summary> public static class TypeHelper { #region Fields /// <summary> /// The <see cref = "ILog">log</see> object. /// </summary> private static readonly ILog Log = LogManager.GetCurrentClassLogger(); /// <summary> /// A list of microsoft public key tokens. /// </summary> private static readonly HashSet<string> _microsoftPublicKeyTokens; private const char InnerTypeCountStart = '`'; private const char InternalTypeStart = '+'; private const char InternalTypeEnd = '['; private const string AllTypesStart = "[["; private const char SingleTypeStart = '['; private const char SingleTypeEnd = ']'; private static readonly char[] InnerTypeCountEnd = new[] { '[', '+' }; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="T:System.Object"/> class. /// </summary> static TypeHelper() { _microsoftPublicKeyTokens = new HashSet<string>(); _microsoftPublicKeyTokens.Add("b77a5c561934e089"); _microsoftPublicKeyTokens.Add("b03f5f7f11d50a3a"); _microsoftPublicKeyTokens.Add("31bf3856ad364e35"); } #endregion #region Properties /// <summary> /// Gets the Microsoft public key tokens. /// </summary> /// <value>The Microsoft public key tokens.</value> public static IEnumerable<string> MicrosoftPublicKeyTokens { get { return _microsoftPublicKeyTokens; } } #endregion #region Methods /// <summary> /// Gets the typed instance based on the specified instance. /// </summary> /// <param name="instance">The instance to retrieve in the typed form.</param> /// <returns>The typed instance.</returns> /// <exception cref="NotSupportedException">The <paramref name="instance"/> cannot be casted to <typeparamref name="TTargetType"/>.</exception> public static TTargetType GetTypedInstance<TTargetType>(object instance) where TTargetType : class { var typedInstance = instance as TTargetType; if ((typedInstance is null) && (instance is not null)) { throw Log.ErrorAndCreateException<NotSupportedException>("Expected an instance of '{0}', but retrieved an instance of '{1}', cannot return the typed instance", typeof (TTargetType).Name, instance.GetType().Name); } return typedInstance; } /// <summary> /// Determines whether the subclass is of a raw generic type. /// </summary> /// <param name = "generic">The generic.</param> /// <param name = "toCheck">The type to check.</param> /// <returns> /// <c>true</c> if the subclass is of a raw generic type; otherwise, <c>false</c>. /// </returns> /// <remarks> /// This implementation is based on this forum thread: /// http://stackoverflow.com/questions/457676/c-reflection-check-if-a-class-is-derived-from-a-generic-class /// <para /> /// Original license: CC BY-SA 2.5, compatible with the MIT license. /// </remarks> /// <exception cref = "ArgumentNullException">The <paramref name = "generic" /> is <c>null</c>.</exception> /// <exception cref = "ArgumentNullException">The <paramref name = "toCheck" /> is <c>null</c>.</exception> public static bool IsSubclassOfRawGeneric(Type generic, Type toCheck) { Argument.IsNotNull("generic", generic); Argument.IsNotNull("toCheck", toCheck); while ((toCheck is not null) && (toCheck != typeof(object))) { var cur = toCheck.IsGenericTypeEx() ? toCheck.GetGenericTypeDefinition() : toCheck; if (generic == cur) { return true; } toCheck = toCheck.GetBaseTypeEx(); } return false; } /// <summary> /// Gets the assembly name without overhead (version, public keytoken, etc) /// </summary> /// <param name="fullyQualifiedAssemblyName">Name of the fully qualified assembly.</param> /// <returns>The assembly without the overhead.</returns> /// <exception cref="ArgumentException">The <paramref name="fullyQualifiedAssemblyName"/> is <c>null</c> or whitespace.</exception> public static string GetAssemblyNameWithoutOverhead(string fullyQualifiedAssemblyName) { Argument.IsNotNullOrWhitespace("fullyQualifiedAssemblyName", fullyQualifiedAssemblyName); var indexOfFirstComma = fullyQualifiedAssemblyName.IndexOf(','); if (indexOfFirstComma != -1) { return fullyQualifiedAssemblyName.Substring(0, indexOfFirstComma); } return fullyQualifiedAssemblyName; } /// <summary> /// Gets the name of the assembly. /// </summary> /// <param name="fullTypeName">Full name of the type, for example <c>Catel.TypeHelper, Catel.Core</c>.</param> /// <returns>The assembly name retrieved from the type, for example <c>Catel.Core</c> or <c>null</c> if the assembly is not contained by the type.</returns> /// <exception cref="ArgumentException">The <paramref name="fullTypeName"/> is <c>null</c> or whitespace.</exception> public static string GetAssemblyName(string fullTypeName) { Argument.IsNotNullOrWhitespace("fullTypeName", fullTypeName); var lastGenericIndex = fullTypeName.LastIndexOf("]]", StringComparison.Ordinal); if (lastGenericIndex != -1) { fullTypeName = fullTypeName.Substring(lastGenericIndex + 2); } var splitterPos = fullTypeName.IndexOf(", ", StringComparison.Ordinal); var assemblyName = (splitterPos != -1) ? fullTypeName.Substring(splitterPos + 1).Trim() : null; return assemblyName; } /// <summary> /// Gets the type name with assembly, but without the fully qualified assembly name. For example, this method provides /// the string: /// <para /> /// <c>Catel.TypeHelper, Catel.Core, Version=1.0.0.0, PublicKeyToken=123456789</c> /// <para /> /// and will return: /// <para /> /// <c>Catel.TypeHelper, Catel.Core</c> /// </summary> /// <param name="fullTypeName">Full name of the type.</param> /// <returns>The type name including the assembly.</returns> /// <exception cref="ArgumentException">The <paramref name="fullTypeName"/> is <c>null</c> or whitespace.</exception> public static string GetTypeNameWithAssembly(string fullTypeName) { Argument.IsNotNullOrWhitespace("fullTypeName", fullTypeName); var assemblyNameWithoutOverhead = GetAssemblyName(fullTypeName); var assemblyName = GetAssemblyNameWithoutOverhead(assemblyNameWithoutOverhead); var typeName = GetTypeName(fullTypeName); return FormatType(assemblyName, typeName); } /// <summary> /// Gets the name of the type without the assembly but including the namespace. /// </summary> /// <param name="fullTypeName">Full name of the type, for example <c>Catel.TypeHelper, Catel.Core</c>.</param> /// <returns>The type name retrieved from the type, for example <c>Catel.TypeHelper</c>.</returns> /// <exception cref="ArgumentException">The <paramref name="fullTypeName"/> is <c>null</c> or whitespace.</exception> public static string GetTypeName(string fullTypeName) { Argument.IsNotNullOrWhitespace("fullTypeName", fullTypeName); return ConvertTypeToVersionIndependentType(fullTypeName, true); } /// <summary> /// Gets the type name without the assembly namespace. /// </summary> /// <param name="fullTypeName">Full name of the type, for example <c>Catel.TypeHelper, Catel.Core</c>.</param> /// <returns>The type name retrieved from the type, for example <c>TypeHelper</c>.</returns> /// <exception cref="ArgumentException">The <paramref name="fullTypeName"/> is <c>null</c> or whitespace.</exception> public static string GetTypeNameWithoutNamespace(string fullTypeName) { Argument.IsNotNullOrWhitespace("fullTypeName", fullTypeName); fullTypeName = GetTypeName(fullTypeName); var splitterPos = fullTypeName.LastIndexOf(".", StringComparison.Ordinal); var typeName = (splitterPos != -1) ? fullTypeName.Substring(splitterPos + 1).Trim() : fullTypeName; return typeName; } /// <summary> /// Gets the type namespace. /// </summary> /// <param name="fullTypeName">Full name of the type, for example <c>Catel.TypeHelper, Catel.Core</c>.</param> /// <returns>The type namespace retrieved from the type, for example <c>Catel</c>.</returns> /// <exception cref="ArgumentException">The <paramref name="fullTypeName"/> is <c>null</c> or whitespace.</exception> public static string GetTypeNamespace(string fullTypeName) { Argument.IsNotNullOrWhitespace("fullTypeName", fullTypeName); fullTypeName = GetTypeName(fullTypeName); var splitterPos = fullTypeName.LastIndexOf(".", StringComparison.Ordinal); var typeName = (splitterPos != -1) ? fullTypeName.Substring(0, splitterPos).Trim() : fullTypeName; return typeName; } /// <summary> /// Formats a type in the official type description like [typename], [assemblyname]. /// </summary> /// <param name = "assembly">Assembly name to format.</param> /// <param name = "type">Type name to format.</param> /// <returns>Type name like [typename], [assemblyname].</returns> /// <exception cref="ArgumentException">The <paramref name="assembly"/> is <c>null</c> or whitespace.</exception> /// <exception cref="ArgumentException">The <paramref name="type"/> is <c>null</c> or whitespace.</exception> public static string FormatType(string assembly, string type) { Argument.IsNotNullOrWhitespace("assembly", assembly); Argument.IsNotNullOrWhitespace("type", type); return $"{type}, {assembly}"; } /// <summary> /// Formats multiple inner types into one string. /// </summary> /// <param name="innerTypes">The inner types.</param> /// <param name="stripAssemblies">if set to <c>true</c>, the assembly names will be stripped as well.</param> /// <returns>string representing a combination of all inner types.</returns> public static string FormatInnerTypes(IEnumerable<string> innerTypes, bool stripAssemblies = false) { return string.Join(",", innerTypes.Select(x => { var type = stripAssemblies ? ConvertTypeToVersionIndependentType(x, true) : x; return $"[{type}]"; })); } /// <summary> /// Converts a string representation of a type to a version independent type by removing the assembly version information. /// </summary> /// <param name="type">Type to convert.</param> /// <param name="stripAssemblies">if set to <c>true</c>, the assembly names will be stripped as well.</param> /// <returns>String representing the type without version information.</returns> /// <exception cref="ArgumentException">The <paramref name="type" /> is <c>null</c> or whitespace.</exception> public static string ConvertTypeToVersionIndependentType(string type, bool stripAssemblies = false) { Argument.IsNotNullOrWhitespace("type", type); const string innerTypesEnd = ","; var newType = type; var innerTypes = GetInnerTypes(newType); if (innerTypes.Length > 0) { // Remove inner types, but never strip assemblies because we need the real original type newType = newType.Replace($"[{FormatInnerTypes(innerTypes, false)}]", string.Empty); for (var i = 0; i < innerTypes.Length; i++) { innerTypes[i] = ConvertTypeToVersionIndependentType(innerTypes[i], stripAssemblies); } } var splitterPos = newType.IndexOf(", ", StringComparison.Ordinal); var typeName = (splitterPos != -1) ? newType.Substring(0, splitterPos).Trim() : newType; var assemblyName = GetAssemblyName(newType); // Remove version info from assembly (if not signed by Microsoft) if (!string.IsNullOrWhiteSpace(assemblyName) && !stripAssemblies) { var isMicrosoftAssembly = MicrosoftPublicKeyTokens.Any(t => assemblyName.Contains(t)); if (!isMicrosoftAssembly) { assemblyName = GetAssemblyNameWithoutOverhead(assemblyName); } newType = FormatType(assemblyName, typeName); } else { newType = typeName; } if (innerTypes.Length > 0) { var innerTypesIndex = stripAssemblies ? newType.Length : newType.IndexOf(innerTypesEnd); if (innerTypesIndex >= 0) { newType = newType.Insert(innerTypesIndex, $"[{FormatInnerTypes(innerTypes, stripAssemblies)}]"); } } return newType; } /// <summary> /// Returns the inner type of a type, for example, a generic array type. /// </summary> /// <param name="type">Full type which might contain an inner type.</param> /// <returns>Array of inner types.</returns> /// <exception cref="ArgumentException">The <paramref name="type"/> is <c>null</c> or whitespace.</exception> public static string[] GetInnerTypes(string type) { Argument.IsNotNullOrWhitespace("type", type); var innerTypes = new List<string>(); try { var countIndex = type.IndexOf(InnerTypeCountStart); if (countIndex == -1) { return innerTypes.ToArray(); } // This is a generic, but does the type definition also contain the inner types? if (!type.Contains(AllTypesStart)) { return innerTypes.ToArray(); } // Get the number of inner types var innerTypeCountEnd = -1; foreach (var t in InnerTypeCountEnd) { var index = type.IndexOf(t); if ((index != -1) && ((innerTypeCountEnd == -1) || (index < innerTypeCountEnd))) { // This value is more likely to be the one innerTypeCountEnd = index; } } var innerTypeCount = int.Parse(type.Substring(countIndex + 1, innerTypeCountEnd - countIndex - 1)); // Remove all info until the first inner type if (!type.Contains(InternalTypeStart.ToString())) { // Just remove the info type = type.Substring(innerTypeCountEnd + 1); } else { // Remove the index, but not the numbers var internalTypeEnd = type.IndexOf(InternalTypeEnd); type = type.Substring(internalTypeEnd + 1); } // Get all the inner types for (var i = 0; i < innerTypeCount; i++) { // Get the start & end of this inner type var innerTypeStart = type.IndexOf(SingleTypeStart); var innerTypeEnd = innerTypeStart + 1; var openings = 1; // Loop until we find the end while (openings > 0) { if (type[innerTypeEnd] == SingleTypeStart) { openings++; } else if (type[innerTypeEnd] == SingleTypeEnd) { openings--; } // Increase current pos if we still have openings left if (openings > 0) { innerTypeEnd++; } } innerTypes.Add(type.Substring(innerTypeStart + 1, innerTypeEnd - innerTypeStart - 1)); type = type.Substring(innerTypeEnd + 1); } } catch (Exception ex) { Log.Warning(ex, "Failed to retrieve inner types"); } return innerTypes.ToArray(); } #endregion #region Powercast /// <summary> /// Tries to Generic cast of a value. /// </summary> /// <typeparam name = "TOutput">Requested return type.</typeparam> /// <typeparam name = "TInput">The input type.</typeparam> /// <param name = "value">The value to cast.</param> /// <param name = "output">The casted value.</param> /// <returns>When a cast is succeded true else false.</returns> public static bool TryCast<TOutput, TInput>(TInput value, out TOutput output) { var success = true; try { var outputType = typeof(TOutput); var innerType = Nullable.GetUnderlyingType(outputType); // Database support... if (value is null) { output = default; if (outputType.IsValueTypeEx() && innerType is null) { success = false; } else { // Non-valuetype can contain nill. // (Nullable<T> also) } } else { var inputType = value.GetType(); if (inputType.IsAssignableFromEx(outputType)) { // Direct assignable output = (TOutput)(object)value; } else { #pragma warning disable HAA0601 // Value type to reference type conversion causing boxing allocation output = (TOutput)Convert.ChangeType(value, innerType ?? outputType, CultureInfo.InvariantCulture); #pragma warning restore HAA0601 // Value type to reference type conversion causing boxing allocation } } } catch (Exception) { output = default; success = false; } return success; } /// <summary> /// Generic cast of a value. /// </summary> /// <typeparam name = "TOutput">Requested return type.</typeparam> /// <typeparam name = "TInput">The input type.</typeparam> /// <param name = "value">The value to cast.</param> /// <returns>The casted value.</returns> public static TOutput Cast<TOutput, TInput>(TInput value) { #pragma warning disable HAA0601 // Value type to reference type conversion causing boxing allocation return Cast<TOutput>(value); #pragma warning restore HAA0601 // Value type to reference type conversion causing boxing allocation } /// <summary> /// Generic cast of a value. /// </summary> /// <typeparam name = "TOutput">Requested return type.</typeparam> /// <param name = "value">The value to cast.</param> /// <returns>The casted value.</returns> public static TOutput Cast<TOutput>(object value) { if (!TryCast(value, out TOutput output)) { var tI = value.GetType().GetSafeFullName(false); var tO = typeof(TOutput).FullName; var vl = string.Concat(value); var msg = "Failed to cast from '{0}' to '{1}'"; if (!tI.Equals(vl)) { msg = string.Concat(msg, " for value '{2}'"); } throw Log.ErrorAndCreateException<InvalidCastException>(msg, tI, tO, vl); } return output; } /// <summary> /// Generic cast of a value. /// </summary> /// <typeparam name = "TOutput">Requested return type.</typeparam> /// <typeparam name = "TInput">The input type.</typeparam> /// <param name = "value">The value to cast.</param> /// <param name = "whenNullValue">When unable to cast the incoming value, this value is returned instead.</param> /// <returns>The casted value or when uncastable the <paramref name = "whenNullValue" /> is returned.</returns> public static TOutput Cast<TOutput, TInput>(TInput value, TOutput whenNullValue) { if (!TryCast(value, out TOutput output) || output is null) { output = whenNullValue; } return output; } #endregion } }
namespace Exemplo2.Areas.HelpPage.ModelDescriptions { public class EnumValueDescription { public string Documentation { get; set; } public string Name { get; set; } public string Value { get; set; } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading.Tasks; using NServiceBus.Extensibility; using NServiceBus.Unicast.Subscriptions; using NServiceBus.Unicast.Subscriptions.MessageDrivenSubscriptions; public class InMemorySubscriptionStorage : ISubscriptionStorage { public Task Subscribe(Subscriber subscriber, MessageType messageType, ContextBag context) { var dict = storage.GetOrAdd(messageType, type => new ConcurrentDictionary<string, Subscriber>(StringComparer.OrdinalIgnoreCase)); dict.AddOrUpdate(BuildKey(subscriber), _ => subscriber, (_, __) => subscriber); return Task.CompletedTask; } static string BuildKey(Subscriber subscriber) { return $"{subscriber.TransportAddress ?? ""}_{subscriber.Endpoint ?? ""}"; } public Task Unsubscribe(Subscriber subscriber, MessageType messageType, ContextBag context) { if (storage.TryGetValue(messageType, out var dict)) { dict.TryRemove(BuildKey(subscriber), out var _); } return Task.CompletedTask; } public Task<IEnumerable<Subscriber>> GetSubscriberAddressesForMessage(IEnumerable<MessageType> messageTypes, ContextBag context) { var result = new HashSet<Subscriber>(); foreach (var m in messageTypes) { if (storage.TryGetValue(m, out var list)) { result.UnionWith(list.Values); } } return Task.FromResult((IEnumerable<Subscriber>)result); } ConcurrentDictionary<MessageType, ConcurrentDictionary<string, Subscriber>> storage = new ConcurrentDictionary<MessageType, ConcurrentDictionary<string, Subscriber>>(); }
using System.Collections.Generic; using System.Linq; using UncommonSense.CBreeze.Core.Base; using UncommonSense.CBreeze.Core.Contracts; namespace UncommonSense.CBreeze.Core.Page { public class Pages : IntegerKeyedAndNamedContainer<Page>, INode { internal Pages(Application application, IEnumerable<Page> pages) { Application = application; AddRange(pages); } public Application Application { get; protected set; } public IEnumerable<INode> ChildNodes => this.Cast<INode>(); public INode ParentNode => Application; protected override IEnumerable<int> DefaultRange => DefaultRanges.ID; public override void ValidateName(Page item) { TestNameNotNullOrEmpty(item); TestNameUnique(item); } protected override void InsertItem(int index, Page item) { base.InsertItem(index, item); item.Container = this; } protected override void RemoveItem(int index) { this[index].Container = null; base.RemoveItem(index); } } }
using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Text; using System.Threading; using System.Threading.Tasks; using AutoMapper; using MongoDB.Bson; using MongoDB.Bson.Serialization; using MongoDB.Driver; namespace ContractSystem.DAL.MongoDb.DbSetting { /// <summary> /// this is base class for contract mongodb we use this to do not to repeat codes in every service /// </summary> /// <typeparam name="TEntity"></typeparam> public class ContractMongoDbBaseService<TEntity> where TEntity : class { public IMongoCollection<TEntity> _contract; public IMapper _mapper; public ContractMongoDbBaseService(IContractDatabaseSettings settings, IMapper mapper) { var client = new MongoClient(settings.ConnectionString); var database = client.GetDatabase(settings.DatabaseName); _contract = database.GetCollection<TEntity>(settings.ContractCollectionName); _mapper = mapper; } } }
using System; using System.Text; using Cosmos.System.Network.Config; using Cosmos.System.Network.IPv4; using Cosmos.System.Network.IPv4.TCP; using Con = System.Console; namespace Cosmos.System.Network { public class NetworkDebugger { /// <summary> /// TCP Server. /// </summary> private TcpListener xListener = null; /// <summary> /// TCP Client. /// </summary> private TcpClient xClient = null; /// <summary> /// Remote IP Address /// </summary> public Address Ip { get; set; } /// <summary> /// Port used /// </summary> public int Port { get; set; } /// <summary> /// Create NetworkDebugger class (used to listen for a debugger connection) /// </summary> /// <param name="port">Port used for TCP connection.</param> public NetworkDebugger(int port) { Port = port; xListener = new TcpListener((ushort)port); } /// <summary> /// Create NetworkDebugger class (used to connect to a remote debugger) /// </summary> /// <param name="ip">IP Address of the remote debugger.</param> /// <param name="port">Port used for TCP connection.</param> public NetworkDebugger(Address ip, int port) { Ip = ip; Port = port; xClient = new TcpClient(port); } /// <summary> /// Start debugger /// </summary> public void Start() { if (xClient == null) { xListener.Start(); Con.WriteLine("Waiting for remote debugger connection at " + NetworkConfig.CurrentConfig.Value.IPAddress.ToString() + ":" + Port); xClient = xListener.AcceptTcpClient(); //blocking } else if (xListener == null) { xClient.Connect(Ip, Port); } Send("--- Cosmos Network Debugger ---"); Send("Debugger Connected!"); } /// <summary> /// Send text to the debugger /// </summary> /// <param name="message">Text to send to the debugger.</param> public void Send(string message) { xClient.Send(Encoding.ASCII.GetBytes("[" + DateTime.Now.ToString("HH:mm:ss") + "] - " + message + "\r\n")); } /// <summary> /// Stop the debugger by closing TCP Connection /// </summary> public void Stop() { Con.WriteLine("Closing Debugger connection"); Send("Closing..."); xClient.Close(); } } }
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WPF.UI.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
using Omnikeeper.Base.Entity; using Omnikeeper.Base.Entity.DataOrigin; using Omnikeeper.Base.Utils; using Omnikeeper.Base.Utils.ModelContext; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Omnikeeper.Base.Model { public interface IChangesetModel { public interface IChangesetSelection { } public class ChangesetSelectionSpecificCIs : IChangesetSelection { public Guid[] CIIDs { get; } private ChangesetSelectionSpecificCIs(IEnumerable<Guid> ciids) { CIIDs = ciids.ToArray(); } public bool Contains(Guid ciid) => CIIDs.Contains(ciid); public static ChangesetSelectionSpecificCIs Build(IEnumerable<Guid> ciids) { if (ciids.IsEmpty()) throw new Exception("Empty ChangesetSelectionMultipleCIs not allowed"); return new ChangesetSelectionSpecificCIs(ciids); } public static ChangesetSelectionSpecificCIs Build(params Guid[] ciids) { if (ciids.IsEmpty()) throw new Exception("Empty ChangesetSelectionMultipleCIs not allowed"); return new ChangesetSelectionSpecificCIs(ciids); } } public class ChangesetSelectionAllCIs : IChangesetSelection { } Task<Changeset> CreateChangeset(long userID, string layerID, DataOriginV1 dataOrigin, IModelContext trans, DateTimeOffset? timestamp = null); Task<Changeset?> GetChangeset(Guid id, IModelContext trans); Task<IEnumerable<Changeset>> GetChangesets(ISet<Guid> ids, IModelContext trans); Task<IEnumerable<Changeset>> GetChangesetsInTimespan(DateTimeOffset from, DateTimeOffset to, LayerSet layers, IChangesetSelection cs, IModelContext trans, int? limit = null); Task<Changeset?> GetLatestChangesetForLayer(string layerID, IModelContext trans); [Obsolete("Archiving full-changesets-only is not necessary anymore, consider writing a simpler method that just removes outdated attributes/relations")] Task<int> ArchiveUnusedChangesetsOlderThan(DateTimeOffset threshold, IModelContext trans); Task<int> DeleteEmptyChangesets(IModelContext trans); Task<long> GetNumberOfChangesets(IModelContext trans); } }
using System.Text.Json.Serialization; namespace Essensoft.AspNetCore.Payment.Alipay.Domain { /// <summary> /// PurchaseApplyInfoDTO Data Structure. /// </summary> public class PurchaseApplyInfoDTO : AlipayObject { /// <summary> /// 采购类目 /// </summary> [JsonPropertyName("account_code")] public string AccountCode { get; set; } /// <summary> /// 预算周期 /// </summary> [JsonPropertyName("begin_cycle")] public string BeginCycle { get; set; } /// <summary> /// 活动预算申请code /// </summary> [JsonPropertyName("biz_budget_apply_code")] public string BizBudgetApplyCode { get; set; } /// <summary> /// 活动预算id /// </summary> [JsonPropertyName("biz_budget_id")] public string BizBudgetId { get; set; } /// <summary> /// 业务类型 COMMISSION("COMMISSION", "返佣"), PURCHASE("PURCHASE", "采购"), PROMO("PROMO", "营销"), /// </summary> [JsonPropertyName("biz_type")] public string BizType { get; set; } /// <summary> /// PERCENTAGE("PERCENTAGE", "出资占比"), ORDER("ORDER", "自定义顺序"); /// </summary> [JsonPropertyName("budget_strategy")] public string BudgetStrategy { get; set; } /// <summary> /// 预算周期结束时间 /// </summary> [JsonPropertyName("end_cycle")] public string EndCycle { get; set; } /// <summary> /// 创建时间 /// </summary> [JsonPropertyName("gmt_create")] public string GmtCreate { get; set; } /// <summary> /// 修改时间 /// </summary> [JsonPropertyName("gmt_modified")] public string GmtModified { get; set; } /// <summary> /// 申请id /// </summary> [JsonPropertyName("id")] public string Id { get; set; } /// <summary> /// 活动预算池编码 /// </summary> [JsonPropertyName("pool_code")] public string PoolCode { get; set; } /// <summary> /// 状态:CONFIG,CONFIG_DONE,CHECK,ACTIVE,HISTORY,CLOSE,DISCARD,INACTIVE /// </summary> [JsonPropertyName("status")] public string Status { get; set; } /// <summary> /// 采购用途 /// </summary> [JsonPropertyName("use")] public string Use { get; set; } } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@ViewData["Title"] - Blog_demo</title> <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" /> <link rel="stylesheet" href="~/css/site.css" /> </head> <body> <header> <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3"> <div class="container"> <a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">Blog_demo</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between"> <ul class="navbar-nav flex-grow-1"> <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a> </li> <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a> </li> </ul> </div> </div> </nav> </header> <div class="container"> <main role="main" class="pb-3"> @RenderBody() </main> </div> <footer class="border-top footer text-muted"> <div class="container"> &copy; 2021 - Blog_demo - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a> </div> </footer> <script src="~/lib/jquery/dist/jquery.min.js"></script> <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script> <script src="~/js/site.js" asp-append-version="true"></script> @await RenderSectionAsync("Scripts", required: false) </body> </html>
using System; using System.Collections.Generic; using System.Text; namespace BHackerOverhaul.FileHandler { public class HeaderReader { public string ReadHeader(byte[] file) { string OutPut = ""; UInt32 Length = ByteTools.Read4Bytes(file, (UInt32)0x4); OutPut += string.Format("Header length: {0}{1}", Length, Environment.NewLine + Environment.NewLine); int Inpos = 0xC; for (int i = 0; i < Length; i++) { string InHex = Inpos.ToString("X"); OutPut += string.Format("Data offset in file: {0}", InHex + Environment.NewLine); UInt32 OffsetterInt = ByteTools.Read4Bytes(file, (UInt32)(Inpos)); OutPut += string.Format("{2}: Unknown Int: {0}{1}", OffsetterInt, Environment.NewLine, i); byte[] Floater = new byte[4]; for (int j = 0; j != 4; j++) { Floater[j] = file[Inpos + j + 4]; } Array.Reverse(Floater); float UnknownFloat = BitConverter.ToSingle(Floater, 0); OutPut += string.Format("{2}: Unknown Float: {0}{1}", UnknownFloat, Environment.NewLine, i); UInt32 UnknownInt = ByteTools.Read4Bytes(file, (UInt32)(Inpos + 8)); string hexValue = UnknownInt.ToString("X"); OutPut += string.Format("{2}: Offset: {0}{1}", hexValue, Environment.NewLine + Environment.NewLine, i); Inpos += 0xC; } return OutPut; } public int[] ReadOffsets(byte[] file) { List<int> OutPut = new List<int>(); UInt32 Length = ByteTools.Read4Bytes(file, (UInt32)0x4); int Inpos = 0xC; for (int i = 0; i < Length; i++) { UInt32 UnknownInt = ByteTools.Read4Bytes(file, (UInt32)(Inpos + 8)); string hexValue = UnknownInt.ToString("X"); OutPut.Add((int)UnknownInt); Inpos += 0xC; } return OutPut.ToArray(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using MFiles.VAF.Common; using MFilesAPI; namespace MFiles.VAF.Extensions { /// <summary> /// Extension methods for the <see cref="MFSearchBuilder"/> class. /// </summary> // ReSharper disable once InconsistentNaming public static partial class MFSearchBuilderExtensionMethods { #region Boolean overloads /// <summary> /// Adds a <see cref="SearchCondition"/> to the collection for a <see cref="MFDataType.MFDatatypeBoolean"/> /// property definition. /// </summary> /// <param name="searchBuilder">The <see cref="MFSearchBuilder"/> to add the condition to.</param> /// <param name="propertyDef">The ID of the property to search by.</param> /// <param name="value">The value to search for.</param> /// <param name="conditionType">What type of search to execute (defaults to <see cref="MFConditionType.MFConditionTypeEqual"/>).</param> /// <param name="parentChildBehavior">Whether to accept matches to parent/child values as well (defaults to <see cref="MFParentChildBehavior.MFParentChildBehaviorNone"/>).</param> /// <param name="dataFunctionCall">An expression for modifying how the results of matches are evaluated (defaults to null).</param> /// <param name="indirectionLevels">The indirection levels (from the search object) to access the property to match.</param> /// <returns>The <paramref name="searchBuilder"/> provided, for chaining.</returns> public static MFSearchBuilder Property ( this MFSearchBuilder searchBuilder, int propertyDef, bool? value, MFConditionType conditionType = MFConditionType.MFConditionTypeEqual, MFParentChildBehavior parentChildBehavior = MFParentChildBehavior.MFParentChildBehaviorNone, PropertyDefOrObjectTypes indirectionLevels = null, DataFunctionCall dataFunctionCall = null ) { // Sanity. if (null == searchBuilder) throw new ArgumentNullException(nameof(searchBuilder)); if (0 > propertyDef) throw new ArgumentOutOfRangeException(nameof(propertyDef), Resources.Exceptions.VaultInteraction.PropertyDefinition_NotResolved); // What is the type of this property? var dataType = searchBuilder.Vault.PropertyDefOperations.GetPropertyDef(propertyDef).DataType; // If it is not valid then throw. if (dataType != MFDataType.MFDatatypeBoolean) throw new ArgumentException ( String.Format ( Resources.Exceptions.VaultInteraction.PropertyDefinition_NotOfExpectedType, propertyDef, string.Join(", ", new[] { MFDataType.MFDatatypeBoolean }) ), nameof(propertyDef) ); // Add the search condition. return searchBuilder.AddPropertyValueSearchCondition ( propertyDef, dataType, value, conditionType, parentChildBehavior, indirectionLevels, dataFunctionCall ); } #endregion } }
using Antrv.FFMpeg.Interop; namespace Antrv.FFMpeg.Model.Codecs; public abstract class Decoder: Coder { private protected Decoder(ConstPtr<AVCodec> ptr) : base(ptr, false) { } }
// Wi Advice (https://github.com/raste/WiAdvice)(http://www.wiadvice.com/) // Copyright (c) 2015 Georgi Kolev. // Licensed under Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0). using System; using System.Collections.Generic; using System.Web.UI.WebControls; using AjaxControlToolkit; using BusinessLayer; using DataAccess; namespace UserInterface { public partial class Statistics : BasePage { private Entities objectContext = null; private EntitiesUsers userContext = new EntitiesUsers(); protected void Page_Init(object sender, EventArgs e) { objectContext = CreateEntities(); } protected void Page_Load(object sender, EventArgs e) { SetNeedsToBeLogged(); CheckUser(); // checks user , redirrects if not admin ShowAtTheMoment(); // shows users label and button for showing online users ShowStatistics(null); ShowInfo(); } private void ShowInfo() { Title = "Statistics Page"; BusinessSiteText siteText = new BusinessSiteText(); SiteNews aboutExtended = siteText.GetSiteText(objectContext, "aboutStatistics"); if (aboutExtended != null && aboutExtended.visible) { lblAbout.Text = aboutExtended.description; } else { lblAbout.Text = "About statistics text not typed."; } CheckShowHideButtons(); } private void CheckUser() { BusinessUser businessUser = new BusinessUser(); User currUser = GetCurrentUser(userContext, objectContext); if (currUser != null && businessUser.IsFromAdminTeam(currUser)) { // ok .. } else { CommonCode.UiTools.RedirrectToErrorPage(Response, Session, "That page is for administrators only."); } } private void ShowAtTheMoment() { BusinessStatistics stats = new BusinessStatistics(); BusinessUser businessUser = new BusinessUser(); int loggedUsers = businessUser.GetLoggedUsers().Count; lblAtm.Text = string.Format("Currently online are : {0} guests, and {1} users.", businessUser.GetGuests(), loggedUsers); if (loggedUsers > 0) { btnShowRegOn.Visible = true; } else { btnShowRegOn.Visible = false; } } private void ShowStatistics(List<Statistic> Statistics) { tblLast5Days.Rows.Clear(); BusinessStatistics businessStatistics = new BusinessStatistics(); List<Statistic> stats = new List<Statistic>(); if (Statistics == null || Statistics.Count < 1) { stats = businessStatistics.GetLastNumStatistics(objectContext, 5); } else { stats = Statistics; } int count = stats.Count; if (count > 0) { TableRow zeroRow = new TableRow(); TableCell zeroCell = new TableCell(); zeroCell.CssClass = "textHeaderWA"; zeroCell.ColumnSpan = 13; zeroCell.HorizontalAlign = HorizontalAlign.Center; if (count == 1) { zeroCell.Text = string.Format("Statistic for {0}",stats[0].forDate.ToString("d", System.Globalization.CultureInfo.InvariantCulture)); } else { zeroCell.Text = string.Format("Statistics for last {0} days", count); } zeroRow.Cells.Add(zeroCell); tblLast5Days.Rows.Add(zeroRow); ShowFirstAndSecRowForLastDaysStatsTable(); foreach(Statistic statistic in stats) { // date , users , admins , products , prod char , companies , comp char // categries , pictures , comments , reports , sessions , users L/O TableRow newRow = new TableRow(); TableCell DateCell = new TableCell(); DateCell.CssClass = "commentsDate"; DateCell.Text = statistic.forDate.ToShortDateString(); newRow.Cells.Add(DateCell); TableCell usersCell = new TableCell(); usersCell.Text = string.Format("{0} / {1}", statistic.usersRegistered,statistic.usersDeleted); newRow.Cells.Add(usersCell); TableCell adminsCell = new TableCell(); adminsCell.Text = string.Format("{0} / {1}", statistic.adminsRegistered,statistic.adminsDeleted); newRow.Cells.Add(adminsCell); TableCell prodCell = new TableCell(); prodCell.Text = string.Format("{0} / {1}", statistic.productsCreated,statistic.productsDeleted); newRow.Cells.Add(prodCell); TableCell prodChCell = new TableCell(); prodChCell.Text = string.Format("{0} / {1}", statistic.prodCharsCreated,statistic.prodCharsDeleted); newRow.Cells.Add(prodChCell); TableCell compCell = new TableCell(); compCell.Text = string.Format("{0} / {1}", statistic.companiesCreated,statistic.companiesDeleted); newRow.Cells.Add(compCell); TableCell compChCell = new TableCell(); compChCell.Text = string.Format("{0} / {1}", statistic.compCharsCreated,statistic.compCharsDeleted); newRow.Cells.Add(compChCell); TableCell catCell = new TableCell(); catCell.Text = string.Format("{0} / {1}", statistic.categoriesCreated,statistic.categoriesDeleted); newRow.Cells.Add(catCell); TableCell picCell = new TableCell(); picCell.Text = string.Format("{0} / {1}", statistic.picturesUploaded,statistic.picturesDeleted); newRow.Cells.Add(picCell); TableCell commCell = new TableCell(); commCell.Text = string.Format("{0} / {1}", statistic.commentsWritten, statistic.commentsDeleted); newRow.Cells.Add(commCell); TableCell topicCell = new TableCell(); topicCell.Text = string.Format("{0} / {1}", statistic.topicsCreated, statistic.topicsDeleted); newRow.Cells.Add(topicCell); TableCell repCell = new TableCell(); repCell.Text = statistic.reportsWritten.ToString(); newRow.Cells.Add(repCell); TableCell usrLoCell = new TableCell(); usrLoCell.Text = string.Format("{0} / {1}", statistic.usersLogged, statistic.usersLoggedOut); newRow.Cells.Add(usrLoCell); tblLast5Days.Rows.Add(newRow); } } else { tblLast5Days.Visible = false; } } private void ShowFirstAndSecRowForLastDaysStatsTable() { TableRow firstRow = new TableRow(); TableCell empCell = new TableCell(); firstRow.Cells.Add(empCell); TableCell createDelCell = new TableCell(); createDelCell.ColumnSpan = 10; createDelCell.HorizontalAlign = HorizontalAlign.Center; createDelCell.Text = "Created/Deleted"; firstRow.Cells.Add(createDelCell); TableCell writtenCell = new TableCell(); writtenCell.ColumnSpan = 1; writtenCell.HorizontalAlign = HorizontalAlign.Center; writtenCell.Text = "Written"; firstRow.Cells.Add(writtenCell); TableCell otherCell = new TableCell(); otherCell.ColumnSpan = 1; otherCell.HorizontalAlign = HorizontalAlign.Center; otherCell.Text = "others"; firstRow.Cells.Add(otherCell); tblLast5Days.Rows.Add(firstRow); TableRow secRow = new TableRow(); TableCell dateCell = new TableCell(); dateCell.Text = "Date"; secRow.Cells.Add(dateCell); /// TableCell usersCell = new TableCell(); usersCell.Text = "users"; secRow.Cells.Add(usersCell); TableCell adminsCell = new TableCell(); adminsCell.Text = "admins"; secRow.Cells.Add(adminsCell); TableCell prodsCell = new TableCell(); prodsCell.Text = "products"; secRow.Cells.Add(prodsCell); TableCell prodChCell = new TableCell(); prodChCell.Text = "prod Chars"; secRow.Cells.Add(prodChCell); TableCell compCell = new TableCell(); compCell.Text = string.Format("{0}s", Configuration.CompanyName); secRow.Cells.Add(compCell); TableCell compChCell = new TableCell(); compChCell.Text = "comp Chars"; secRow.Cells.Add(compChCell); TableCell catCell = new TableCell(); catCell.Text = "categories"; secRow.Cells.Add(catCell); TableCell picCell = new TableCell(); picCell.Text = "pictures"; secRow.Cells.Add(picCell); TableCell commCell = new TableCell(); commCell.Text = "comments"; secRow.Cells.Add(commCell); TableCell topicCell = new TableCell(); topicCell.Text = "topics"; secRow.Cells.Add(topicCell); //// TableCell repCell = new TableCell(); repCell.Text = "reports"; secRow.Cells.Add(repCell); TableCell usrLOCell = new TableCell(); usrLOCell.Text = "users L/O "; secRow.Cells.Add(usrLOCell); tblLast5Days.Rows.Add(secRow); } protected void btnShowStats_Click(object sender, EventArgs e) { phShowStats.Visible = true; phShowStats.Controls.Add(lblError); String strDate = tbDate.Text; String strNum = tbNum.Text; if (string.IsNullOrEmpty(strDate) && string.IsNullOrEmpty(strNum)) { lblError.Text = "Type date or number"; } else if (!string.IsNullOrEmpty(strDate) && !string.IsNullOrEmpty(strNum)) { lblError.Text = "Type only date or number"; } else { BusinessStatistics businessStatistics = new BusinessStatistics(); if (strDate.Length > 0) { DateTime newTime = new DateTime(); if (Tools.ParseStringToDateTime(strDate, out newTime) == true) { Statistic currStat = businessStatistics.Get(objectContext, newTime); if (currStat == null) { lblError.Text = string.Format("No statistics for date {0}", newTime.ToShortDateString()); } else { phShowStats.Visible = false; List<Statistic> Stat = new List<Statistic>(); Stat.Add(currStat); ShowStatistics(Stat); } } else { lblError.Text = "Type correct date."; } } if (strNum.Length > 0) { long number = -1; if (long.TryParse(strNum, out number)) { if (number > 0) { List<Statistic> Stats = businessStatistics.GetLastNumStatistics(objectContext, number); if (Stats.Count > 0) { phShowStats.Visible = false; ShowStatistics(Stats); } else { lblError.Text = "No statistics."; } } else { lblError.Text = "Number must be positive"; } } else { lblError.Text = "Type correct number"; } } } } protected void cExpireDate_SelectionChanged(object sender, EventArgs e) { if (!string.IsNullOrEmpty(cExpireDate.SelectedDate.ToString())) { string dateStr = Tools.ParseDateTimeToString(cExpireDate.SelectedDate); PopupControlExtender.GetProxyForCurrentPopup(Page).Commit(dateStr); } } private void CheckShowHideButtons() { if (btnShowRegOn.Text == "Hide logged users") { tblShowRegOn.Visible = true; ShowLoggedOnlineUsers(); } } protected void btnShowRegOn_Click(object sender, EventArgs e) { if (btnShowRegOn.Text == "Show logged users") { btnShowRegOn.Text = "Hide logged users"; tblShowRegOn.Visible = true; ShowLoggedOnlineUsers(); } else { btnShowRegOn.Text = "Show logged users"; tblShowRegOn.Visible = false; } } private void ShowLoggedOnlineUsers() { BusinessUser businessUser = new BusinessUser(); List<User> loggedUsers = businessUser.GetLoggedUsers(userContext); tblShowRegOn.Rows.Clear(); TableRow firstRow = new TableRow(); tblShowRegOn.Rows.Add(firstRow); TableCell firstCell = new TableCell(); firstRow.Cells.Add(firstCell); firstCell.CssClass = "textHeaderWA"; firstCell.HorizontalAlign = HorizontalAlign.Center; if (loggedUsers.Count > 0) { firstCell.Text = "Currently logged users"; TableRow currentRow = new TableRow(); tblShowRegOn.Rows.Add(currentRow); int i = 0; foreach (User user in loggedUsers) { if (i % 4 == 0) { currentRow = new TableRow(); tblShowRegOn.Rows.Add(currentRow); } TableCell userCell = new TableCell(); currentRow.Cells.Add(userCell); userCell.HorizontalAlign = HorizontalAlign.Center; userCell.Width = Unit.Percentage(25); HyperLink userLink = CommonCode.UiTools.GetUserHyperLink(user); userCell.Controls.Add(userLink); if (businessUser.IsFromAdminTeam(user)) { userLink.ForeColor = System.Drawing.Color.Red; } i++; } if (i > 4) { firstCell.ColumnSpan = 4; } else { firstCell.ColumnSpan = i; } } else { firstCell.Text = "Currently there are no logged users."; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using DG.Tweening; using System; using UnityEngine.EventSystems; public class PlayerMovement : MonoBehaviour { public Collider2D collider2d; [HideInInspector] public Rigidbody2D rigidbody2d; private Collision collision; private Animator animator; private AnimationScript animationScript; private SpriteRenderer sprite; private DialogueManager dialogueManager; private SoundManager soundManager; private PauseManager pauseManager; private Fade fade; public JoystickTest joystick; private Vector3 moveVector; // 플레이어 이동벡터 [Space] [Header("움직임")] public float moveSpeed = 10; public float jumpPower = 50; public bool jumpFlag; public bool jumpIsRunning; public bool canDoubleJump = true; public bool canMove = false; public bool pause = false; private bool groundTouch; private bool isDie; private bool pauseFlag = false; public bool forceMoveMode = false; public bool moveIsEnd = false; #region TEMP TRASH /* public float slideSpeed = 5; public float wallJumpLerp = 10; public float dashSpeed = 20; public bool hasDashed; public bool wallGrab; public bool wallJumped; public bool wallSlide; public bool isDashing; public ParticleSystem dashParticle; public ParticleSystem wallJumpParticle; public ParticleSystem slideParticle; */ #endregion public int side = 1; public ParticleSystem jumpParticle; public bool canGoDown = false; public PlatformEffector2D effector; [Space] [Header("공격")] public float cooldown = 0.5f; // Combo Attack Cooldown public float maxTime = 0.8f; // Accepted Combo Limit Time public int maxCombo; // Combo Attack Max Count private int combo = 0; // Current Combo Count private float lastTime; // Last Attack Time [Space] [Header("체력")] public int maxHP = 10; public int HP = 10; [Space] [Header("대화")] public bool isTalking = false; private bool nextDialogue; void Start() { collision = GetComponent<Collision>(); rigidbody2d = GetComponent<Rigidbody2D>(); animationScript = GetComponentInChildren<AnimationScript>(); animator = GetComponentInChildren<Animator>(); sprite = GetComponentInChildren<SpriteRenderer>(); soundManager = GameObject.Find("Sound Manager").GetComponent<SoundManager>(); dialogueManager = GameObject.Find("Canvas").GetComponent<DialogueManager>(); pauseManager = GameObject.Find("Pause Manager").GetComponent<PauseManager>(); fade = GameObject.Find("Fade").GetComponent<Fade>(); collider2d = GetComponent<Collider2D>(); } #region ONCLICK EVENT public void OnClickJump() { jumpFlag = true; jumpIsRunning = true; } public void OnClickNextDialogue() { nextDialogue = true; } public void OnClickRotateEffector() { StartCoroutine(CoRotatePlatform(0.5f)); } #endregion void Update() { #region TEMP TRASH /* float x = Input.GetAxis("Horizontal"); float y = Input.GetAxis("Vertical"); float xRaw = Input.GetAxisRaw("Horizontal"); float yRaw = Input.GetAxisRaw("Vertical"); Vector2 dir = new Vector2(x, y); */ #endregion HandleInput(); // 조이스틱 입력 받기. Walk(moveVector); if (!forceMoveMode) { animationScript.SetHorizontalMovement(moveVector.x, moveVector.y, rigidbody2d.velocity.y); } if (pause) { //pauseManager.Pause(this.gameObject, false); canMove = false; pauseFlag = true; } else if (!pause && pauseFlag) { //pauseManager.Release(this.gameObject, "Player"); canMove = true; pauseFlag = false; } if (isTalking && nextDialogue) { nextDialogue = false; dialogueManager.DisplayNextSentence(); } if (HP == 0) { Pause(); // Die Coroutine and Game End... } if (jumpFlag) { animationScript.SetTrigger("jump"); if (!collision.onGround && canDoubleJump) { Jump(Vector2.up, false); canDoubleJump = false; } if (collision.onGround) // 바닥에서 시작할때 { Jump(Vector2.up, false); } jumpFlag = false; #region TEMP TRASH /* if (collision.onWall && !collision.onGround) { WallJump(); } */ #endregion } #region TEMP TRASH /* if (Input.GetButtonDown("Dash"))//&& !hasDashed) { if (xRaw != 0 || yRaw != 0) { Debug.Log(xRaw + " " + yRaw); Dash(xRaw, yRaw); } } if (collision.onWall && Input.GetButton("Interact") && canMove) { if (side != collision.wallSide) animationScript.Flip(side * -1); wallGrab = true; wallSlide = false; } if (Input.GetButtonUp("Interact") || !collision.onWall || !canMove) { wallGrab = false; wallSlide = false; } */ #endregion if (collision.onGround) { canDoubleJump = true; } #region TEMP TRASH /* if (collision.onGround && !isDashing) { wallJumped = false; } if (wallGrab && !isDashing) { rigidbody2d.gravityScale = 0; if (x > 0.2f || x < -0.2f) { rigidbody2d.velocity = new Vector2(rigidbody2d.velocity.x, 0); } float speedModifier = y > 0 ? 0.5f : 1; rigidbody2d.velocity = new Vector2(rigidbody2d.velocity.x, y * (moveSpeed * speedModifier)); } else { rigidbody2d.gravityScale = 3; } if (collision.onWall && !collision.onGround) { if (x != 0 && !wallGrab) { wallSlide = true; WallSlide(); } } if (!collision.onWall || collision.onGround) { wallSlide = false; } */ #endregion if (collision.onGround && !groundTouch) { GroundTouch(); groundTouch = true; } if (!collision.onGround && groundTouch) { groundTouch = false; } #region TEMP TRASH /* WallParticle(y); if (wallGrab || wallSlide) return; */ #endregion if (moveVector.x > 0) { side = 1; animationScript.Flip(side); } if (moveVector.x < 0) { side = -1; animationScript.Flip(side); } } void Walk(Vector2 dir) { if (!canMove) return; #region TEMP TRASH /* if (wallGrab) return; if (!wallJumped) { // 원래 여깄었음. } else { rigidbody2d.velocity = Vector2.Lerp(rigidbody2d.velocity, (new Vector2(dir.x * moveSpeed, rigidbody2d.velocity.y)), wallJumpLerp * Time.deltaTime); } */ #endregion rigidbody2d.velocity = new Vector2(dir.x * moveSpeed, rigidbody2d.velocity.y); } #region TEMP TRASH /* private void Dash(float x, float y) { Camera.main.transform.DOComplete(); Camera.main.transform.DOShakePosition(.2f, .5f, 14, 90, false, true); FindObjectOfType<RippleEffect>().Emit(Camera.main.WorldToViewportPoint(transform.position)); hasDashed = true; animationScript.SetTrigger("dash"); rigidbody2d.velocity = Vector2.zero; Vector2 dir = new Vector2(x, y); rigidbody2d.velocity += dir.normalized * dashSpeed; StartCoroutine(CoDashWait()); } private void WallJump() { if ((side == 1 && collision.onRightWall) || (side == -1 && !collision.onRightWall)) { side *= -1; animationScript.Flip(side); } StopCoroutine(CoDisableMovement(0)); StartCoroutine(CoDisableMovement(0.1f)); Vector2 wallDir = collision.onRightWall ? Vector2.left : Vector2.right; Jump((Vector2.up / 1.5f + wallDir / 1.5f), true); wallJumped = true; } private void WallSlide() { if (collision.wallSide != side) { animationScript.Flip(side * -1); } if (!canMove) return; bool pushingWall = false; if ((rigidbody2d.velocity.x > 0 && collision.onRightWall) || (rigidbody2d.velocity.x < 0 && collision.onLeftWall)) { pushingWall = true; } float push = pushingWall ? 0 : rigidbody2d.velocity.x; rigidbody2d.velocity = new Vector2(push, -slideSpeed); } private void RigidbodyDrag(float x) { rigidbody2d.drag = x; } private void WallParticle(float vertical) { var main = slideParticle.main; if (wallSlide || (wallGrab && vertical < 0)) { slideParticle.transform.parent.localScale = new Vector3(ParticleSide(), 1, 1); main.startColor = Color.white; } else { main.startColor = Color.clear; } } private IEnumerator CoDashWait() { FindObjectOfType<GhostTrail>().ShowGhost(); StartCoroutine(CoGroundDash()); DOVirtual.Float(14, 0, .8f, RigidbodyDrag); dashParticle.Play(); rigidbody2d.gravityScale = 0; GetComponent<BetterJumping>().enabled = false; wallJumped = true; isDashing = true; yield return new WaitForSeconds(.3f); dashParticle.Stop(); rigidbody2d.gravityScale = 3; GetComponent<BetterJumping>().enabled = true; wallJumped = false; isDashing = false; } private IEnumerator CoGroundDash() { yield return new WaitForSeconds(0.15f); if (collision.onGround) hasDashed = false; } */ #endregion private void Jump(Vector2 dir, bool wall) { soundManager.PlaySfx(soundManager.EffectSounds[3]); #region TEMP TRASH /* slideParticle.transform.parent.localScale = new Vector3(ParticleSide(), 1, 1); ParticleSystem particle = wall ? wallJumpParticle : jumpParticle; */ #endregion ParticleSystem particle = jumpParticle; rigidbody2d.velocity = new Vector2(rigidbody2d.velocity.x, 0); rigidbody2d.velocity += dir * jumpPower; particle.Play(); } public void HandleInput() { moveVector = PoolInput(); } public Vector3 PoolInput() { float horizontal = joystick.GetHorizontalValue(); float vertical = joystick.GetVerticalValue(); Vector3 moveDir = new Vector3(horizontal, vertical, 0).normalized; return moveDir; } public void Flip(string direction) { switch(direction) { case "RIGHT": transform.localScale = new Vector3(1, 1, 1); break; case "LEFT": transform.localScale = new Vector3(-1, 1, 1); break; } } public void ForcePlayFallAnim() { rigidbody2d.bodyType = RigidbodyType2D.Kinematic; rigidbody2d.velocity = Vector2.down; } public void ForceStopFallAnim() { rigidbody2d.bodyType = RigidbodyType2D.Dynamic; rigidbody2d.velocity = Vector2.zero; } public void ForcePlayMoveAnim() { forceMoveMode = true; animator.SetFloat("HorizontalAxis", 1); } public void ForceStopMoveAnim() { forceMoveMode = false; animator.SetFloat("HorizontalAxis", 0); } private void MoveOnlyX(float _xEndPos, float moveTime) { moveIsEnd = false; float xEndPos = _xEndPos; transform .DOMoveX(xEndPos, moveTime) .SetEase(Ease.InOutQuart) .OnComplete(EndMove); } void EndMove() { moveIsEnd = true; } public void BackToOriginPos(Transform origin, float move_time) { StartCoroutine(CoBackToOriginPos(origin.position.x, move_time)); } private IEnumerator CoBackToOriginPos(float _xEndPos, float moveTime) { MoveOnlyX(_xEndPos, moveTime); yield return new WaitUntil(()=>moveIsEnd); } public void Pause() { canMove = false; } public void Release() { canMove = true; } public void ChangePos(Vector3 pos) { gameObject.transform.position = pos; } private void GroundTouch() { // hasDashed = false; // isDashing = false; side = animationScript.sr.flipX ? -1 : 1; jumpParticle.Play(); } private int ParticleSide() { int particleSide = collision.onRightWall ? 1 : -1; return particleSide; } private IEnumerator CoRotatePlatform(float waitTime) { canGoDown = true; effector.rotationalOffset = 180; yield return new WaitForSeconds(waitTime); effector.rotationalOffset = 0; canGoDown = false; } private IEnumerator CoDisableMovement(float time) { canMove = false; yield return new WaitForSeconds(time); canMove = true; } private IEnumerator CoMeleeAttack() { // Constantly loops so you only have to call it once while(true) { // Checks if attacking and then starts of the combo if (Input.GetKeyDown(KeyCode.Q)) { canMove = false; combo++; animator.SetBool("isAttacking", true); animator.SetInteger("attackCount", combo); lastTime = Time.time; //Combo loop that ends the combo if you reach the maxTime between attacks, or reach the end of the combo while((Time.time - lastTime) < maxTime && combo < maxCombo) { // Attacks if your cooldown has reset if (Input.GetKeyDown(KeyCode.Q) && (Time.time - lastTime) > cooldown) { combo++; animator.SetInteger("attackCount", combo); lastTime = Time.time; } yield return null; } // Resets combo and waits the remaining amount of cooldown time before you can attack again to restart the combo canMove = true; combo = 0; animator.SetBool("isAttacking", false); animator.SetInteger("attackCount", combo); yield return new WaitForSeconds(cooldown - (Time.time - lastTime)); } yield return null; } } }
namespace System; partial class Optional { public static Optional<Unit> True() => new(default); public static Optional<Unit> False() => default; }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Transactions; using Autofac; using ChinhDo.Transactions.FileManager; using CKAN.Versioning; using CKAN.Configuration; using log4net; namespace CKAN { /// <summary> /// Manage multiple KSP installs. /// </summary> public class KSPManager : IDisposable { public IUser User { get; set; } public IConfiguration Configuration { get; set; } public KSP CurrentInstance { get; set; } public NetModuleCache Cache { get; private set; } private static readonly ILog log = LogManager.GetLogger(typeof (KSPManager)); private readonly SortedList<string, KSP> instances = new SortedList<string, KSP>(); public string AutoStartInstance { get { return HasInstance(Configuration.AutoStartInstance) ? Configuration.AutoStartInstance : null; } private set { if (!String.IsNullOrEmpty(value) && !HasInstance(value)) { throw new InvalidKSPInstanceKraken(value); } Configuration.AutoStartInstance = value; } } public SortedList<string, KSP> Instances { get { return new SortedList<string, KSP>(instances); } } public KSPManager(IUser user, IConfiguration configuration = null) { User = user; Configuration = configuration ?? ServiceLocator.Container.Resolve<IConfiguration>(); LoadInstancesFromRegistry(); } /// <summary> /// Returns the prefered KSP instance, or null if none can be found. /// /// This works by checking to see if we're in a KSP dir first, then the /// registry for an autostart instance, then will try to auto-populate /// by scanning for the game. /// /// This *will not* touch the registry if we find a portable install. /// /// This *will* run KSP instance autodetection if the registry is empty. /// /// This *will* set the current instance, or throw an exception if it's already set. /// /// Returns null if we have multiple instances, but none of them are preferred. /// </summary> public KSP GetPreferredInstance() { CurrentInstance = _GetPreferredInstance(); return CurrentInstance; } // Actual worker for GetPreferredInstance() internal KSP _GetPreferredInstance() { // First check if we're part of a portable install // Note that this *does not* register in the registry. string path = KSP.PortableDir(); if (path != null) { KSP portableInst = new KSP(path, "portable", User); if (portableInst.Valid) { return portableInst; } } // If we only know of a single instance, return that. if (instances.Count == 1 && instances.First().Value.Valid) { return instances.First().Value; } // Return the autostart, if we can find it. // We check both null and "" as we can't write NULL to the registry, so we write an empty string instead // This is necessary so we can indicate that the user wants to reset the current AutoStartInstance without clearing the windows registry keys! if (!string.IsNullOrEmpty(AutoStartInstance) && instances[AutoStartInstance].Valid) { return instances[AutoStartInstance]; } // If we know of no instances, try to find one. // Otherwise, we know of too many instances! // We don't know which one to pick, so we return null. return !instances.Any() ? FindAndRegisterDefaultInstance() : null; } /// <summary> /// Find and register a default instance by running /// game autodetection code. /// /// Returns the resulting KSP object if found. /// </summary> public KSP FindAndRegisterDefaultInstance() { if (instances.Any()) throw new KSPManagerKraken("Attempted to scan for defaults with instances in registry"); try { string gamedir = KSP.FindGameDir(); KSP foundInst = new KSP(gamedir, "auto", User); return foundInst.Valid ? AddInstance(foundInst) : null; } catch (DirectoryNotFoundException) { return null; } catch (NotKSPDirKraken) { return null; } } /// <summary> /// Adds a KSP instance to registry. /// Returns the resulting KSP object. /// </summary> public KSP AddInstance(KSP ksp_instance) { if (ksp_instance.Valid) { string name = ksp_instance.Name; instances.Add(name, ksp_instance); Configuration.SetRegistryToInstances(instances); } else { throw new NotKSPDirKraken(ksp_instance.GameDir()); } return ksp_instance; } /// <summary> /// Clones an existing KSP installation. /// </summary> /// <param name="existingInstance">The KSP instance to clone.</param> /// <param name="newName">The name for the new instance.</param> /// <param name="newPath">The path where the new instance should be located.</param> /// <exception cref="InstanceNameTakenKraken">Thrown if the instance name is already in use.</exception> /// <exception cref="NotKSPDirKraken">Thrown by AddInstance() if created instance is not valid, e.g. if something went wrong with copying.</exception> /// <exception cref="DirectoryNotFoundKraken">Thrown by CopyDirectory() if directory doesn't exist. Should never be thrown here.</exception> /// <exception cref="PathErrorKraken">Thrown by CopyDirectory() if the target folder already exists and is not empty.</exception> /// <exception cref="IOException">Thrown by CopyDirectory() if something goes wrong during the process.</exception> public void CloneInstance(KSP existingInstance, string newName, string newPath) { if (HasInstance(newName)) { throw new InstanceNameTakenKraken(newName); } if (!existingInstance.Valid) { throw new NotKSPDirKraken(existingInstance.GameDir(), "The specified instance is not a valid KSP instance."); } log.Debug("Copying directory."); Utilities.CopyDirectory(existingInstance.GameDir(), newPath, true); // Add the new instance to the registry KSP new_instance = new KSP(newPath, newName, User); AddInstance(new_instance); } /// <summary> /// Create a new fake KSP instance /// </summary> /// <param name="newName">The name for the new instance.</param> /// <param name="newPath">The loaction of the new instance.</param> /// <param name="version">The version of the new instance. Should have a build number.</param> /// <param name="dlcs">The IDlcDetector implementations for the DLCs that should be faked and the requested dlc version as a dictionary.</param> /// <exception cref="InstanceNameTakenKraken">Thrown if the instance name is already in use.</exception> /// <exception cref="NotKSPDirKraken">Thrown by AddInstance() if created instance is not valid, e.g. if a write operation didn't complete for whatever reason.</exception> public void FakeInstance(string newName, string newPath, KspVersion version, Dictionary<DLC.IDlcDetector, KspVersion> dlcs = null) { TxFileManager fileMgr = new TxFileManager(); using (TransactionScope transaction = CkanTransaction.CreateTransactionScope()) { if (HasInstance(newName)) { throw new InstanceNameTakenKraken(newName); } if (!version.InBuildMap()) { throw new BadKSPVersionKraken(String.Format("The specified KSP version is not a known version: {0}", version.ToString())); } if (Directory.Exists(newPath) && (Directory.GetFiles(newPath).Length != 0 || Directory.GetDirectories(newPath).Length != 0)) { throw new BadInstallLocationKraken("The specified folder already exists and is not empty."); } log.DebugFormat("Creating folder structure and text files at {0} for KSP version {1}", Path.GetFullPath(newPath), version.ToString()); // Create a KSP root directory, containing a GameData folder, a buildID.txt/buildID64.txt and a readme.txt fileMgr.CreateDirectory(newPath); fileMgr.CreateDirectory(Path.Combine(newPath, "GameData")); fileMgr.CreateDirectory(Path.Combine(newPath, "Ships")); fileMgr.CreateDirectory(Path.Combine(newPath, "Ships", "VAB")); fileMgr.CreateDirectory(Path.Combine(newPath, "Ships", "SPH")); fileMgr.CreateDirectory(Path.Combine(newPath, "Ships", "@thumbs")); fileMgr.CreateDirectory(Path.Combine(newPath, "Ships", "@thumbs", "VAB")); fileMgr.CreateDirectory(Path.Combine(newPath, "Ships", "@thumbs", "SPH")); fileMgr.CreateDirectory(Path.Combine(newPath, "saves")); fileMgr.CreateDirectory(Path.Combine(newPath, "saves", "scenarios")); fileMgr.CreateDirectory(Path.Combine(newPath, "saves", "training")); // Don't write the buildID.txts if we have no build, otherwise it would be -1. if (version.IsBuildDefined) { fileMgr.WriteAllText(Path.Combine(newPath, "buildID.txt"), String.Format("build id = {0}", version.Build)); fileMgr.WriteAllText(Path.Combine(newPath, "buildID64.txt"), String.Format("build id = {0}", version.Build)); } // Create the readme.txt WITHOUT build number. fileMgr.WriteAllText(Path.Combine(newPath, "readme.txt"), String.Format("Version {0}", new KspVersion(version.Major, version.Minor, version.Patch).ToString())); // Create the needed folder structure and the readme.txt for DLCs that should be simulated. if (dlcs != null) { foreach (KeyValuePair<DLC.IDlcDetector, KspVersion> dlc in dlcs) { DLC.IDlcDetector dlcDetector = dlc.Key; KspVersion dlcVersion = dlc.Value; if (!dlcDetector.AllowedOnBaseVersion(version)) throw new WrongKSPVersionKraken( version, String.Format("KSP version {0} or above is needed for {1} DLC.", dlcDetector.ReleaseGameVersion, dlcDetector.IdentifierBaseName )); string dlcDir = Path.Combine(newPath, dlcDetector.InstallPath()); fileMgr.CreateDirectory(dlcDir); fileMgr.WriteAllText( Path.Combine(dlcDir, "readme.txt"), String.Format("Version {0}", dlcVersion)); } } // Add the new instance to the registry KSP new_instance = new KSP(newPath, newName, User, false); AddInstance(new_instance); transaction.Complete(); } } /// <summary> /// Given a string returns a unused valid instance name by postfixing the string /// </summary> /// <returns> A unused valid instance name.</returns> /// <param name="name">The name to use as a base.</param> /// <exception cref="CKAN.Kraken">Could not find a valid name.</exception> public string GetNextValidInstanceName(string name) { // Check if the current name is valid. if (InstanceNameIsValid(name)) { return name; } // Try appending a number to the name. var validName = Enumerable.Repeat(name, 1000) .Select((s, i) => s + " (" + i + ")") .FirstOrDefault(InstanceNameIsValid); if (validName != null) { return validName; } // Check if a name with the current timestamp is valid. validName = name + " (" + DateTime.Now + ")"; if (InstanceNameIsValid(validName)) { return validName; } // Give up. throw new Kraken("Could not return a valid name for the new instance."); } /// <summary> /// Check if the instance name is valid. /// </summary> /// <returns><c>true</c>, if name is valid, <c>false</c> otherwise.</returns> /// <param name="name">Name to check.</param> private bool InstanceNameIsValid(string name) { // Discard null, empty strings and white space only strings. // Look for the current name in the list of loaded instances. return !String.IsNullOrWhiteSpace(name) && !HasInstance(name); } /// <summary> /// Removes the instance from the registry and saves. /// </summary> public void RemoveInstance(string name) { instances.Remove(name); Configuration.SetRegistryToInstances(instances); } /// <summary> /// Renames an instance in the registry and saves. /// </summary> public void RenameInstance(string from, string to) { // TODO: What should we do if our target name already exists? KSP ksp = instances[from]; instances.Remove(from); ksp.Name = to; instances.Add(to, ksp); Configuration.SetRegistryToInstances(instances); } /// <summary> /// Sets the current instance. /// Throws an InvalidKSPInstanceKraken if not found. /// </summary> public void SetCurrentInstance(string name) { if (!HasInstance(name)) { throw new InvalidKSPInstanceKraken(name); } else if (!instances[name].Valid) { throw new NotKSPDirKraken(instances[name].GameDir()); } // Don't try to Dispose a null CurrentInstance. if (CurrentInstance != null && !CurrentInstance.Equals(instances[name])) { // Dispose of the old registry manager, to release the registry. RegistryManager.Instance(CurrentInstance)?.Dispose(); } CurrentInstance = instances[name]; } public void SetCurrentInstanceByPath(string path) { KSP ksp = new KSP(path, "custom", User); if (ksp.Valid) { CurrentInstance = ksp; } else { throw new NotKSPDirKraken(ksp.GameDir()); } } /// <summary> /// Sets the autostart instance in the registry and saves it. /// </summary> public void SetAutoStart(string name) { if (!HasInstance(name)) { throw new InvalidKSPInstanceKraken(name); } else if (!instances[name].Valid) { throw new NotKSPDirKraken(instances[name].GameDir()); } AutoStartInstance = name; } public bool HasInstance(string name) { return instances.ContainsKey(name); } public void ClearAutoStart() { Configuration.AutoStartInstance = null; } public void LoadInstancesFromRegistry() { log.Info("Loading KSP instances from registry"); instances.Clear(); foreach (Tuple<string, string> instance in Configuration.GetInstances()) { var name = instance.Item1; var path = instance.Item2; log.DebugFormat("Loading {0} from {1}", name, path); // Add unconditionally, sort out invalid instances downstream instances.Add(name, new KSP(path, name, User)); } if (!Directory.Exists(Configuration.DownloadCacheDir)) { Directory.CreateDirectory(Configuration.DownloadCacheDir); } string failReason; TrySetupCache(Configuration.DownloadCacheDir, out failReason); } /// <summary> /// Switch to using a download cache in a new location /// </summary> /// <param name="path">Location of folder for new cache</param> /// <returns> /// true if successful, false otherwise /// </returns> public bool TrySetupCache(string path, out string failureReason) { string origPath = Configuration.DownloadCacheDir; try { if (string.IsNullOrEmpty(path)) { Configuration.DownloadCacheDir = ""; Cache = new NetModuleCache(this, Configuration.DownloadCacheDir); } else { Cache = new NetModuleCache(this, path); Configuration.DownloadCacheDir = path; } failureReason = null; return true; } catch (DirectoryNotFoundKraken) { failureReason = $"{path} does not exist"; return false; } catch (PathErrorKraken ex) { failureReason = ex.Message; return false; } catch (IOException ex) { // MoveFrom failed, possibly full disk, so undo the change Configuration.DownloadCacheDir = origPath; failureReason = ex.Message; return false; } } /// <summary> /// Releases all resource used by the <see cref="CKAN.KSP"/> object. /// </summary> /// <remarks>Call <see cref="Dispose"/> when you are finished using the <see cref="CKAN.KSP"/>. The <see cref="Dispose"/> /// method leaves the <see cref="CKAN.KSP"/> in an unusable state. After calling <see cref="Dispose"/>, you must /// release all references to the <see cref="CKAN.KSP"/> so the garbage collector can reclaim the memory that /// the <see cref="CKAN.KSP"/> was occupying.</remarks> public void Dispose() { if (Cache != null) { Cache.Dispose(); Cache = null; } // Attempting to dispose of the related RegistryManager object here is a bad idea, it cause loads of failures } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Management.Automation; using System.Management.Automation.Internal; using Microsoft.PowerShell.Commands.Internal.Format; namespace Microsoft.PowerShell.Commands { /// <summary> /// Class output by Measure-Object. /// </summary> public abstract class MeasureInfo { /// <summary> /// /// Property name. /// /// </summary> public string Property { get; set; } = null; } /// <summary> /// Class output by Measure-Object. /// </summary> public sealed class GenericMeasureInfo : MeasureInfo { /// <summary> /// Default ctor. /// </summary> public GenericMeasureInfo() { Average = Sum = Maximum = Minimum = StandardDeviation = null; } /// <summary> /// Keeping track of number of objects with a certain property. /// </summary> public int Count { get; set; } /// <summary> /// The average of property values. /// </summary> public double? Average { get; set; } /// <summary> /// The sum of property values. /// </summary> public double? Sum { get; set; } /// <summary> /// The max of property values. /// </summary> public double? Maximum { get; set; } /// <summary> /// The min of property values. /// </summary> public double? Minimum { get; set; } /// <summary> /// The Standard Deviation of property values. /// </summary> public double? StandardDeviation { get; set; } } /// <summary> /// Class output by Measure-Object. /// </summary> /// <remarks> /// This class is created to make 'Measure-Object -MAX -MIN' work with ANYTHING that supports 'CompareTo'. /// GenericMeasureInfo class is shipped with PowerShell V2. Fixing this bug requires, changing the type of /// Maximum and Minimum properties which would be a breaking change. Hence created a new class to not /// have an appcompat issues with PS V2. /// </remarks> public sealed class GenericObjectMeasureInfo : MeasureInfo { /// <summary> /// Default ctor. /// </summary> public GenericObjectMeasureInfo() { Average = Sum = StandardDeviation = null; Maximum = Minimum = null; } /// <summary> /// /// Keeping track of number of objects with a certain property. /// /// </summary> public int Count { get; set; } /// <summary> /// /// The average of property values. /// /// </summary> public double? Average { get; set; } /// <summary> /// /// The sum of property values. /// /// </summary> public double? Sum { get; set; } /// <summary> /// /// The max of property values. /// /// </summary> public object Maximum { get; set; } /// <summary> /// /// The min of property values. /// /// </summary> public object Minimum { get; set; } /// <summary> /// The Standard Deviation of property values. /// </summary> public double? StandardDeviation { get; set; } } /// <summary> /// Class output by Measure-Object. /// </summary> public sealed class TextMeasureInfo : MeasureInfo { /// <summary> /// Default ctor. /// </summary> public TextMeasureInfo() { Lines = Words = Characters = null; } /// <summary> /// Keeping track of number of objects with a certain property. /// </summary> public int? Lines { get; set; } /// <summary> /// The average of property values. /// </summary> public int? Words { get; set; } /// <summary> /// The sum of property values. /// </summary> public int? Characters { get; set; } } /// <summary> /// Measure object cmdlet. /// </summary> [Cmdlet(VerbsDiagnostic.Measure, "Object", DefaultParameterSetName = GenericParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113349", RemotingCapability = RemotingCapability.None)] [OutputType(typeof(GenericMeasureInfo), typeof(TextMeasureInfo), typeof(GenericObjectMeasureInfo))] public sealed class MeasureObjectCommand : PSCmdlet { /// <summary> /// Dictionary to be used by Measure-Object implementation. /// Keys are strings. Keys are compared with OrdinalIgnoreCase. /// </summary> /// <typeparam name="V">Value type.</typeparam> private class MeasureObjectDictionary<V> : Dictionary<string, V> where V : new() { /// <summary> /// Default ctor. /// </summary> internal MeasureObjectDictionary() : base(StringComparer.OrdinalIgnoreCase) { } /// <summary> /// Attempt to look up the value associated with the /// the specified key. If a value is not found, associate /// the key with a new value created via the value type's /// default constructor. /// </summary> /// <param name="key">The key to look up</param> /// <returns> /// The existing value, or a newly-created value. /// </returns> public V EnsureEntry(string key) { V val; if (!TryGetValue(key, out val)) { val = new V(); this[key] = val; } return val; } } /// <summary> /// Convenience class to track statistics without having /// to maintain two sets of MeasureInfo and constantly checking /// what mode we're in. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")] private class Statistics { // Common properties internal int count = 0; // Generic/Numeric statistics internal double sum = 0.0; internal double sumPrevious = 0.0; internal double variance = 0.0; internal object max = null; internal object min = null; // Text statistics internal int characters = 0; internal int words = 0; internal int lines = 0; } /// <summary> /// Default constructor. /// </summary> public MeasureObjectCommand() : base() { } #region Command Line Switches #region Common parameters in both sets /// <summary> /// Incoming object. /// </summary> /// <value></value> [Parameter(ValueFromPipeline = true)] public PSObject InputObject { set; get; } = AutomationNull.Value; /// <summary> /// Properties to be examined. /// </summary> /// <value></value> [ValidateNotNullOrEmpty] [Parameter(Position = 0)] public PSPropertyExpression[] Property { get; set; } = null; #endregion Common parameters in both sets /// <summary> /// Set to true if Standard Deviation is to be returned. /// </summary> [Parameter(ParameterSetName = GenericParameterSet)] public SwitchParameter StandardDeviation { get { return _measureStandardDeviation; } set { _measureStandardDeviation = value; } } private bool _measureStandardDeviation; /// <summary> /// Set to true is Sum is to be returned. /// </summary> /// <value></value> [Parameter(ParameterSetName = GenericParameterSet)] public SwitchParameter Sum { get { return _measureSum; } set { _measureSum = value; } } private bool _measureSum; /// <summary> /// Gets or sets the value indicating if all statistics should be returned. /// </summary> /// <value></value> [Parameter(ParameterSetName = GenericParameterSet)] public SwitchParameter AllStats { get { return _allStats; } set { _allStats = value; } } private bool _allStats; /// <summary> /// Set to true is Average is to be returned. /// </summary> /// <value></value> [Parameter(ParameterSetName = GenericParameterSet)] public SwitchParameter Average { get { return _measureAverage; } set { _measureAverage = value; } } private bool _measureAverage; /// <summary> /// Set to true is Max is to be returned. /// </summary> /// <value></value> [Parameter(ParameterSetName = GenericParameterSet)] public SwitchParameter Maximum { get { return _measureMax; } set { _measureMax = value; } } private bool _measureMax; /// <summary> /// Set to true is Min is to be returned. /// </summary> /// <value></value> [Parameter(ParameterSetName = GenericParameterSet)] public SwitchParameter Minimum { get { return _measureMin; } set { _measureMin = value; } } private bool _measureMin; #region TextMeasure ParameterSet /// <summary> /// /// </summary> /// <value></value> [Parameter(ParameterSetName = TextParameterSet)] public SwitchParameter Line { get { return _measureLines; } set { _measureLines = value; } } private bool _measureLines = false; /// <summary> /// /// </summary> /// <value></value> [Parameter(ParameterSetName = TextParameterSet)] public SwitchParameter Word { get { return _measureWords; } set { _measureWords = value; } } private bool _measureWords = false; /// <summary> /// /// </summary> /// <value></value> [Parameter(ParameterSetName = TextParameterSet)] public SwitchParameter Character { get { return _measureCharacters; } set { _measureCharacters = value; } } private bool _measureCharacters = false; /// <summary> /// /// </summary> /// <value></value> [Parameter(ParameterSetName = TextParameterSet)] public SwitchParameter IgnoreWhiteSpace { get { return _ignoreWhiteSpace; } set { _ignoreWhiteSpace = value; } } private bool _ignoreWhiteSpace; #endregion TextMeasure ParameterSet #endregion Command Line Switches /// <summary> /// Which parameter set the Cmdlet is in. /// </summary> private bool IsMeasuringGeneric { get { return String.Compare(ParameterSetName, GenericParameterSet, StringComparison.Ordinal) == 0; } } /// <summary> /// Does the begin part of the cmdlet. /// </summary> protected override void BeginProcessing() { // Sets all other generic parameters to true to get all statistics. if (_allStats) { _measureSum = _measureStandardDeviation = _measureAverage = _measureMax = _measureMin = true; } // finally call the base class. base.BeginProcessing(); } /// <summary> /// Collect data about each record that comes in. /// Side effects: Updates totalRecordCount. /// </summary> protected override void ProcessRecord() { if (InputObject == null || InputObject == AutomationNull.Value) { return; } _totalRecordCount++; if (Property == null) AnalyzeValue(null, InputObject.BaseObject); else AnalyzeObjectProperties(InputObject); } /// <summary> /// Analyze an object on a property-by-property basis instead /// of as a simple value. /// Side effects: Updates statistics. /// <param name="inObj">The object to analyze.</param> /// </summary> private void AnalyzeObjectProperties(PSObject inObj) { // Keep track of which properties are counted for an // input object so that repeated properties won't be // counted twice. MeasureObjectDictionary<object> countedProperties = new MeasureObjectDictionary<object>(); // First iterate over the user-specified list of // properties... foreach (var expression in Property) { List<PSPropertyExpression> resolvedNames = expression.ResolveNames(inObj); if (resolvedNames == null || resolvedNames.Count == 0) { // Insert a blank entry so we can track // property misses in EndProcessing. if (!expression.HasWildCardCharacters) { string propertyName = expression.ToString(); _statistics.EnsureEntry(propertyName); } continue; } // Each property value can potentially refer // to multiple properties via globbing. Iterate over // the actual property names. foreach (PSPropertyExpression resolvedName in resolvedNames) { string propertyName = resolvedName.ToString(); // skip duplicated properties if (countedProperties.ContainsKey(propertyName)) { continue; } List<PSPropertyExpressionResult> tempExprRes = resolvedName.GetValues(inObj); if (tempExprRes == null || tempExprRes.Count == 0) { // Shouldn't happen - would somehow mean // that the property went away between when // we resolved it and when we tried to get its // value. continue; } AnalyzeValue(propertyName, tempExprRes[0].Result); // Remember resolved propertyNames that have been counted countedProperties[propertyName] = null; } } } /// <summary> /// Analyze a value for generic/text statistics. /// Side effects: Updates statistics. May set nonNumericError. /// <param name="propertyName">The property this value corresponds to.</param> /// <param name="objValue">The value to analyze.</param> /// </summary> private void AnalyzeValue(string propertyName, object objValue) { if (propertyName == null) propertyName = thisObject; Statistics stat = _statistics.EnsureEntry(propertyName); // Update common properties. stat.count++; if (_measureCharacters || _measureWords || _measureLines) { string strValue = (objValue == null) ? string.Empty : objValue.ToString(); AnalyzeString(strValue, stat); } if (_measureAverage || _measureSum || _measureStandardDeviation) { double numValue = 0.0; if (!LanguagePrimitives.TryConvertTo(objValue, out numValue)) { _nonNumericError = true; ErrorRecord errorRecord = new ErrorRecord( PSTraceSource.NewInvalidOperationException(MeasureObjectStrings.NonNumericInputObject, objValue), "NonNumericInputObject", ErrorCategory.InvalidType, objValue); WriteError(errorRecord); return; } AnalyzeNumber(numValue, stat); } // Measure-Object -MAX -MIN should work with ANYTHING that supports CompareTo if (_measureMin) { stat.min = Compare(objValue, stat.min, true); } if (_measureMax) { stat.max = Compare(objValue, stat.max, false); } } /// <summary> /// Compare is a helper function used to find the min/max between the supplied input values. /// </summary> /// <param name="objValue"> /// Current input value. /// </param> /// <param name="statMinOrMaxValue"> /// Current minimum or maximum value in the statistics. /// </param> /// <param name="isMin"> /// Indicates if minimum or maximum value has to be found. /// If true is passed in then the minimum of the two values would be returned. /// If false is passed in then maximum of the two values will be returned.</param> /// <returns></returns> private object Compare(object objValue, object statMinOrMaxValue, bool isMin) { object currentValue = objValue; object statValue = statMinOrMaxValue; int factor = isMin ? 1 : -1; double temp; currentValue = ((objValue != null) && LanguagePrimitives.TryConvertTo<double>(objValue, out temp)) ? temp : currentValue; statValue = ((statValue != null) && LanguagePrimitives.TryConvertTo<double>(statValue, out temp)) ? temp : statValue; if (currentValue != null && statValue != null && !currentValue.GetType().Equals(statValue.GetType())) { currentValue = PSObject.AsPSObject(currentValue).ToString(); statValue = PSObject.AsPSObject(statValue).ToString(); } if ((statValue == null) || ((LanguagePrimitives.Compare(statValue, currentValue, false, CultureInfo.CurrentCulture) * factor) > 0)) { return objValue; } return statMinOrMaxValue; } /// <summary> /// Class contains util static functions. /// </summary> private static class TextCountUtilities { /// <summary> /// Count chars in inStr. /// </summary> /// <param name="inStr">string whose chars are counted</param> /// <param name="ignoreWhiteSpace">true to discount white space</param> /// <returns>number of chars in inStr</returns> internal static int CountChar(string inStr, bool ignoreWhiteSpace) { if (String.IsNullOrEmpty(inStr)) { return 0; } if (!ignoreWhiteSpace) { return inStr.Length; } int len = 0; foreach (char c in inStr) { if (!char.IsWhiteSpace(c)) { len++; } } return len; } /// <summary> /// Count words in inStr. /// </summary> /// <param name="inStr">string whose words are counted</param> /// <returns>number of words in inStr</returns> internal static int CountWord(string inStr) { if (String.IsNullOrEmpty(inStr)) { return 0; } int wordCount = 0; bool wasAWhiteSpace = true; foreach (char c in inStr) { if (char.IsWhiteSpace(c)) { wasAWhiteSpace = true; } else { if (wasAWhiteSpace) { wordCount++; } wasAWhiteSpace = false; } } return wordCount; } /// <summary> /// Count lines in inStr. /// </summary> /// <param name="inStr">string whose lines are counted</param> /// <returns>number of lines in inStr</returns> internal static int CountLine(string inStr) { if (String.IsNullOrEmpty(inStr)) { return 0; } int numberOfLines = 0; foreach (char c in inStr) { if (c == '\n') { numberOfLines++; } } // 'abc\nd' has two lines // but 'abc\n' has one line if (inStr[inStr.Length - 1] != '\n') { numberOfLines++; } return numberOfLines; } } /// <summary> /// Update text statistics. /// <param name="strValue">The text to analyze.</param> /// <param name="stat">The Statistics object to update.</param> /// </summary> private void AnalyzeString(string strValue, Statistics stat) { if (_measureCharacters) stat.characters += TextCountUtilities.CountChar(strValue, _ignoreWhiteSpace); if (_measureWords) stat.words += TextCountUtilities.CountWord(strValue); if (_measureLines) stat.lines += TextCountUtilities.CountLine(strValue); } /// <summary> /// Update number statistics. /// <param name="numValue">The number to analyze.</param> /// <param name="stat">The Statistics object to update.</param> /// </summary> private void AnalyzeNumber(double numValue, Statistics stat) { if (_measureSum || _measureAverage || _measureStandardDeviation) { stat.sumPrevious = stat.sum; stat.sum += numValue; } if (_measureStandardDeviation && stat.count > 1) { // Based off of iterative method of calculating variance on // https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm double avgPrevious = stat.sumPrevious / (stat.count - 1); stat.variance *= (stat.count - 2.0) / (stat.count - 1); stat.variance += (numValue - avgPrevious) * (numValue - avgPrevious) / stat.count; } } /// <summary> /// WriteError when a property is not found. /// </summary> /// <param name="propertyName">The missing property.</param> /// <param name="errorId">The error ID to write.</param> private void WritePropertyNotFoundError(string propertyName, string errorId) { Diagnostics.Assert(Property != null, "no property and no InputObject should have been addressed"); ErrorRecord errorRecord = new ErrorRecord( PSTraceSource.NewArgumentException("Property"), errorId, ErrorCategory.InvalidArgument, null); errorRecord.ErrorDetails = new ErrorDetails( this, "MeasureObjectStrings", "PropertyNotFound", propertyName); WriteError(errorRecord); } /// <summary> /// Output collected statistics. /// Side effects: Updates statistics. Writes objects to stream. /// </summary> protected override void EndProcessing() { // Fix for 917114: If Property is not set, // and we aren't passed any records at all, // output 0s to emulate wc behavior. if (_totalRecordCount == 0 && Property == null) { _statistics.EnsureEntry(thisObject); } foreach (string propertyName in _statistics.Keys) { Statistics stat = _statistics[propertyName]; if (stat.count == 0 && Property != null) { // Why are there two different ids for this error? string errorId = (IsMeasuringGeneric) ? "GenericMeasurePropertyNotFound" : "TextMeasurePropertyNotFound"; WritePropertyNotFoundError(propertyName, errorId); continue; } MeasureInfo mi = null; if (IsMeasuringGeneric) { double temp; if ((stat.min == null || LanguagePrimitives.TryConvertTo<double>(stat.min, out temp)) && (stat.max == null || LanguagePrimitives.TryConvertTo<double>(stat.max, out temp))) { mi = CreateGenericMeasureInfo(stat, true); } else { mi = CreateGenericMeasureInfo(stat, false); } } else mi = CreateTextMeasureInfo(stat); // Set common properties. if (Property != null) mi.Property = propertyName; WriteObject(mi); } } /// <summary> /// Create a MeasureInfo object for generic stats. /// <param name="stat">The statistics to use.</param> /// <returns>A new GenericMeasureInfo object.</returns> /// </summary> /// <param name="shouldUseGenericMeasureInfo"></param> private MeasureInfo CreateGenericMeasureInfo(Statistics stat, bool shouldUseGenericMeasureInfo) { double? sum = null; double? average = null; double? StandardDeviation = null; object max = null; object min = null; if (!_nonNumericError) { if (_measureSum) sum = stat.sum; if (_measureAverage && stat.count > 0) average = stat.sum / stat.count; if (_measureStandardDeviation) { StandardDeviation = Math.Sqrt(stat.variance); } } if (_measureMax) { if (shouldUseGenericMeasureInfo && (stat.max != null)) { double temp; LanguagePrimitives.TryConvertTo<double>(stat.max, out temp); max = temp; } else { max = stat.max; } } if (_measureMin) { if (shouldUseGenericMeasureInfo && (stat.min != null)) { double temp; LanguagePrimitives.TryConvertTo<double>(stat.min, out temp); min = temp; } else { min = stat.min; } } if (shouldUseGenericMeasureInfo) { GenericMeasureInfo gmi = new GenericMeasureInfo(); gmi.Count = stat.count; gmi.Sum = sum; gmi.Average = average; gmi.StandardDeviation = StandardDeviation; if (max != null) { gmi.Maximum = (double)max; } if (min != null) { gmi.Minimum = (double)min; } return gmi; } else { GenericObjectMeasureInfo gomi = new GenericObjectMeasureInfo(); gomi.Count = stat.count; gomi.Sum = sum; gomi.Average = average; gomi.Maximum = max; gomi.Minimum = min; return gomi; } } /// <summary> /// Create a MeasureInfo object for text stats. /// <param name="stat">The statistics to use.</param> /// <returns>A new TextMeasureInfo object.</returns> /// </summary> private TextMeasureInfo CreateTextMeasureInfo(Statistics stat) { TextMeasureInfo tmi = new TextMeasureInfo(); if (_measureCharacters) tmi.Characters = stat.characters; if (_measureWords) tmi.Words = stat.words; if (_measureLines) tmi.Lines = stat.lines; return tmi; } /// <summary> /// The observed statistics keyed by property name. /// If Property is not set, then the key used will be the value of thisObject. /// </summary> private MeasureObjectDictionary<Statistics> _statistics = new MeasureObjectDictionary<Statistics>(); /// <summary> /// Whether or not a numeric conversion error occurred. /// If true, then average/sum/standard deviation will not be output. /// </summary> private bool _nonNumericError = false; /// <summary> /// The total number of records encountered. /// </summary> private int _totalRecordCount = 0; /// <summary> /// Parameter set name for measuring objects. /// </summary> private const string GenericParameterSet = "GenericMeasure"; /// <summary> /// Parameter set name for measuring text. /// </summary> private const string TextParameterSet = "TextMeasure"; /// <summary> /// Key that statistics are stored under when Property is not set. /// </summary> private const string thisObject = "$_"; } }
using AutoMapper; using FluentValidation; using MediatR; using Microsoft.EntityFrameworkCore; using Stickerzzz.Core.Users; using Stickerzzz.Infrastructure.Data; using Stickerzzz.Infrastructure.Errors; using Stickerzzz.Infrastructure.Security; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; namespace Stickerzzz.Web.Users { public class Login { public class UserData { public string Email { get; set; } public string Password { get; set; } } public class UserDataValidator : AbstractValidator<UserData> { public UserDataValidator() { RuleFor(x => x.Email).NotNull().NotEmpty(); RuleFor(x => x.Password).NotNull().NotEmpty(); } } public class Command : IRequest<UserEnvelope> { public UserData User { get; set; } } public class CommandValidator : AbstractValidator<Command> { public CommandValidator() { RuleFor(x => x.User).NotNull().SetValidator(new UserDataValidator()); } } public class Handler : IRequestHandler<Command, UserEnvelope> { private readonly AppDbContext _context; private readonly IPasswordHasher _passwordHasher; private readonly IJwtTokenGenerator _jwtTokenGenerator; private readonly IMapper _mapper; public Handler( AppDbContext context, IPasswordHasher passwordHasher, IJwtTokenGenerator jwtTokenGenerator, IMapper mapper) { _context = context; _passwordHasher = passwordHasher; _jwtTokenGenerator = jwtTokenGenerator; _mapper = mapper; } public async Task<UserEnvelope> Handle(Command message, CancellationToken cancellationToken) { var appUser = await _context.Users.Where(i => i.Email == message.User.Email).SingleOrDefaultAsync(cancellationToken); if (appUser == null) { throw new RestException(HttpStatusCode.Unauthorized, new { Error = "Invalid email / password." }); } if (!appUser.Hash.SequenceEqual(_passwordHasher.Hash(message.User.Password, appUser.Salt))) { throw new RestException(HttpStatusCode.Unauthorized, new { Error = "Invalid email / password." }); } var user = _mapper.Map<AppUser, User>(appUser); user.Token = await _jwtTokenGenerator.CreateToken(appUser.UserName); return new UserEnvelope(user); } } } }
using System; using System.Collections.Generic; using System.Security.Cryptography; using System.Text; namespace Blockchain { public class StringUtil { public static string ApplySha256(string input) { var crypt = new System.Security.Cryptography.SHA256Managed(); var hash = new System.Text.StringBuilder(); byte[] crypto = crypt.ComputeHash(Encoding.UTF8.GetBytes(input)); foreach (byte theByte in crypto) { var hex = String.Format("{0:X}", 0xff & theByte); if(hex.Length == 1) hash.Append('0'); hash.Append(hex); } return hash.ToString(); } public static String GetStringFromKey(string key) { var encodedBytes = Encoding.Unicode.GetBytes(key); return Convert.ToBase64String(encodedBytes); } public static byte[] SignData(string privateKey, string input) { // convert the string into byte array byte[] str = ASCIIEncoding.Unicode.GetBytes(input); var sha1hash = new SHA1Managed(); var hashdata = sha1hash.ComputeHash(str); // sign the hash data with private key RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.FromXmlStringInternal(privateKey); // signature hold the sign data of plaintext , signed by private key return rsa.SignData(str, "SHA1"); } public static bool VerifyData(string publicKey, string data, byte[] signature) { var str = ASCIIEncoding.Unicode.GetBytes(data); // compute the hash again, also we can pass it as a parameter var sha1hash = new SHA1Managed(); var hashdata = sha1hash.ComputeHash(str); RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.FromXmlStringInternal(publicKey); return rsa.VerifyHash(hashdata, "SHA1", signature); } // NOT AN ACTUAL MERKLE ROOT -- NEED TO REVIEW AND IMPLEMENT CORRECT ONE public static String GetMerkleRoot(List<Transaction> transactions) { int count = transactions.Count; var previousTreeLayer = new List<string>(); foreach (var transaction in transactions) { previousTreeLayer.Add(transaction.TransactionId); } var treeLayer = previousTreeLayer; while (count > 1) { treeLayer = new List<string>(); for (int i = 1; i < previousTreeLayer.Count; i++) { treeLayer.Add(ApplySha256(previousTreeLayer[i - 1] + previousTreeLayer[i])); } count = treeLayer.Count; previousTreeLayer = treeLayer; } return treeLayer.Count == 1 ? treeLayer[0] : ""; } } }
using System; using System.Collections.Generic; using System.Linq; public class Pizza { private string name; private List<Topping> toppings; private Dough dough; public Pizza(string name) { this.Name = name; this.Toppings = new List<Topping>(); } public string Name { get { return name; } set { if (value.Length < 1 || value.Length > 15 || String.IsNullOrWhiteSpace(value)) { throw new ArgumentException("Pizza name should be between 1 and 15 symbols."); } name = value; } } public List<Topping> Toppings { get { return toppings; } set { toppings = value; } } public Dough Dough { get { return dough; } set { dough = value; } } public void AddToppings(Topping topping) { if (Toppings.Count > 10) { throw new ArgumentException("Number of toppings should be in range [0..10]."); } Toppings.Add(topping); } private double GetTotalCalories { get { return toppings.Sum(x => x.TotalCalories) + dough.TotalCalories; } } public override string ToString() { return $"{this.Name} - {GetTotalCalories:F2} Calories."; } }
///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Tencent is pleased to support the open source community by making behaviac available. // // Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause // // 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; namespace behaviac { public class DecoratorTime : DecoratorNode { protected IInstanceMember m_time; protected override void load(int version, string agentType, List<property_t> properties) { base.load(version, agentType, properties); for (int i = 0; i < properties.Count; ++i) { property_t p = properties[i]; if (p.name == "Time") { int pParenthesis = p.value.IndexOf('('); if (pParenthesis == -1) { this.m_time = AgentMeta.ParseProperty(p.value); } else { this.m_time = AgentMeta.ParseMethod(p.value); } } } } protected virtual double GetTime(Agent pAgent) { double time = 0; if (this.m_time != null) { if (this.m_time is CInstanceMember<double>) { time = ((CInstanceMember<double>)this.m_time).GetValue(pAgent); } else if (this.m_time is CInstanceMember<float>) { time = ((CInstanceMember<float>)this.m_time).GetValue(pAgent); } else if (this.m_time is CInstanceMember<int>) { time = ((CInstanceMember<int>)this.m_time).GetValue(pAgent); } } return time; } protected override BehaviorTask createTask() { DecoratorTimeTask pTask = new DecoratorTimeTask(); return pTask; } private class DecoratorTimeTask : DecoratorTask { public override void copyto(BehaviorTask target) { base.copyto(target); Debug.Check(target is DecoratorTimeTask); DecoratorTimeTask ttask = (DecoratorTimeTask)target; ttask.m_start = this.m_start; ttask.m_time = this.m_time; } public override void save(ISerializableNode node) { base.save(node); CSerializationID startId = new CSerializationID("start"); node.setAttr(startId, this.m_start); CSerializationID timeId = new CSerializationID("time"); node.setAttr(timeId, this.m_time); } public override void load(ISerializableNode node) { base.load(node); } protected override bool onenter(Agent pAgent) { base.onenter(pAgent); this.m_start = Workspace.Instance.TimeSinceStartup * 1000.0; this.m_time = this.GetTime(pAgent); return (this.m_time >= 0); } protected override EBTStatus decorate(EBTStatus status) { if (Workspace.Instance.TimeSinceStartup * 1000.0 - this.m_start >= this.m_time) { return EBTStatus.BT_SUCCESS; } return EBTStatus.BT_RUNNING; } private double GetTime(Agent pAgent) { Debug.Check(this.GetNode() is DecoratorTime); DecoratorTime pNode = (DecoratorTime)(this.GetNode()); return pNode != null ? pNode.GetTime(pAgent) : 0; } private double m_start = 0; private double m_time = 0; } } }