Пример #1
0
    public float GetRatio(Enum statusKey)
    {
        Assert.IsTrue(ContainsKey(statusKey));

        var targetStatus = Find(statusKey);
        return targetStatus.Get(statusKey) / targetStatus.GetMax(statusKey);
    }
Пример #2
0
 /// <summary>
 /// 添加事件及回调
 /// </summary>
 /// <param name="type">事件枚举</param>
 /// <param name="handle">回调</param>
 /// <param name="isUseOnce"></param>
 public static void AddEvent(Enum type, EventHandle handle, bool isUseOnce = false)
 {
     if (isUseOnce)
     {
         if (mUseOnceEventDic.ContainsKey(type))
         {
             if (!mUseOnceEventDic[type].Contains(handle))
                 mUseOnceEventDic[type].Add(handle);
             else
                 Debug.LogWarning("already existing EventType: " + type + " handle: " + handle);
         }
         else
         {
             List<EventHandle> temp = new List<EventHandle>();
             temp.Add(handle);
             mUseOnceEventDic.Add(type, temp);
         }
     }
     else
     {
         if (mEventDic.ContainsKey(type))
         {
             if (!mEventDic[type].Contains(handle))
                 mEventDic[type].Add(handle);
             else
                 Debug.LogWarning("already existing EventType: "+ type+" handle: "+ handle );
         }
         else
         {
             List<EventHandle> temp = new List<EventHandle>();
             temp.Add(handle);
             mEventDic.Add(type, temp);
         }
     }
 }
Пример #3
0
 /// <summary>
 ///     Limit the display of the field based on the enum value of another field
 /// </summary>
 /// <param name="field">Field to check for enum value</param>
 /// <param name="value">Enum value other field must have</param>
 /// <param name="contains">If not contains, enums have to match exactly</param>
 /// <param name="reverse">If reversed, will only display if the other field's value does not match</param>
 public DatablockEnumAttribute(string field, object value, bool reverse = false, bool contains = false)
 {
     fieldName = field;
     enumValue = (Enum)value;
     this.reverse = reverse;
     this.contains = contains;
 }
    public void ChangeState(Enum newState)
    {
        if(mCurrentWorkDelegate != null){
            StopCoroutine(mCurrentWorkDelegate);
        }

        if(mCurrentState != null){
            StateTransitionDelegate exitDelegate = mEndStateDelegate[mCurrentState];
            if(exitDelegate != null){
                exitDelegate();
            }
        }

        StateTransitionDelegate enterDelegate = mStartStateDelegate[newState];
        if(enterDelegate != null){
            enterDelegate();
        }

        mCurrentState = newState;

        StateWorkDelegate workDelegate = mStateWorkDelegate[mCurrentState];
        if(workDelegate != null){
            mCurrentWorkDelegate = workDelegate();
            StartCoroutine(mCurrentWorkDelegate);
        }
    }
    /// <summary>
    /// Gets a string value for a particular enum value.
    /// </summary>
    /// <param name="value">Value.</param>
    /// <returns>String Value associated via a <see cref="StringValueAttribute"/> attribute, or null if not found.</returns>
    public static string GetStringValue(Enum value)
    {
        string output = null;
            Type type = value.GetType();

            if (_stringValues.ContainsKey(value))
                output = (_stringValues[value] as StringValueAttribute).Value;
            else
            {
                //Look for our 'StringValueAttribute' in the field's custom attributes
                FieldInfo fi = type.GetField(value.ToString());
                StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[];
                if (attrs.Length > 0)
                {
                    try
                    {
                        _stringValues.Add(value, attrs[0]);
                    }
                    catch { }
                    output = attrs[0].Value;
                }

            }
            return output;
    }
Пример #6
0
    public static bool HasDone(Enum check)
    {
        if (HarmonicSerialization.Instance.CurrentSave != null)
        {
            if (HarmonicSerialization.Instance.CurrentSave.HideTutorial)
                return true;
            else
            {
                if (check is MeatspaceProgress)
                    return (HarmonicSerialization.Instance.CurrentSave.MeatspaceProgression & ((MeatspaceProgress)check)) != 0;
                else if (check is CyberspaceProgress)
                    return (HarmonicSerialization.Instance.CurrentSave.CyberspaceProgression & ((CyberspaceProgress)check)) != 0;
                else if (check is WorkstationProgress)
                    return (HarmonicSerialization.Instance.CurrentSave.WorkstationProgression & ((WorkstationProgress)check)) != 0;
                else if (check is HackingProgress)
                    return (HarmonicSerialization.Instance.CurrentSave.HackingProgression & ((HackingProgress)check)) != 0;

                UnityEngine.Debug.LogWarning("flag enum is none of any progression enums!");
                return false;
            }
        }
        else
        {
            UnityEngine.Debug.LogWarning("no current save to check enums against!");
            return false;
        }
    }
Пример #7
0
 void Exit_EnterState()
 {
     exitSaveColor = exitStyle.normal.textColor;
     exitStyle.normal.textColor = Color.red;
     this.lastState = (Enum)stateMachine.lastState;
     this.lastMachine = stateMachine.lastStateMachineBehaviour;
 }
Пример #8
0
        /// <summary>
        /// Initializes a new instance of the EnumItem class.
        /// </summary>
        /// <param name="document">The document that contains the element.</param>
        /// <param name="parent">The parent of the element.</param>
        /// <param name="header">The Xml header for this element.</param>
        /// <param name="attributes">The list of attributes attached to this element.</param>
        /// <param name="declaration">The declaration code for this element.</param>
        /// <param name="initialization">The initialization expression, if there is one.</param>
        /// <param name="unsafeCode">Indicates whether the element resides within a block of unsafe code.</param>
        /// <param name="generated">Indicates whether the code element was generated or written by hand.</param>
        internal EnumItem(
            CsDocument document,
            Enum parent,
            XmlHeader header,
            ICollection<Attribute> attributes,
            Declaration declaration,
            Expression initialization,
            bool unsafeCode,
            bool generated)
            : base(document,
            parent,
            ElementType.EnumItem, 
            "enum item " + declaration.Name, 
            header, 
            attributes,
            declaration,
            unsafeCode,
            generated)
        {
            Param.Ignore(document, parent, header, attributes, declaration, initialization, unsafeCode, generated);

            this.initialization = initialization;
            if (this.initialization != null)
            {
                this.AddExpression(this.initialization);
            }
        }
Пример #9
0
 float ApplyBuff(Enum statType, float value)
 {
     string strStatType = statType.ToString();
     float addSum = 0;
     float multiSum = 0;
     foreach (var buff in buffs)
     {
         if (buff.Value.statMod != null)
         {
             foreach (var buffStat in buff.Value.statMod)
             {
                 string strBuffStatType = buffStat.Key.ToString();
                 if (strBuffStatType == strStatType)
                 {
                     addSum += buffStat.Value;
                 }
                 else if (strBuffStatType != "GoldGetAmplifier" && strBuffStatType == strStatType + "Amplifier")
                 {
                     multiSum += buffStat.Value;
                 }
             }
         }
     }
     return (value + addSum) * (1 + multiSum);
 }
Пример #10
0
    protected void Init(Enum statType, object val)
    {
        CheckKeyType(statType);
        ClearCache();

        initValue.Add(statType, val);
    }
Пример #11
0
    IEnumerator Limp_Enter(Enum prevState)
    {
        Debug.Log("Enter Limp " + prevState.ToString());
        yield return new WaitForSeconds(5);

        Debug.Log("Limp Entered");
    }
Пример #12
0
    public float Get(Enum statKey)
    {
        Type keyType = statKey.GetType();
        Assert.IsTrue(stats.ContainsKey(keyType));

        return stats[keyType].Get(statKey);
    }
Пример #13
0
    public void RemoveState(Enum stateId) {
        FSMState state = GetState(stateId);

        if(state == null)
            throw new Exception("Could not find state " + stateId.ToString() + " for removal.");

        _states.Remove(state);
    }
Пример #14
0
 public static Enum EnumComboBox(string label, Enum selected)
 {
     EditorGUILayout.BeginHorizontal();
     GUILayout.Label(label);
     var result = EnumComboBox(selected);
     EditorGUILayout.EndHorizontal();
     return result;
 }
Пример #15
0
			internal Visitor(Enum providerMode)
			{
				if(providerMode == null)
				{
					throw Error.ArgumentNull("providerMode");
				}
				this._providerMode = providerMode;
			}
Пример #16
0
		public EnumMember (Enum parent, EnumMember prev_member, string name, Expression expr,
				   Attributes attrs, Location loc)
			: base (parent, new EnumTypeExpr (parent), name, expr, Modifiers.PUBLIC,
				attrs, loc)
		{
			this.ParentEnum = parent;
			this.ValueExpr = expr;
			this.prev_member = prev_member;
		}
Пример #17
0
 Status2 Find(Enum statusKey)
 {
     Type keyType = statusKey.GetType();
     if (statuses.ContainsKey(keyType))
     {
         return statuses[keyType];
     }
     return null;
 }
Пример #18
0
 public bool Change(Enum statusKey, float value)
 {
     if (ContainsKey(statusKey))
     {
         Find(statusKey).Change(statusKey, value);
         return true;
     }
     return false;
 }
Пример #19
0
    public void AddEventListener(Enum EventEnum, EventHandle handle)
    {
        EventHandRegisterInfo info = new EventHandRegisterInfo();
        info.m_EventKey = EventEnum;
        info.m_hande = handle;

        GlobalEvent.AddEvent(EventEnum, handle);

        m_EventListeners.Add(info);
    }
Пример #20
0
 public Schedule(Queue<Task> tasksToDo, NPC toManage, Enum priority)
     : base()
 {
     _tasksToDo = tasksToDo;
     _toManage = toManage;
     schedulePriority = Convert.ToInt32(priority);
     flagList = new List<List<string>>();
     scheduleName = this.GetType().ToString();
     Init ();
 }
Пример #21
0
 public Schedule(NPC toManage, Enum priority, bool _canPassiveChat)
     : base()
 {
     _tasksToDo = new Queue<Task>();
     _toManage = toManage;
     canPassiveChat = _canPassiveChat;
     schedulePriority = Convert.ToInt32(priority);
     flagList = new List<List<string>>();
     scheduleName = this.GetType().ToString();
     Init ();
 }
Пример #22
0
	public static string GetEnumDescription (Enum value)
	{
		FieldInfo fi = value.GetType ().GetField (value.ToString ());
		DescriptionAttribute [] attributes =
			(DescriptionAttribute []) fi.GetCustomAttributes (typeof (DescriptionAttribute), false);
		if (attributes.Length > 0) {
			return attributes [0].Description;
		} else {
			return value.ToString ();
		}
	}
Пример #23
0
 private static bool BoxUnboxToNQ(Enum o)
 {
     try
     {
         return Helper.Compare((ByteE)(ValueType)(object)o, Helper.Create(default(ByteE)));
     }
     catch (NullReferenceException)
     {
         return o == null;
     }
 }
Пример #24
0
 private static bool BoxUnboxToNQ(Enum o)
 {
     try
     {
         return Helper.Compare((IntE)o, Helper.Create(default(IntE)));
     }
     catch (NullReferenceException)
     {
         return o == null;
     }
 }
Пример #25
0
    /// <summary>
    /// 
    /// </summary>
    /// <param name="next_state"></param>
    public void ChangeState( Enum next_state )
    {
        InTransition = true;

        if ( CurrentState != null ) {
            CurrentState.OnStateExit( States[ next_state ] );
        }

        States[ next_state ].OnStateEnter( CurrentState );
        CurrentState = States[ next_state ];

        InTransition = false;
    }
Пример #26
0
        public static string GetDescription(Enum key)
        {
            FieldInfo fi = key.GetType().GetField(key.ToString());

            if (null != fi)
            {
                object[] attrs = fi.GetCustomAttributes(typeof(EnumDescriptionAttribute), true);
                if (attrs != null && attrs.Length > 0)
                    return ((EnumDescriptionAttribute)attrs[0]).Description;
            }

            return string.Empty;
        }
Пример #27
0
 private static IEnumerator CoWaitCallback(Enum type, string subType, int count, WaitCallbackDelegate func)
 {
     bool wait = true;
     func(type, subType, count, () =>
     {
         wait = false;
     });
     // ReSharper disable once LoopVariableIsNeverChangedInsideLoop
     while (wait)
     {
         yield return null;
     }
 }
Пример #28
0
        public EnumProvider(Dictionary<string, object> node)
        {
            Enums = new Dictionary<string, Enum>();

            var groups = node["Enums"] as System.Xml.XmlNodeList;
            foreach (System.Xml.XmlNode group in groups)
            {
                if (group.Name != "Enum") continue;

                Enum item = new Enum(group);
                Enums.Add(item.ID, item);
            }
        }
Пример #29
0
 public override void ExecuteEvent(Enum eventName)
 {
     if (eventName is ApartmentScriptEventNames) { // FIXME will this ever be true?
         switch ((ApartmentScriptEventNames)eventName) {
             case ApartmentScriptEventNames.WAKE_UP:
                 WakeUp();
                 //QuickStart();
                 break;
             case ApartmentScriptEventNames.POLICE_ARRIVE:
                 PoliceArrive();
                 break;
         }
     }
 }
Пример #30
0
    public static string GetDescription(Enum en)
    {
        Type type = en.GetType();
        MemberInfo[] memInfo = type.GetMember(en.ToString());
        if (memInfo != null && memInfo.Length > 0)
        {
            object[] attrs = memInfo[0].GetCustomAttributes(typeof(Description),
                                                            false);
            if (attrs != null && attrs.Length > 0)
                return ((Description)attrs[0]).Text;
        }

        return en.ToString();
    }
Пример #31
0
		public static object Convert(Type desiredType, String[] values, String paramName, IDictionary files, NameValueCollection paramList, out bool conversionSucceeded)
		{
			String value = null;

			if (values != null && values.Length > 0) 
			{
				value = values[0];
				conversionSucceeded = true;
			}
			else
			{
				conversionSucceeded = false;
			}

			if (desiredType == typeof(String))
			{
				return value;
			}
			else if (desiredType.IsArray)
			{
				return values != null ? ConvertToArray(desiredType, values, paramName, files, paramList) : null;
			}
			else if (desiredType.IsEnum)
			{
				if (value == String.Empty || value == null) return null;
				
				if (!Regex.IsMatch(value.ToString(), @"\D", RegexOptions.Compiled)) 
				{
					object enumValue = System.Convert.ChangeType(value, Enum.GetUnderlyingType(desiredType));
					// optional: test if the specified value is valid within the enum
					//if (Enum.IsDefined(desiredType, enumValue))
					//	throw or set enumValue = null
					return enumValue;
				}
				
				return Enum.Parse(desiredType, value, true);
			}
			else if (desiredType.IsPrimitive)
			{
				if (desiredType == typeof(Boolean))
					return (value != null && String.Compare("false", value, true) != 0);
				
				if (value == String.Empty || value == null) 
					return null;
				
				return System.Convert.ChangeType(value, desiredType);
			}
			else if (desiredType == typeof(Decimal))
			{
				if (value == null) return null;
				return System.Convert.ToDecimal(value.ToString());
			}			
			else if (desiredType == typeof(Guid))
			{
				if (value == null) return Guid.Empty;
				return new Guid(value.ToString());
			}
			else if (desiredType == typeof(DateTime))
			{
				if (value == null)
				{
					String day   = paramList[paramName + "day"];
					String month = paramList[paramName + "month"];
					String year  = paramList[paramName + "year"];

					if (day != null && month != null && year != null)
					{
						try
						{						
							int numYear = System.Convert.ToInt32(year);
							int numMonth = System.Convert.ToInt32(month);
							int numDay = System.Convert.ToInt32(day);
							
							int daysInMonth = DateTime.DaysInMonth( numYear, numMonth);
							
							if( numDay > 31 ) throw new ArgumentException( String.Format( "{0}day {1} is too big", paramName, numDay) );
							
							if( numDay > daysInMonth ) numDay = daysInMonth;

							DateTime dt = new DateTime( numYear, numMonth, numDay );

							conversionSucceeded = true; 

							return dt;
						}
						catch(Exception inner)
						{
							String message = String.Format("Invalid date (day {0} month {1} year {2}) for {3} ", 
								day, month, year, paramName);

							throw new ArgumentException(message, inner);
						}
					}
				}

				if (value == null || value == String.Empty)
				{
					return null;
				}
				else
				{
					return DateTime.Parse(value);
				}
			}
			else if (desiredType == typeof(HttpPostedFile))
			{
				conversionSucceeded = true; // if we get some files we don't care about the values being null
				return files[paramName];
			}
			else 
			{
				// support for types that specify a TypeConverter, i.e.: NullableTypes
				Type sourceType = (value != null ? value.GetType() : typeof(String));
				TypeConverter conv = TypeDescriptor.GetConverter(desiredType);
				if (conv != null && conv.CanConvertFrom(sourceType))
					return conv.ConvertFrom(value);
				
				String message = String.Format("Cannot convert argument '{0}', with value '{1}', "+
					"from {2} to {3}", paramName, value, sourceType, desiredType);
	
				throw new ArgumentException(message);
			}
		}
 /// <summary>
 /// The Get Operation Status operation returns the status of the
 /// specified operation. After calling an asynchronous operation, you
 /// can call Get Operation Status to determine whether the operation
 /// has succeeded, failed, or is still in progress.  (see
 /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx
 /// for more information)
 /// </summary>
 /// <param name='requestId'>
 /// Required. The request ID for the request you wish to track. The
 /// request ID is returned in the x-ms-request-id response header for
 /// every request.
 /// </param>
 /// <param name='cancellationToken'>
 /// Cancellation token.
 /// </param>
 /// <returns>
 /// The response body contains the status of the specified asynchronous
 /// operation, indicating whether it has succeeded, is inprogress, or
 /// has failed. Note that this status is distinct from the HTTP status
 /// code returned for the Get Operation Status operation itself. If
 /// the asynchronous operation succeeded, the response body includes
 /// the HTTP status code for the successful request. If the
 /// asynchronous operation failed, the response body includes the HTTP
 /// status code for the failed request, and also includes error
 /// information regarding the failure.
 /// </returns>
 public async System.Threading.Tasks.Task<OperationStatusResponse> GetOperationStatusAsync(string requestId, CancellationToken cancellationToken)
 {
     // Validate
     if (requestId == null)
     {
         throw new ArgumentNullException("requestId");
     }
     
     // Tracing
     bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
     string invocationId = null;
     if (shouldTrace)
     {
         invocationId = Tracing.NextInvocationId.ToString();
         Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
         tracingParameters.Add("requestId", requestId);
         Tracing.Enter(invocationId, this, "GetOperationStatusAsync", tracingParameters);
     }
     
     // Construct URL
     string url = "/" + (this.Credentials.SubscriptionId != null ? this.Credentials.SubscriptionId.Trim() : "") + "/operations/" + requestId.Trim();
     string baseUrl = this.BaseUri.AbsoluteUri;
     // Trim '/' character from the end of baseUrl and beginning of url.
     if (baseUrl[baseUrl.Length - 1] == '/')
     {
         baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
     }
     if (url[0] == '/')
     {
         url = url.Substring(1);
     }
     url = baseUrl + "/" + url;
     url = url.Replace(" ", "%20");
     
     // Create HTTP transport objects
     HttpRequestMessage httpRequest = null;
     try
     {
         httpRequest = new HttpRequestMessage();
         httpRequest.Method = HttpMethod.Get;
         httpRequest.RequestUri = new Uri(url);
         
         // Set Headers
         httpRequest.Headers.Add("x-ms-version", "2014-10-01");
         
         // Set Credentials
         cancellationToken.ThrowIfCancellationRequested();
         await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
         
         // Send Request
         HttpResponseMessage httpResponse = null;
         try
         {
             if (shouldTrace)
             {
                 Tracing.SendRequest(invocationId, httpRequest);
             }
             cancellationToken.ThrowIfCancellationRequested();
             httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
             if (shouldTrace)
             {
                 Tracing.ReceiveResponse(invocationId, httpResponse);
             }
             HttpStatusCode statusCode = httpResponse.StatusCode;
             if (statusCode != HttpStatusCode.OK)
             {
                 cancellationToken.ThrowIfCancellationRequested();
                 CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                 if (shouldTrace)
                 {
                     Tracing.Error(invocationId, ex);
                 }
                 throw ex;
             }
             
             // Create Result
             OperationStatusResponse result = null;
             // Deserialize Response
             cancellationToken.ThrowIfCancellationRequested();
             string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
             result = new OperationStatusResponse();
             XDocument responseDoc = XDocument.Parse(responseContent);
             
             XElement operationElement = responseDoc.Element(XName.Get("Operation", "http://schemas.microsoft.com/windowsazure"));
             if (operationElement != null)
             {
                 XElement idElement = operationElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
                 if (idElement != null)
                 {
                     string idInstance = idElement.Value;
                     result.Id = idInstance;
                 }
                 
                 XElement statusElement = operationElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure"));
                 if (statusElement != null)
                 {
                     OperationStatus statusInstance = ((OperationStatus)Enum.Parse(typeof(OperationStatus), statusElement.Value, true));
                     result.Status = statusInstance;
                 }
                 
                 XElement httpStatusCodeElement = operationElement.Element(XName.Get("HttpStatusCode", "http://schemas.microsoft.com/windowsazure"));
                 if (httpStatusCodeElement != null)
                 {
                     HttpStatusCode httpStatusCodeInstance = ((HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), httpStatusCodeElement.Value, true));
                     result.HttpStatusCode = httpStatusCodeInstance;
                 }
                 
                 XElement errorElement = operationElement.Element(XName.Get("Error", "http://schemas.microsoft.com/windowsazure"));
                 if (errorElement != null)
                 {
                     OperationStatusResponse.ErrorDetails errorInstance = new OperationStatusResponse.ErrorDetails();
                     result.Error = errorInstance;
                     
                     XElement codeElement = errorElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure"));
                     if (codeElement != null)
                     {
                         string codeInstance = codeElement.Value;
                         errorInstance.Code = codeInstance;
                     }
                     
                     XElement messageElement = errorElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure"));
                     if (messageElement != null)
                     {
                         string messageInstance = messageElement.Value;
                         errorInstance.Message = messageInstance;
                     }
                 }
             }
             
             result.StatusCode = statusCode;
             if (httpResponse.Headers.Contains("x-ms-request-id"))
             {
                 result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
             }
             
             if (shouldTrace)
             {
                 Tracing.Exit(invocationId, result);
             }
             return result;
         }
         finally
         {
             if (httpResponse != null)
             {
                 httpResponse.Dispose();
             }
         }
     }
     finally
     {
         if (httpRequest != null)
         {
             httpRequest.Dispose();
         }
     }
 }
Пример #33
0
        public NotifierData GetNotifierData <TActivity>(CommentModel comment, TActivity activity, Enum notificationType)
            where TActivity : IIntranetActivity, IHaveOwner
        {
            var currentMember = _intranetMemberService.GetCurrentMember();
            var data          = new NotifierData
            {
                NotificationType = notificationType,
                ActivityType     = activity.Type,
                ReceiverIds      = ReceiverIds(comment, activity, notificationType, currentMember),
                Value            = _notifierDataHelper.GetCommentNotifierDataModel(activity, comment, notificationType, currentMember.Id)
            };

            return(data);
        }
Пример #34
0
        /// <summary>
        /// clear current chart and draw new from port
        /// </summary>
        /// <param name="port"></param>
        /// <param name="pm24"></param>
        private void DrawPortToChart(NE.Port port, bool pm24, bool ClearPrevSerias)
        {
            try
            {
                Chart chart = pm24 ? chart1 : chart2;
                ComboBox cb_line = pm24 ? comboBox1 : comboBox2;
                ComboBox cb_ports = pm24 ? comboBox3 : comboBox4;
                if (ClearPrevSerias) chart.Series.Clear();

                    #region series s1
                    Series s1 = new Series();
                    s1.ChartArea = "ChartArea1";
                    if (cb_line.SelectedItem != null) s1.ChartType = (SeriesChartType)Enum.Parse(typeof(SeriesChartType), cb_line.SelectedItem.ToString());
                    else s1.ChartType = SeriesChartType.SplineRange;
                    s1.Color = System.Drawing.Color.Red;
                    s1.CustomProperties = "EmptyPointValue=Zero";
                    s1.Legend = "Legend1";
                    s1.LegendText = "BBE";
                    s1.Name = port.PortName;
                    s1.IsVisibleInLegend = true;
                    s1.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Date;
                    s1.YValuesPerPoint = 2;
                    s1.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
                    #endregion
                    List<int> bbeList = new List<int>();
                    List<DateTime> dates = new List<DateTime>();
                if(port.Stat_Have_BBE()) //Добавление данных для графика
                    foreach (var stat in port.Stat)
                    { 
                        if (!pm24 && !stat.HaveError()) continue;//пропустим пустые дни для pm15
                        bbeList.Add(stat.BBE);
                        dates.Add(stat.Date);
                        s1.Points.AddXY(stat.Date, stat.BBE);
                    }else if(port.Stat_Have_FEBBE())
                {
                    foreach (var stat in port.Stat)
                    {
                        if (!pm24 && !stat.HaveError()) continue;//пропустим пустые дни для pm15
                        bbeList.Add(stat.FEBBE);
                        dates.Add(stat.Date);
                        s1.Points.AddXY(stat.Date, stat.FEBBE);
                    }
                    s1.LegendText = "FEBBE";
                }

                    //s1.LegendText = port.PortName;
                    chart.Series.Add(s1);
                chart.ChartAreas[0].RecalculateAxesScale();
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "DrawPortToChart Method");
            }
        }
Пример #35
0
		public static T GetAttributeValue<T>(this XElement element, XName attributeName, T defaultValue)
			where T : struct
		{
			T result = element.GetAttributeValue(attributeName, defaultValue, x => (T)Enum.Parse(typeof(T), x, false));
			return result;
		}
Пример #36
0
        private void SendKeysSeparately(HotKeySettings settings)
        {
            InputSimulator simulator = new InputSimulator();

            // Deceide which keys to press
            // Windows
            if (settings.Windows)
            {
                simulator.Keyboard.KeyDown(VirtualKeyCode.LWIN).Sleep(30);
            }

            // Control
            if (settings.Control)
            {
                simulator.Keyboard.KeyDown(VirtualKeyCode.LCONTROL).Sleep(30);
            }

            // Alt
            if (settings.Alt)
            {
                simulator.Keyboard.KeyDown(VirtualKeyCode.LMENU).Sleep(30);
            }

            // Shift
            if (settings.Shift)
            {
                simulator.Keyboard.KeyDown(VirtualKeyCode.LSHIFT).Sleep(30);
            }

            // Modifier
            if (settings.KeyCode != null)
            {
                foreach (var k in settings.KeyCode)
                {
                    if (!Enum.IsDefined(typeof(VirtualKeyCode), k.GetHashCode()))
                    {
                        continue;
                    }

                    var key = (VirtualKeyCode)k;
                    simulator.Keyboard.KeyPress(key).Sleep(30);
                }
            }
            // Release Shift
            if (settings.Shift)
            {
                simulator.Keyboard.KeyUp(VirtualKeyCode.LSHIFT).Sleep(30);
            }

            // Release Alt
            if (settings.Alt)
            {
                simulator.Keyboard.KeyUp(VirtualKeyCode.LMENU).Sleep(30);
            }

            // Release Control
            if (settings.Control)
            {
                simulator.Keyboard.KeyUp(VirtualKeyCode.LCONTROL).Sleep(30);
            }

            // Release Windows
            if (settings.Windows)
            {
                simulator.Keyboard.KeyUp(VirtualKeyCode.LWIN).Sleep(30);
            }
        }
Пример #37
0
	/// <summary>
	/// 指定された列挙型の値の数返します
	/// </summary>
	public int getEnumLength<T>() {
		return Enum.GetValues( typeof( T ) ).Length;
	}
Пример #38
0
        public override void ParseGroupCode(DXFDocument doc, int groupcode, string value)
        {
            base.ParseGroupCode(doc, groupcode, value);
            switch (groupcode)
            {
            case 2:
                _record.LineTypeName = value;
                break;

            case 3:
                _record.Description = value;
                break;

            case 72:
                _record.AlignmentCode = int.Parse(value);
                break;

            case 73:
                _record.ElementCount = int.Parse(value);
                break;

            case 40:
                _record.PatternLength = double.Parse(value);
                break;

            case 49:
                _subrecord = new DXFLineTypeRecord.LineTypeElement();
                _record.Elements.Add(_subrecord);
                _subrecord.Length = double.Parse(value);
                break;

            case 74:
                _subrecord.Flags = (DXFLineTypeRecord.ElementFlags)Enum.Parse(typeof(DXFLineTypeRecord.ElementFlags), value);
                break;

            case 75:
                _subrecord.ShapeNumber = int.Parse(value);
                break;

            case 340:
                _subrecord.Shape = value;
                break;

            case 46:
                _subrecord.Scalings.Add(double.Parse(value));
                break;

            case 50:
                _subrecord.Rotation = double.Parse(value);
                break;

            case 44:
                _subrecord.XOffsets.Add(double.Parse(value));
                break;

            case 45:
                _subrecord.YOffsets.Add(double.Parse(value));
                break;

            case 9:
                _subrecord.Text = value;
                break;
            }
        }
Пример #39
0
 static public void Dispatch(Enum eventType, object data = null)
 {
     Instance.m_eventsHandler.Dispatch(eventType, data);
 }
Пример #40
0
		public Configuration(ILogger logger)
		{
			var settings = ConfigurationManager.ConnectionStrings["RabbitMQ"];
			if (settings != null)
			{
				RabbitMqConnectionString = settings.ConnectionString;
			}

			RabbitMqClusterHosts = GetValue(nameof(RabbitMqClusterHosts));
			if (String.IsNullOrWhiteSpace(RabbitMqClusterHosts))
			{
				RabbitMqClusterHosts = null;
			}

			RabbitMqAutomaticRecoveryEnabled = true;
			if (Boolean.TryParse(GetValue(nameof(RabbitMqAutomaticRecoveryEnabled)), out var tmpBool))
			{
				RabbitMqAutomaticRecoveryEnabled = tmpBool;
			}

			QueueExpiration = TimeSpan.FromSeconds(10);
			if (TimeSpan.TryParse(GetValue(nameof(QueueExpiration)), out var tmpTimeSpan))
			{
				QueueExpiration = tmpTimeSpan;
			}

			RequestExpiration = TimeSpan.FromSeconds(10);
			if (TimeSpan.TryParse(GetValue(nameof(RequestExpiration)), out tmpTimeSpan))
			{
				RequestExpiration = tmpTimeSpan;
			}

			OnPremiseConnectorCallbackTimeout = TimeSpan.FromSeconds(30);
			if (TimeSpan.TryParse(GetValue(nameof(OnPremiseConnectorCallbackTimeout)), out tmpTimeSpan))
			{
				OnPremiseConnectorCallbackTimeout = tmpTimeSpan;
			}

			TraceFileDirectory = GetPathValue(nameof(TraceFileDirectory), logger) ?? "tracefiles";

			LinkPasswordLength = 100;
			if (Int32.TryParse(GetValue(nameof(LinkPasswordLength)), out var tmpInt))
			{
				LinkPasswordLength = tmpInt;
			}

			DisconnectTimeout = 6;
			if (Int32.TryParse(GetValue(nameof(DisconnectTimeout)), out tmpInt))
			{
				DisconnectTimeout = tmpInt;
			}

			ConnectionTimeout = 5;
			if (Int32.TryParse(GetValue(nameof(ConnectionTimeout)), out tmpInt))
			{
				ConnectionTimeout = tmpInt;
			}

			KeepAliveInterval = DisconnectTimeout / 3;
			if (Int32.TryParse(GetValue(nameof(KeepAliveInterval)), out tmpInt) && tmpInt >= KeepAliveInterval)
			{
				KeepAliveInterval = tmpInt;
			}

			UseInsecureHttp = false;
			if (Boolean.TryParse(GetValue(nameof(UseInsecureHttp)), out tmpBool))
			{
				UseInsecureHttp = tmpBool;
			}

			EnableManagementWeb = ModuleBinding.True;
			if (Enum.TryParse(GetValue(nameof(EnableManagementWeb)), true, out ModuleBinding tmpModuleBinding))
			{
				EnableManagementWeb = tmpModuleBinding;
			}

			EnableRelaying = ModuleBinding.True;
			if (Enum.TryParse(GetValue(nameof(EnableRelaying)), true, out tmpModuleBinding))
			{
				EnableRelaying = tmpModuleBinding;
			}

			EnableOnPremiseConnections = ModuleBinding.True;
			if (Enum.TryParse(GetValue(nameof(EnableOnPremiseConnections)), true, out tmpModuleBinding))
			{
				EnableOnPremiseConnections = tmpModuleBinding;
			}

			HostName = GetValue(nameof(HostName)) ?? "+";

			Port = UseInsecureHttp ? 20000 : 443;
			if (Int32.TryParse(GetValue(nameof(Port)), out tmpInt))
			{
				Port = tmpInt;
			}

			ManagementWebLocation = GetPathValue(nameof(ManagementWebLocation), logger);
			if (String.IsNullOrWhiteSpace(ManagementWebLocation))
			{
				ManagementWebLocation = "ManagementWeb";
			}

			TemporaryRequestStoragePath = GetPathValue(nameof(TemporaryRequestStoragePath), logger);
			if (String.IsNullOrWhiteSpace(TemporaryRequestStoragePath))
			{
				TemporaryRequestStoragePath = null;
			}

			TemporaryRequestStoragePeriod = OnPremiseConnectorCallbackTimeout + OnPremiseConnectorCallbackTimeout;
			if (TimeSpan.TryParse(GetValue(nameof(TemporaryRequestStoragePeriod)), out tmpTimeSpan) && tmpTimeSpan >= TemporaryRequestStoragePeriod)
			{
				TemporaryRequestStoragePeriod = tmpTimeSpan;
			}

			ActiveConnectionTimeout = TimeSpan.FromMinutes(2);
			if (TimeSpan.TryParse(GetValue(nameof(ActiveConnectionTimeout)), out tmpTimeSpan))
			{
				ActiveConnectionTimeout = tmpTimeSpan;
			}

			CustomCodeAssemblyPath = GetPathValue(nameof(CustomCodeAssemblyPath), logger);
			if (String.IsNullOrWhiteSpace(CustomCodeAssemblyPath))
			{
				CustomCodeAssemblyPath = null;
			}
			else if (!File.Exists(CustomCodeAssemblyPath))
			{
				logger?.Warning("A custom code assembly has been configured, but it is not available at the configured path. assembly-path={CustomCodeAssemblyPath}", CustomCodeAssemblyPath);
				CustomCodeAssemblyPath = null;
			}

			SharedSecret = GetValue(nameof(SharedSecret));
			OAuthCertificate = GetValue(nameof(OAuthCertificate));

			if (String.IsNullOrEmpty(SharedSecret) && String.IsNullOrEmpty(OAuthCertificate))
			{
				if (String.IsNullOrEmpty(TemporaryRequestStoragePath)) // assume Multi-Server operation mode when this folder is configured
				{
					logger?.Warning("No SharedSecret or OAuthCertificate is configured. Please configure one of them. Continuing with a random value which will make all tokens invalid on restart.");
					SharedSecret = Convert.ToBase64String(Guid.NewGuid().ToByteArray());
				}
				else
				{
					var message = "No SharedSecret or OAuthCertificate is configured, and RelayServer is set up for Multi-Server operation. You need to configure either SharedSecret or OAuthCertificate before starting RelayServer.";

					logger?.Error(message);
					throw new ConfigurationErrorsException(message);
				}
			}

			HstsHeaderMaxAge = TimeSpan.FromDays(365);
			if (TimeSpan.TryParse(GetValue(nameof(HstsHeaderMaxAge)), out tmpTimeSpan))
			{
				HstsHeaderMaxAge = tmpTimeSpan;
			}

			HstsIncludeSubdomains = false;
			if (Boolean.TryParse(GetValue(nameof(HstsIncludeSubdomains)), out tmpBool))
			{
				HstsIncludeSubdomains = tmpBool;
			}

			IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Default;
			if (Enum.TryParse(GetValue(nameof(IncludeErrorDetailPolicy)), true, out IncludeErrorDetailPolicy tmpIncludeErrorDetailPolicy))
			{
				IncludeErrorDetailPolicy = tmpIncludeErrorDetailPolicy;
			}

			MaxFailedLoginAttempts = 5;
			if (Int32.TryParse(GetValue(nameof(MaxFailedLoginAttempts)), out tmpInt))
			{
				MaxFailedLoginAttempts = tmpInt;
			}

			FailedLoginLockoutPeriod = TimeSpan.FromMinutes(15);
			if (TimeSpan.TryParse(GetValue(nameof(FailedLoginLockoutPeriod)), out tmpTimeSpan))
			{
				FailedLoginLockoutPeriod = tmpTimeSpan;
			}

			SecureClientController = false;
			if (Boolean.TryParse(GetValue(nameof(SecureClientController)), out tmpBool))
			{
				SecureClientController = tmpBool;
			}

			AccessTokenLifetime = TimeSpan.FromDays(365);
			if (TimeSpan.TryParse(GetValue(nameof(AccessTokenLifetime)), out tmpTimeSpan))
			{
				AccessTokenLifetime = tmpTimeSpan;
			}

			LogSensitiveData = true;
			if (Boolean.TryParse(GetValue(nameof(LogSensitiveData)), out tmpBool))
			{
				LogSensitiveData = tmpBool;
			}

			LinkTokenRefreshWindow = TimeSpan.FromMinutes(1);
			if (TimeSpan.TryParse(GetValue(nameof(LinkTokenRefreshWindow)), out tmpTimeSpan) && tmpTimeSpan < AccessTokenLifetime)
			{
				LinkTokenRefreshWindow = tmpTimeSpan;
			}

			LinkReconnectMinWaitTime = TimeSpan.FromSeconds(2);
			if (TimeSpan.TryParse(GetValue(nameof(LinkReconnectMinWaitTime)), out tmpTimeSpan))
			{
				LinkReconnectMinWaitTime = tmpTimeSpan;
			}

			LinkReconnectMaxWaitTime = TimeSpan.FromSeconds(30);
			if (TimeSpan.TryParse(GetValue(nameof(LinkReconnectMaxWaitTime)), out tmpTimeSpan) && tmpTimeSpan > LinkReconnectMinWaitTime)
			{
				LinkReconnectMaxWaitTime = tmpTimeSpan;
			}
			else if (LinkReconnectMaxWaitTime < LinkReconnectMinWaitTime)
			{
				 // something is fishy in the config
				 LinkReconnectMaxWaitTime = LinkReconnectMinWaitTime + TimeSpan.FromSeconds(30);
			}

			LinkAbsoluteConnectionLifetime = null;
			if (TimeSpan.TryParse(GetValue(nameof(LinkAbsoluteConnectionLifetime)), out tmpTimeSpan))
			{
				LinkAbsoluteConnectionLifetime = tmpTimeSpan;
			}

			LinkSlidingConnectionLifetime = null;
			if (TimeSpan.TryParse(GetValue(nameof(LinkSlidingConnectionLifetime)), out tmpTimeSpan))
			{
				LinkSlidingConnectionLifetime = tmpTimeSpan;
			}

			LogSettings(logger);
		}
Пример #41
0
	public List<ISharedCookedBuild> FindBestBuilds()
	{
		// Attempt manifest searching first
		ConfigHierarchy Hierarchy = ConfigCache.ReadHierarchy(ConfigHierarchyType.Engine, DirectoryReference.FromFile(ProjectFile), UnrealTargetPlatform.Win64);

		IReadOnlyList<string> RawSharedCookedSources = null;
		Hierarchy.TryGetValues("SharedCookedBuildSettings", "SharedCookedSources", out RawSharedCookedSources);
		if (RawSharedCookedSources == null)
		{
			throw new AutomationException("Unable to locate shared cooked builds. SharedCookedSources not set in Engine.ini [SharedCookedBuildSettings]");
		}

		List<Dictionary<string, string>> ParsedSharedCookSources = new List<Dictionary<string, string>>();
		foreach (string RawConfig in RawSharedCookedSources)
		{
			Dictionary<string, string> ParsedSource = null;
			if (ConfigHierarchy.TryParse(RawConfig, out ParsedSource))
			{
				ParsedSharedCookSources.Add(ParsedSource);
			}
		}

		List<ISharedCookedBuild> CandidateBuilds = new List<ISharedCookedBuild>();

		// If existing sync is present, stick to it. Read version out of sync file
		foreach (string Platform in TargetPlatforms)
		{
			FileReference SyncedBuildFile = new FileReference(CommandUtils.CombinePaths(InstallPath.FullName, Platform, SyncedBuildFileName));
			if (FileReference.Exists(SyncedBuildFile))
			{
				string[] SyncedBuildInfo = FileReference.ReadAllLines(SyncedBuildFile);
				int SyncedCL = int.Parse(SyncedBuildInfo[0]);
				if (IsValidCL(SyncedCL, BuildType, LocalSync))
				{
					CandidateBuilds.Add(new ExistingSharedCookedBuild() { CL = SyncedCL, Platform = Platform });
				}
			}
		}

		foreach (Dictionary<string, string> Source in ParsedSharedCookSources)
		{
			SharedCookSource SourceType = (SharedCookSource)Enum.Parse(typeof(SharedCookSource), Source["Type"], true);
			foreach (string Platform in TargetPlatforms)
			{
				if (SourceType == SharedCookSource.Manifest)
				{
					CandidateBuilds.AddRange(FindValidManifestBuilds(Source["Path"], Platform));
				}
				else if (SourceType == SharedCookSource.LooseFiles)
				{
					CandidateBuilds.AddRange(FindValidLooseBuilds(Source["Path"], Platform));
				}
			}
		}

		// Strip all failed searches
		CandidateBuilds.RemoveAll(x => x == null);

		// Make sure we have a matching CL for all target platforms, regardless of source
		List<int> OrderedDistinctCLs = CandidateBuilds.Select(x => x.CL).Distinct().OrderByDescending(i => i).ToList();
		int BestCL = -1;
		foreach (int CL in OrderedDistinctCLs)
		{
			// Ensure we have a platform for each
			HashSet<string> CLPlatforms = new HashSet<string>(CandidateBuilds.Where(x => x.CL == CL).Select(x => x.Platform).ToList());
			if (CLPlatforms.SetEquals(TargetPlatforms))
			{
				BestCL = CL;
				break;
			}
		}

		if (BestCL < 0)
		{
			CommandUtils.LogError("Could not locate valid shared cooked build for all target platforms");
			CommandUtils.LogError("Current CL: {0}, Current Code CL: {1}", LocalSync.Changelist, LocalSync.CompatibleChangelist);
		}

		return CandidateBuilds.Where(x => x.CL == BestCL).ToList();
	}
 static string GetLetter(int num)
 {
     return Enum.Parse(typeof(Letters), num.ToString()).ToString();
 }
Пример #43
0
        /// <summary>
        /// Get the lossless equivalent type for serialization
        /// </summary>
        /// <param name="type">A .NET type to serialize</param>
        /// <param name="bestType">The optimal field type for the provided .NET type, or 0 if none can be determined.</param>
        /// <returns>A boolean indicating that no matching type was found.</returns>
        /// <remarks>No exception is raised if no matching type can be found, instead the best type is set to zero (invalid)
        /// and false is returned.</remarks>
        public static bool TryGetSerializableType(Type type, out FieldType bestType)
        {
            bestType = 0; //0 is bad...

            if (type == typeof(DateTime))
            {
                bestType = FieldType.DateTime;
            }
            else if (type == typeof(DateTime[]))
            {
                bestType = FieldType.DateTimeArray;
            }
            else if (type == typeof(DateTimeOffset))
            {
                bestType = FieldType.DateTimeOffset;
            }
            else if (type == typeof(DateTimeOffset[]))
            {
                bestType = FieldType.DateTimeOffsetArray;
            }
            else if (type == typeof(TimeSpan))
            {
                bestType = FieldType.TimeSpan;
            }
            else if (type == typeof(TimeSpan[]))
            {
                bestType = FieldType.TimeSpanArray;
            }
            else if (type == typeof(String))
            {
                bestType = FieldType.String;
            }
            else if (type == typeof(String[]))
            {
                bestType = FieldType.StringArray;
            }
            else if (type == typeof(Int64))
            {
                bestType = FieldType.Int64;
            }
            else if (type == typeof(Int64[]))
            {
                bestType = FieldType.Int64Array;
            }
            else if (type == typeof(UInt64))
            {
                bestType = FieldType.UInt64;
            }
            else if (type == typeof(UInt64[]))
            {
                bestType = FieldType.UInt64Array;
            }
            else if (type == typeof(Int32))
            {
                bestType = FieldType.Int32;
            }
            else if (type == typeof(Int32[]))
            {
                bestType = FieldType.Int32Array;
            }
            else if (type == typeof(UInt32))
            {
                bestType = FieldType.UInt32;
            }
            else if (type == typeof(UInt32[]))
            {
                bestType = FieldType.UInt32Array;
            }
            else if (type == typeof(Int16))
            {
                bestType = FieldType.Int32;
            }
            else if (type == typeof(Int16[]))
            {
                bestType = FieldType.Int32Array;
            }
            else if (type == typeof(UInt16))
            {
                bestType = FieldType.UInt32;
            }
            else if (type == typeof(UInt16[]))
            {
                bestType = FieldType.UInt32Array;
            }
            else if (type == typeof(Double))
            {
                bestType = FieldType.Double;
            }
            else if (type == typeof(Double[]))
            {
                bestType = FieldType.DoubleArray;
            }
            else if (type == typeof(Decimal)) // Note: Does this cast to a double without loss?
            {
                bestType = FieldType.Double;
            }
            else if (type == typeof(Decimal[]))
            {
                bestType = FieldType.DoubleArray;
            }
            else if (type == typeof(Single))
            {
                bestType = FieldType.Double;
            }
            else if (type == typeof(Single[]))
            {
                bestType = FieldType.DoubleArray;
            }
            else if (type == typeof(Boolean))
            {
                bestType = FieldType.Bool;
            }
            else if (type == typeof(Boolean[]))
            {
                bestType = FieldType.BoolArray;
            }
            else if (type == typeof(Guid))
            {
                bestType = FieldType.Guid;
            }
            else if (type == typeof(Guid[]))
            {
                bestType = FieldType.GuidArray;
            }
            else
            {
                var baseType = type.GetTypeInfo().BaseType;
                if (baseType == typeof(Enum))
                {
                    Type underlyingType = Enum.GetUnderlyingType(type);
                    return(TryGetSerializableType(underlyingType, out bestType));
                }
                else if (baseType == typeof(Enum[]))
                {
                    Type underlyingType = Enum.GetUnderlyingType(type);
                    return(TryGetSerializableType(underlyingType, out bestType));
                }
            }

            if (bestType == 0)
            {
                //we didn't find a matching type
                return(false);
            }

            return(true);
        }
Пример #44
0
        void ButtonVisibilityOptionsTest(string buttonNamePrefix)
        {
            SetButtonVisibilityModeFunction SetButtonVisibilityMode;
            UIObject buttonBeingTested;

            using (var setup = new TestSetupHelper("Pager Tests"))
            {

                elements = new PagerTestsPageElements();
                switch (buttonNamePrefix)
                {
                    case "First":
                        SetButtonVisibilityMode = SetFirstPageButtonVisibilityMode;
                        buttonBeingTested = elements.GetFirstPageButton();
                        break;
                    case "Previous":
                        SetButtonVisibilityMode = SetPreviousPageButtonVisibilityMode;
                        buttonBeingTested = elements.GetPreviousPageButton();
                        break;
                    case "Next":
                        SetButtonVisibilityMode = SetNextPageButtonVisibilityMode;
                        buttonBeingTested = elements.GetNextPageButton();
                        break;
                    case "Last":
                        SetButtonVisibilityMode = SetLastPageButtonVisibilityMode;
                        buttonBeingTested = elements.GetLastPageButton();
                        break;
                    default:
                        Log.Warning("This test is being skipped because the button string was not one of these four strings: [First, Previous, Next, Last]");
                        return;
                }

                VerifyPageChanged(0);

                foreach (ButtonVisibilityModes visMode in Enum.GetValues(typeof(ButtonVisibilityModes)))
                {
                    SetButtonVisibilityMode(visMode);
                    GetLastPage();
                    // If we're not on the first page then navigate to the first page.
                    if (previousPage != 0)
                    {
                        SelectValueInPagerComboBox(0);
                        VerifyPageChanged(0);
                    }

                    var expectedVisibility = ((visMode == ButtonVisibilityModes.None) ||
                        (visMode == ButtonVisibilityModes.HiddenOnEdge &&
                        (buttonNamePrefix == "First" || buttonNamePrefix == "Previous"))) ? Visibility.Collapsed : Visibility.Visible;

                    var expectedIsEnableValue = (buttonNamePrefix == "First" || buttonNamePrefix == "Previous") ? false : true;

                    VerifyButton(buttonBeingTested, expectedVisibility, expectedIsEnableValue);

                    SelectValueInPagerComboBox(1);
                    VerifyPageChanged(1);

                    expectedVisibility = (visMode == ButtonVisibilityModes.None) ? Visibility.Collapsed : Visibility.Visible;
                    expectedIsEnableValue = true;

                    VerifyButton(buttonBeingTested, expectedVisibility, expectedIsEnableValue);

                    SelectValueInPagerComboBox(GetLastPageAsInt() - 1);
                    VerifyPageChanged(GetLastPageAsInt() - 1);

                    expectedVisibility = ((visMode == ButtonVisibilityModes.None) ||
                        (visMode == ButtonVisibilityModes.HiddenOnEdge &&
                        (buttonNamePrefix == "Next" || buttonNamePrefix == "Last"))) ? Visibility.Collapsed : Visibility.Visible;

                    expectedIsEnableValue = (buttonNamePrefix == "Next" || buttonNamePrefix == "Last") ? false : true;

                    VerifyButton(buttonBeingTested, expectedVisibility, expectedIsEnableValue);
                }
            }
        }
Пример #45
0
        internal static List<DirectInputKeyCode> ExtractKeyStrokes(string macroText)
        {
            var keyStrokes = new List<DirectInputKeyCode>();


            try
            {
                var matches = Regex.Matches(macroText, REGEX_SUB_COMMAND);
                foreach (var match in matches)
                {
                    var matchText = match.ToString().ToUpperInvariant().Replace("{", "").Replace("}", "");

                    if (Program.Bindings.KeyboardLayout == "en-US")
                    {
                        // http://kbdlayout.info/kbdusx/shiftstates+scancodes/base

                        // FIRST ROW  DIKGRAVE          DIKMINUS        DIKEQUALS
                        // SECOND ROW DIKLEFTBRACKET    DIKRIGHTBRACKET DIKBACKSLASH
                        // THIRD ROW  DIKSEMICOLON      DIKAPOSTROPHE
                        // FOURTH ROW DIKCOMMA          DIKPERIOD       DIKSLASH
                    }
                    else if (Program.Bindings.KeyboardLayout == "es-ES")
                    {
                        // http://kbdlayout.info/kbdsp/shiftstates+scancodes/base

                        // FIRST ROW
                        // SECOND ROW 
                        // THIRD ROW
                        // FOURTH ROW

                        // all the keys are the same as en-US in binding file , for some reason ????
                    }
                    else if (Program.Bindings.KeyboardLayout == "en-GB")
                    {
                        // http://kbdlayout.info/kbduk/shiftstates+scancodes/base

                        switch (matchText)
                        {
                            // third row
                            case "DIKHASH":
                                matchText = "DIKBACKSLASH";
                                break;
                        }
                    }
                    else if (Program.Bindings.KeyboardLayout == "fr-FR")
                    {
                        // http://kbdlayout.info/kbdfr/shiftstates+scancodes/base

                        switch (matchText)
                        {
                            // FIRST ROW
                            case "DIKSUPERSCRIPTTWO":
                                matchText = "DIKGRAVE";
                                break;
                            case "DIKAMPERSAND":
                                matchText = "DIK1";
                                break;
                            case "DIKÉ":
                                matchText = "DIK2";
                                break;
                            case "DIKDOUBLEQUOTE":
                                matchText = "DIK3";
                                break;
                            case "DIKAPOSTROPHE":
                                matchText = "DIK4";
                                break;
                            case "DIKLEFTPARENTHESIS":
                                matchText = "DIK5";
                                break;
                            case "DIKMINUS":
                                matchText = "DIK6";
                                break;
                            case "DIKÈ":
                                matchText = "DIK7";
                                break;
                            case "DIKUNDERLINE":
                                matchText = "DIK8";
                                break;
                            case "DIKÇ":
                                matchText = "DIK9";
                                break;
                            case "DIKÀ":
                                matchText = "DIK0";
                                break;
                            case "DIKRIGHTPARENTHESIS":
                                matchText = "DIKMINUS";
                                break;

                            // SECOND ROW
                            case "DIKA":
                                matchText = "DIKQ";
                                break;
                            case "DIKZ":
                                matchText = "DIKW";
                                break;
                            case "DIKCIRCUMFLEX":
                                matchText = "DIKLEFTBRACKET";
                                break;
                            case "DIKDOLLAR":
                                matchText = "DIKRIGHTBRACKET";
                                break;

                            // THIRD ROW
                            case "DIKM":
                                matchText = "DIKSEMICOLON";
                                break;
                            case "DIKÙ":
                                matchText = "DIKAPOSTROPHE";
                                break;
                            case "DIKASTERISK":
                                matchText = "DIKBACKSLASH";
                                break;

                            // FOURTH ROW
                            case "DIKW":
                                matchText = "DIKZ";
                                break;
                            case "DIKCOMMA":
                                matchText = "DIKM";
                                break;
                            case "DIKSEMICOLON":
                                matchText = "DIKCOMMA";
                                break;
                            case "DIKCOLON":
                                matchText = "DIKPERIOD";
                                break;
                            case "DIKEXCLAMATIONPOINT":
                                matchText = "DIKSLASH";
                                break;
                        }

                    }
                    else if (Program.Bindings.KeyboardLayout == "de-DE")
                    {
                        switch (matchText)
                        {
                            // FIRST ROW
                            case "DIKCIRCUMFLEX":
                                matchText = "DIKGRAVE";
                                break;
                            case "DIKß":
                                matchText = "DIKMINUS";
                                break;
                            case "DIKACUTE":
                                matchText = "DIKEQUALS";
                                break;

                            // SECOND ROW 
                            case "DIKZ":
                                matchText = "DIKY";
                                break;
                            case "DIKÜ":
                                matchText = "DIKLEFTBRACKET";
                                break;
                            case "DIKPLUS":
                                matchText = "DIKRIGHTBRACKET";
                                break;
                            case "DIKHASH":
                                matchText = "DIKBACKSLASH";
                                break;

                            // THIRD ROW
                            case "DIKÖ":
                                matchText = "DIKSEMICOLON";
                                break;
                            case "DIKÄ":
                                matchText = "DIKAPOSTROPHE";
                                break;

                            // FOURTH ROW
                            case "DIKY":
                                matchText = "DIKZ";
                                break;
                            case "DIKMINUS":
                                matchText = "DIKSLASH";
                                break;
                        }

                    }
                    else if (Program.Bindings.KeyboardLayout == "de-CH")
                    {
                        switch (matchText)
                        {
                            // FIRST ROW
                            case "DIK§":
                                matchText = "DIKGRAVE";
                                break;
                            case "DIKAPOSTROPHE":
                                matchText = "DIKMINUS";
                                break;
                            case "DIKCIRCUMFLEX":
                                matchText = "DIKEQUALS";
                                break;

                            // SECOND ROW 
                            case "DIKZ":
                                matchText = "DIKY";
                                break;
                            case "DIKÜ":
                                matchText = "DIKLEFTBRACKET";
                                break;
                            case "DIKUMLAUT":
                                matchText = "DIKRIGHTBRACKET";
                                break;
                            case "DIKDOLLAR":
                                matchText = "DIKBACKSLASH";
                                break;

                            // THIRD ROW
                            case "DIKÖ":
                                matchText = "DIKSEMICOLON";
                                break;
                            case "DIKÄ":
                                matchText = "DIKAPOSTROPHE";
                                break;

                            // FOURTH ROW
                            case "DIKY":
                                matchText = "DIKZ";
                                break;
                            case "DIKMINUS":
                                matchText = "DIKSLASH";
                                break;

                        }

                    }
                    else if (Program.Bindings.KeyboardLayout == "da-DK")
                    {
                        switch (matchText)
                        {
                            // FIRST ROW
                            case "DIKHALF":
                                matchText = "DIKGRAVE";
                                break;
                            case "DIKPLUS":
                                matchText = "DIKMINUS";
                                break;
                            case "DIKACUTE":
                                matchText = "DIKEQUALS";
                                break;

                            // SECOND ROW 
                            case "DIKÅ":
                                matchText = "DIKLEFTBRACKET";
                                break;
                            case "DIKUMLAUT":
                                matchText = "DIKRIGHTBRACKET";
                                break;
                            case "DIKAPOSTROPHE":
                                matchText = "DIKBACKSLASH";
                                break;

                            // THIRD ROW
                            case "DIKÆ":
                                matchText = "DIKSEMICOLON";
                                break;
                            case "DIKØ":
                                matchText = "DIKAPOSTROPHE";
                                break;

                            // FOURTH ROW
                            case "DIKMINUS":
                                matchText = "DIKSLASH";
                                break;
                        }

                    }
                    else if (Program.Bindings.KeyboardLayout == "it-IT")
                    {
                        switch (matchText)
                        {
                            // FIRST ROW
                            case "DIKBACKSLASH":
                                matchText = "DIKGRAVE";
                                break;
                            case "DIKAPOSTROPHE":
                                matchText = "DIKMINUS";
                                break;
                            case "DIKÌ":
                                matchText = "DIKEQUALS";
                                break;

                            // SECOND ROW 
                            case "DIKÈ":
                                matchText = "DIKLEFTBRACKET";
                                break;
                            case "DIKPLUS":
                                matchText = "DIKRIGHTBRACKET";
                                break;
                            case "DIKÙ":
                                matchText = "DIKBACKSLASH";
                                break;

                            // THIRD ROW
                            case "DIKÒ":
                                matchText = "DIKSEMICOLON";
                                break;
                            case "DIKÀ":
                                matchText = "DIKAPOSTROPHE";
                                break;

                            // FOURTH ROW
                            case "DIKMINUS":
                                matchText = "DIKSLASH";
                                break;
                        }

                    }

                    else if (Program.Bindings.KeyboardLayout == "pt-PT")
                    {
                        switch (matchText)
                        {
                            // FIRST ROW
                            case "DIKBACKSLASH":
                                matchText = "DIKGRAVE";
                                break;
                            case "DIKAPOSTROPHE":
                                matchText = "DIKMINUS";
                                break;
                            case "DIK«":
                                matchText = "DIKEQUALS";
                                break;

                            // SECOND ROW 
                            case "DIKPLUS":
                                matchText = "DIKLEFTBRACKET";
                                break;
                            case "DIKACUTE":
                                matchText = "DIKRIGHTBRACKET";
                                break;
                            case "DIKTILDE":
                                matchText = "DIKBACKSLASH";
                                break;

                            // THIRD ROW
                            case "DIKÇ":
                                matchText = "DIKSEMICOLON";
                                break;
                            case "DIKº":
                                matchText = "DIKAPOSTROPHE";
                                break;

                            // FOURTH ROW
                            case "DIKMINUS":
                                matchText = "DIKSLASH";
                                break;
                        }

                    }


                    var stroke = (DirectInputKeyCode)Enum.Parse(typeof(DirectInputKeyCode), matchText, true);

                    keyStrokes.Add(stroke);
                }
            }
            catch (Exception ex)
            {
                Logger.Instance.LogMessage(TracingLevel.FATAL, $"ExtractKeyStrokes Exception: {ex}");
            }

            return keyStrokes;
        }
Пример #46
0
        /// <summary>
        /// Detects Visual Studio installations using the Windows registry
        /// </summary>
        /// <returns>
        /// The detected Visual Studio installations
        /// </returns>
        private static IDictionary<VisualStudioVersion, VisualStudioPath[]> GetInstalledVisualStudios()
        {
            var versions = new Dictionary<VisualStudioVersion, VisualStudioPath[]>();

            if (SolutionSynchronizationSettings.IsWindows)
            {
                foreach (VisualStudioVersion version in Enum.GetValues(typeof(VisualStudioVersion)))
                {
                    if (version > VisualStudioVersion.VisualStudio2015)
                        continue;

                    try
                    {
                        // Try COMNTOOLS environment variable first
                        string key = Environment.GetEnvironmentVariable(string.Format("VS{0}0COMNTOOLS", (int)version));
                        if (!string.IsNullOrEmpty(key))
                        {
                            string path = UnityEditor.Utils.Paths.Combine(key, "..", "IDE", "devenv.exe");
                            if (File.Exists(path))
                            {
                                versions[version] = new[] { new VisualStudioPath(path) };
                                continue;
                            }
                        }

                        // Try the proper registry key
                        key = GetRegistryValue(
                            string.Format(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\{0}.0", (int)version), "InstallDir");

                        // Try to fallback to the 32bits hive
                        if (string.IsNullOrEmpty(key))
                            key = GetRegistryValue(
                                string.Format(@"HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\{0}.0", (int)version), "InstallDir");

                        if (!string.IsNullOrEmpty(key))
                        {
                            string path = UnityEditor.Utils.Paths.Combine(key, "devenv.exe");
                            if (File.Exists(path))
                            {
                                versions[version] = new[] { new VisualStudioPath(path) };
                                continue;
                            }
                        }

                        // Fallback to debugger key
                        key = GetRegistryValue(
                            // VS uses this key for the local debugger path
                            string.Format(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\{0}.0\Debugger", (int)version), "FEQARuntimeImplDll");
                        if (!string.IsNullOrEmpty(key))
                        {
                            string path = DeriveVisualStudioPath(key);
                            if (!string.IsNullOrEmpty(path) && File.Exists(path))
                                versions[version] = new[] { new VisualStudioPath(DeriveVisualStudioPath(key)) };
                        }
                    }
                    catch
                    {
                        // This can happen with a registry lookup failure
                    }
                }

                var requiredWorkloads = new[] {"Microsoft.VisualStudio.Workload.ManagedGame"};
                var raw = VisualStudioUtil.FindVisualStudioDevEnvPaths((int)VisualStudioVersion.VisualStudio2017, requiredWorkloads);

                var visualStudioPaths = VisualStudioUtil.ParseRawDevEnvPaths(raw)
                    .Where(vs => !requiredWorkloads.Except(vs.Workloads).Any()) // All required workloads must be present
                    .Select(vs => new VisualStudioPath(vs.DevEnvPath, vs.Edition))
                    .ToArray();

                if (visualStudioPaths.Length != 0)
                {
                    versions[VisualStudioVersion.VisualStudio2017] = visualStudioPaths;
                }
            }

            return versions;
        }
Пример #47
0
        private void SendShortcutKeys(HotKeySettings settings)
        {
            if (settings.SendByKeybdEvent)
            {
                // Create keyboard keys to represent hot key combinations
                KeyboardKey winKey     = new KeyboardKey(Keys.LWin);
                KeyboardKey controlKey = new KeyboardKey(Keys.LControlKey);
                KeyboardKey altKey     = new KeyboardKey(Keys.LMenu);
                KeyboardKey shiftKey   = new KeyboardKey(Keys.LShiftKey);

                // Deceide which keys to press
                // Windows
                if (settings.Windows)
                {
                    winKey.Press();
                }

                // Control
                if (settings.Control)
                {
                    controlKey.Press();
                }

                // Alt
                if (settings.Alt)
                {
                    altKey.Press();
                }

                // Shift
                if (settings.Shift)
                {
                    shiftKey.Press();
                }

                // Modifier
                if (settings.KeyCode != null)
                {
                    foreach (var k in settings.KeyCode)
                    {
                        KeyboardKey modifierKey = new KeyboardKey(k);
                        if (!String.IsNullOrEmpty(modifierKey.KeyName))
                        {
                            modifierKey.PressAndRelease();
                        }
                    }
                }
                // Release Shift
                if (settings.Shift)
                {
                    shiftKey.Release();
                }

                // Release Alt
                if (settings.Alt)
                {
                    altKey.Release();
                }

                // Release Control
                if (settings.Control)
                {
                    controlKey.Release();
                }

                // Release Windows
                if (settings.Windows)
                {
                    winKey.Release();
                }
            }
            else
            {
                InputSimulator        simulator    = new InputSimulator();
                List <VirtualKeyCode> modifiedKeys = new List <VirtualKeyCode>();
                List <VirtualKeyCode> keys         = new List <VirtualKeyCode>();

                if (settings.KeyCode != null)
                {
                    foreach (var k in settings.KeyCode)
                    {
                        if (!Enum.IsDefined(typeof(VirtualKeyCode), k.GetHashCode()))
                        {
                            continue;
                        }

                        var key = (VirtualKeyCode)k;
                        keys.Add(key);
                    }
                }

                if (settings.Windows)
                {
                    modifiedKeys.Add(VirtualKeyCode.LWIN);
                }
                if (settings.Control)
                {
                    modifiedKeys.Add(VirtualKeyCode.LCONTROL);
                }
                if (settings.Alt)
                {
                    modifiedKeys.Add(VirtualKeyCode.LMENU);
                }
                if (settings.Shift)
                {
                    modifiedKeys.Add(VirtualKeyCode.LSHIFT);
                }

                if (modifiedKeys.Count == 0)
                {
                    if (keys.Count != 0)
                    {
                        simulator.Keyboard.KeyPress(keys.ToArray()).Sleep(30);
                    }
                }
                else
                {
                    if (keys.Count != 0)
                    {
                        simulator.Keyboard.ModifiedKeyStroke(modifiedKeys, keys).Sleep(30);
                    }
                    else
                    {
                        simulator.Keyboard.KeyPress(modifiedKeys.ToArray()).Sleep(30);
                    }
                }
            }
        }
Пример #48
0
        public MapEnvironment(Tileset tileset, uint width, uint height, int cliffLevel, RectangleMargins cameraBoundsComplements)
            : this()
        {
            if (!Enum.IsDefined(typeof(Tileset), tileset))
            {
                throw new ArgumentOutOfRangeException(nameof(tileset));
            }

            var maxx = width - 1;

            if ((maxx % 32) != 0 || width == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(width));
            }

            var maxy = height - 1;

            if ((maxy % 32) != 0 || height == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(height));
            }

            if (cameraBoundsComplements is null)
            {
                throw new ArgumentNullException(nameof(cameraBoundsComplements));
            }

            _tileset = tileset;
            _version = LatestVersion;
            _width   = width;
            _height  = height;
            _left    = MapWidth / -2f;
            _bottom  = MapHeight / -2f;

            _terrainTypes = GetDefaultTerrainTypes().ToList();
            _cliffTypes   = GetDefaultCliffTypes().ToList();

            var edgeLeft   = cameraBoundsComplements.Left;
            var edgeRight  = maxx - cameraBoundsComplements.Right;
            var edgeBottom = cameraBoundsComplements.Bottom;
            var edgeTop    = maxy - cameraBoundsComplements.Top;

            for (var y = 0; y < _width; y++)
            {
                for (var x = 0; x < _height; x++)
                {
                    var tile = new MapTile();

                    tile.CliffLevel     = cliffLevel;
                    tile.CliffTexture   = 15;
                    tile.CliffVariation = 0;

                    tile.Height      = 0;
                    tile.IsBlighted  = false;
                    tile.IsBoundary  = false;
                    tile.IsEdgeTile  = x != maxx && y != maxy && (x < edgeLeft || x >= edgeRight || y < edgeBottom || y >= edgeTop);
                    tile.IsRamp      = false;
                    tile.IsWater     = false;
                    tile.Texture     = 0;
                    tile.Variation   = 0;
                    tile.WaterHeight = 0;

                    _tiles.Add(tile);
                }
            }
        }
Пример #49
0
 public static object GetEnumValue(Enum e)
 {
     return(e.GetValue());
 }
Пример #50
0
 public GameDrawingArea()
 {
     UseSolutionArea = true;
     SolutionIcon    = SolutionType.None;
     images          = new SVGImage [Enum.GetValues(typeof(SolutionType)).Length];
 }
Пример #51
0
 public void ReadValues(Data data, string path = "")
 {
     Enabled   = bool.TryParse(data.GetValue(@"" + path + @"Enabled"), out var tmpEnabled) ? tmpEnabled : false;
     Seperator = Enum.TryParse <UserTokenSeperator>(data.GetValue(@"" + path + @"Seperator"), out var tmpSeperator) ? tmpSeperator : UserTokenSeperator.SquareBrackets;
 }
Пример #52
0
		/// <summary>
		///     Initializes a new instance of the <see cref="ProtectionPipeline" /> class.
		/// </summary>
		public ProtectionPipeline() {
			var stages = (PipelineStage[])Enum.GetValues(typeof(PipelineStage));
			preStage = stages.ToDictionary(stage => stage, stage => new List<ProtectionPhase>());
			postStage = stages.ToDictionary(stage => stage, stage => new List<ProtectionPhase>());
		}
Пример #53
0
        internal object ConvertToType(Type type, object obj)
        {
            if (obj == null)
                return null;

            if (obj is IDictionary<string, object>)
            {
                if (type == null)
                    obj = EvaluateDictionary((IDictionary<string, object>)obj);
                else
                {
                    JavaScriptConverter converter = GetConverter(type);
                    if (converter != null)
                        return converter.Deserialize(
                            EvaluateDictionary((IDictionary<string, object>)obj),
                            type, this);
                }

                return ConvertToObject((IDictionary<string, object>)obj, type);
            }
            if (obj is ArrayList)
                return ConvertToList((ArrayList)obj, type);

            if (type == null)
                return obj;

            Type sourceType = obj.GetType();
            if (type.IsAssignableFrom(sourceType))
                return obj;

            if (type.IsEnum)
                if (obj is string)
                    return Enum.Parse(type, (string)obj, true);
                else
                    return Enum.ToObject(type, obj);

            TypeConverter c = TypeDescriptor.GetConverter(type);
            if (c.CanConvertFrom(sourceType))
            {
                if (obj is string)
                    return c.ConvertFromInvariantString((string)obj);

                return c.ConvertFrom(obj);
            }


            if ((type.IsGenericType) && (type.GetGenericTypeDefinition() == typeof(Nullable<>)))
            {
                /*
                 * Take care of the special case whereas in JSON an empty string ("") really means 
                 * an empty value 
                 * (see: https://bugzilla.novell.com/show_bug.cgi?id=328836)
                 */
                string s = obj as String;
                if (s != null)
                {
                    if (s == string.Empty)
                        return null;
                }
                else //It is not string at all, convert to Nullable<> type, from int to uint for example
                    return Convert.ChangeType (obj, type.GetGenericArguments ()[0]);
            }

            return Convert.ChangeType(obj, type);
        }
Пример #54
0
        /// <summary>
        /// Loads the file from the specified stream.
        /// </summary>
        /// <param name="stream">The stream to read from.</param>
        public override void Load(Stream stream) {
            BinaryReader reader = new BinaryReader(stream, Encoding.GetEncoding("us-ascii"));
            AlignedBinaryReader alignedReader = new AlignedBinaryReader(stream, Encoding.GetEncoding("us-ascii"));

            int patternCount = reader.ReadInt32();
            IdleInterval = reader.ReadInt32();
            DamageRate = reader.ReadInt32();
            Name = reader.ReadIntString();

            for (int i = 0; i < patternCount; i++) {
                var pattern = new ArtificialIntelligencePattern();
                pattern.Name = reader.ReadString(32).TrimEnd('\0');

                int eventCount = reader.ReadInt32();

                for (int j = 0; j < eventCount; j++) {
                    var @event = new ArtificialIntelligenceEvent();
                    @event.Name = reader.ReadString(32).TrimEnd('\0');

                    int conditionCount = reader.ReadInt32();

                    for (int k = 0; k < conditionCount; k++) {
                        long position = stream.Position;
                        int size = reader.ReadInt32();
                        var type = (ArtificialIntelligenceCondition)(reader.ReadInt32() ^ CONDITION_MASK);

                        if (!Enum.IsDefined(typeof(ArtificialIntelligenceCondition), type)) {
                            throw new InvalidArtificialIntelligenceConditionException((int)type);
                        }

                        Type classType = type.GetAttributeValue<ArtificialIntelligenceTypeAttribute, Type>(x => x.Type);
                        var condition = (IArtificialIntelligenceCondition)Activator.CreateInstance(classType);

                        alignedReader.Reset();
                        condition.Read(alignedReader);
                        alignedReader.Align();

                        @event.Conditions.Add(condition);

                        if (stream.Position - position != size) {
                            stream.Seek(position + size, SeekOrigin.Begin);
                        }
                    }

                    int actionCount = reader.ReadInt32();

                    for (int k = 0; k < actionCount; k++) {
                        long position = stream.Position;
                        int size = reader.ReadInt32();
                        var type = (ArtificialIntelligenceAction)(reader.ReadInt32() ^ ACTION_MASK);

                        if (!Enum.IsDefined(typeof(ArtificialIntelligenceAction), type)) {
                            throw new InvalidArtificialIntelligenceActionException((int)type);
                        }

                        Type classType = type.GetAttributeValue<ArtificialIntelligenceTypeAttribute, Type>(x => x.Type);
                        var action = (IArtificialIntelligenceAction)Activator.CreateInstance(classType);

                        alignedReader.Reset();
                        action.Read(alignedReader);
                        alignedReader.Align();

                        @event.Actions.Add(action);

                        if (stream.Position - position != size) {
                            stream.Seek(position + size, SeekOrigin.Begin);
                        }
                    }

                    pattern.Events.Add(@event);
                }

                Patterns.Add(pattern);
            }
        }
        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The reader to use.</param>
        /// <param name="objectType">The object type to serialize into.</param>
        /// <param name="existingValue">The current value of the property.</param>
        /// <param name="serializer">The serializer to use.</param>
        /// <returns>The deserialized <see cref="Asset"/>.</returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var jsonObject = JObject.Load(reader);

            if (jsonObject.TryGetValue("size", out var jToken))
            {
                return(new SizeValidator(
                           jToken["min"].ToNullableInt(),
                           jToken["max"].ToNullableInt(),
                           jsonObject["message"]?.ToString()));
            }


            if (jsonObject.TryGetValue("range", out jToken))
            {
                return(new RangeValidator(
                           jToken["min"].ToNullableInt(),
                           jToken["max"].ToNullableInt(),
                           jsonObject["message"]?.ToString()));
            }

            if (jsonObject.TryGetValue("in", out jToken))
            {
                return(new InValuesValidator(jToken.Values <string>(), jsonObject["message"]?.ToString()));
            }

            if (jsonObject.TryGetValue("linkMimetypeGroup", out jToken))
            {
                if (jToken is JValue)
                {
                    //single string value returned for mime type field. This seems to be an inconsistency in the API that needs to be handled.

                    var type = jToken.Value <string>();
                    return(new MimeTypeValidator(new[] { (MimeTypeRestriction)Enum.Parse(typeof(MimeTypeRestriction), type, true) },
                                                 jsonObject["message"]?.ToString()));
                }

                var types = jToken.Values <string>();
                return(new MimeTypeValidator(types.Select(c => (MimeTypeRestriction)Enum.Parse(typeof(MimeTypeRestriction), c, true)),
                                             jsonObject["message"]?.ToString()));
            }

            if (jsonObject.TryGetValue("linkContentType", out jToken))
            {
                return(new LinkContentTypeValidator(jToken.Values <string>(), jsonObject["message"]?.ToString()));
            }

            if (jsonObject.TryGetValue("regexp", out jToken))
            {
                return(new RegexValidator(jToken["pattern"]?.ToString(), jToken["flags"]?.ToString(), jsonObject["message"]?.ToString()));
            }

            if (jsonObject.TryGetValue("unique", out jToken))
            {
                return(new UniqueValidator());
            }

            if (jsonObject.TryGetValue("dateRange", out jToken))
            {
                return(new DateRangeValidator(
                           jToken["min"]?.ToString(),
                           jToken["max"]?.ToString(),
                           jsonObject["message"]?.ToString()));
            }

            if (jsonObject.TryGetValue("assetFileSize", out jToken))
            {
                return(new FileSizeValidator(
                           jToken["min"].ToNullableInt(),
                           jToken["max"].ToNullableInt(),
                           SystemFileSizeUnits.Bytes,
                           SystemFileSizeUnits.Bytes,
                           jsonObject["message"]?.ToString()));
            }

            if (jsonObject.TryGetValue("assetImageDimensions", out jToken))
            {
                int?minWidth  = null;
                int?maxWidth  = null;
                int?minHeight = null;
                int?maxHeight = null;
                if (jToken["width"] != null)
                {
                    var width = jToken["width"];
                    minWidth = width["min"].ToNullableInt();
                    maxWidth = width["max"].ToNullableInt();
                }
                if (jToken["height"] != null)
                {
                    var height = jToken["height"];
                    minHeight = height["min"].ToNullableInt();
                    maxHeight = height["max"].ToNullableInt();
                }
                return(new ImageSizeValidator(minWidth, maxWidth, minHeight, maxHeight, jsonObject["message"]?.ToString()));
            }

            if (jsonObject.TryGetValue("nodes", out jToken))
            {
                var validator = new NodesValidator();

                if (jToken["entry-hyperlink"] != null)
                {
                    validator.EntryHyperlink = jToken["entry-hyperlink"].ToObject <IEnumerable <IFieldValidator> >(serializer);
                }
                if (jToken["embedded-entry-block"] != null)
                {
                    validator.EmbeddedEntryBlock = jToken["embedded-entry-block"].ToObject <IEnumerable <IFieldValidator> >(serializer);
                }
                if (jToken["embedded-entry-inline"] != null)
                {
                    validator.EmbeddedEntryInline = jToken["embedded-entry-inline"].ToObject <IEnumerable <IFieldValidator> >(serializer);
                }

                return(validator);
            }

            if (jsonObject.TryGetValue("enabledMarks", out jToken))
            {
                var types = jToken.Values <string>();
                return(new EnabledMarksValidator(types.Select(c => (EnabledMarkRestrictions)Enum.Parse(typeof(EnabledMarkRestrictions), c, true)),
                                                 jsonObject["message"]?.ToString()));
            }


            if (jsonObject.TryGetValue("enabledNodeTypes", out jToken))
            {
                var types = jToken.Values <string>();
                return(new EnabledNodeTypesValidator(types.Select(c => EnabledNodeTypesValidator.toEnum(c)),
                                                     jsonObject["message"]?.ToString()));
            }

            return(Activator.CreateInstance(objectType));
        }
Пример #56
0
 public static T Parse <T>(char input)
 {
     return((T)Enum.Parse(typeof(T), input.ToString(), true));
 }
 private static AddExtendedQueryTagsInputTableTypeV1Row ToAddExtendedQueryTagsInputTableTypeV1Row(AddExtendedQueryTagEntry entry)
 {
     return(new AddExtendedQueryTagsInputTableTypeV1Row(entry.Path, entry.VR, entry.PrivateCreator, (byte)((QueryTagLevel)Enum.Parse(typeof(QueryTagLevel), entry.Level, true))));
 }
Пример #58
0
        // This method creates a specific call to the above method, requesting the
        // Description MetaData attribute.
        public static string ToName(this Enum value)
        {
            var attribute = value.GetAttribute <DescriptionAttribute>();

            return(attribute == null?value.ToString() : attribute.Description);
        }
Пример #59
0
 /// <summary>
 /// 将指定的 Object 的值转换为指定枚举类型的值.
 /// </summary>
 /// <param name="value">实现 IConvertible 接口的 Object,或者为 null.</param>
 /// <param name="targetType"></param>
 /// <returns></returns>
 private static object GetEnum(object value, Type targetType)
 {
     return(Enum.Parse(targetType, value.ToString()));
 }
Пример #60
0
        private static IEnumerable <Guid> ReceiverIds <TActivity>(TActivity activity, Enum notificationType)
            where TActivity : IIntranetActivity, IHaveOwner
        {
            switch (notificationType)
            {
            case Enum type when type.In(BeforeStart, EventHidden, EventUpdated) && activity is ISubscribable subscribable:
                return(GetNotifiedSubscribers(subscribable));

            case ActivityLikeAdded:
                return(OwnerId(activity));

            default:
                throw new InvalidOperationException();
            }
        }