public override void CompileTimeInitialize(Type target, AspectInfo aspectInfo) { Dictionary <int, PropertyInfo> indexes = new Dictionary <int, PropertyInfo>(); foreach (PropertyInfo propertyInfo in target.GetProperties()) { TlvMemberAttribute memberAttr = propertyInfo.GetCustomAttributes() .Where(x => x is TlvMemberAttribute) .Cast <TlvMemberAttribute>() .SingleOrDefault(); if (memberAttr == null) { Message.Write(MessageLocation.Of(propertyInfo), SeverityType.Error, "USR001", "Property {0} should be marked by TlvMemberAttribute.", propertyInfo); continue; } if (indexes.ContainsKey(memberAttr.Index)) { Message.Write(MessageLocation.Of(propertyInfo), SeverityType.Error, "USR002", "Property {0} marked by TlvMemberAttribute uses Index {1}, which is already used by property {2}.", propertyInfo, memberAttr.Index, indexes[memberAttr.Index]); continue; } indexes[memberAttr.Index] = propertyInfo; } }
/// <summary> /// Compile time validation. /// </summary> /// <param name="type">The type.</param> /// <returns>Returns 'false' if validation fails.</returns> public override bool CompileTimeValidate(Type type) { var error = true; var processedNames = new List <string>(); var methods = type.GetMethods(); var selectedMethods = methods.Where( x => !x.IsVirtual && string.Compare(x.Name, "GetType", true) != 0); //virtual flag cannot be directly checked on properties hence we use methods to obtain the same. //This code below takes care of both properties and methods. foreach (var method in selectedMethods) { var processedMethodName = method.Name.Replace("get_", string.Empty).Replace("set_", string.Empty); if (!processedNames.Contains(processedMethodName)) { processedNames.Add(processedMethodName); Message.Write(MessageLocation.Of(method), SeverityType.Error, "E001", string.Format("{0}.{1} is not virtual", type.Name, processedMethodName)); error = false; } } //Checks if there is a constructor with zero parameter. if (type.GetConstructors().Where(x => x.GetParameters().Count() == 0).Count() != 1) { Message.Write(MessageLocation.Of(type), SeverityType.Error, "E002", string.Format("{0} needs a zero parameter constructor", type.Name)); error = false; } return(error); }
private void ValidateGetTypeExpression(MethodInfo validatedMethod, IExpression expression) { IMethodCallExpression callExpression = expression as IMethodCallExpression; if (callExpression == null) { return; } if (callExpression.Method != typeof(object).GetMethod("GetType")) { return; } IExpression instanceExpression = callExpression.Instance; Type type = instanceExpression.ReturnType; if (type == null) { return; } if (!type.GetCustomAttributes(typeof(FileExtensionAttribute)).Any()) { MessageSource.MessageSink.Write( new Message( MessageLocation.Of(this.userMethod), SeverityType.Error, "MYERR1", String.Format("Calling method {0} on type {1} is not allowed.", validatedMethod, type), null, null, null ) ); } }
public void DisplayMessage(string message, MessageLocation location) { if (TextBoxDictionary == null) { throw new GruffException("Textbox dictionary was not created"); } if (TextBoxDictionary.Count != Enum.GetNames(typeof(MessageLocation)).Length) { throw new GruffException("Message Location enum and textbox dictionary do not match"); } Text targetTextBox; bool fetchTextboxSuccess = TextBoxDictionary.TryGetValue(location, out targetTextBox); if (!fetchTextboxSuccess) { throw new GruffException("Message location not found in dictionary"); } var targetTextController = targetTextBox.GetComponent <TextController>(); if (message != null) { targetTextController.SetText(message); } }
public override bool CompileTimeValidate(LocationInfo locationInfo) { if (!typeof(IModelObject).IsAssignableFrom(locationInfo.DeclaringType)) { Message.Write(MessageLocation.Of(locationInfo.PropertyInfo), SeverityType.Error, "ModelErrorCode", "ModelObjectChangedAttribute was applied to a class not implementing IModelObject: " + locationInfo.DeclaringType.FullName); } if (locationInfo.LocationKind != LocationKind.Property) { return(false); } if (!locationInfo.PropertyInfo.CanRead || !locationInfo.PropertyInfo.CanWrite) { return(false); } if (locationInfo.LocationKind == LocationKind.Property && locationInfo.PropertyInfo.PropertyType.Equals(typeof(ModelContainer))) // dont sync modelcontainers! { return(false); } Console.WriteLine("Yello!"); Message.Write(MessageLocation.Of(locationInfo.PropertyInfo), SeverityType.Info, "ModelErrorCode", "Added ModelContainer changelogging to:: " + locationInfo.DeclaringType.FullName); return(base.CompileTimeValidate(locationInfo)); }
public override bool CompileTimeValidate(Type type) { var isStatic = type.IsAbstract && type.IsSealed; var hasStaticProperties = type .GetProperties(BindingFlags.Static | BindingFlags.Public) .Any(); var methodInfos = type.GetMethods(BindingFlags.Static | BindingFlags.Public); var extensionMethods = methodInfos.Where(m => m.GetCustomAttribute <ExtensionAttribute>() != null) .Select(m => m) .ToList(); var hasStaticMethods = methodInfos.Except(extensionMethods).Any(); if (isStatic && extensionMethods.Any() && !hasStaticMethods && !hasStaticProperties) { return(false); } if (isStatic || hasStaticProperties || hasStaticMethods) { var location = MessageLocation.Of(type); var msg = "Looks like you are increasing chaos on a project using static modificator"; Message.Write(location , SeverityType.Error , "f001" , msg); return(false); } return(base.CompileTimeValidate(type)); }
public override void CompileTimeInitialize(MethodBase method, AspectInfo aspectInfo) { if (null == typeof(Cursors).GetProperty(this.cursorName, BindingFlags.Public | BindingFlags.Static)) { MessageSource.MessageSink.Write(new Message(MessageLocation.Of(method), SeverityType.Error, "USR001", "Invalid cursor name", null, "MyComponent", null)); } }
public async void DoAction(object sender, CrmEvent e) { if (e.Entity != "contacts" || String.IsNullOrEmpty(e.EntityId) || e.ContactType != "contact") { return; } IEnumerable <ContactDTO> amoUser = null; Contact contact = null; try { amoUser = await amocrm.Contacts.Get().SetParam(prm => prm.Id = int.Parse(e.EntityId)).Execute(); contact = amoUser.Adapt <IEnumerable <Contact> >(mapper).FirstOrDefault(); logger.Error("Получен контакт - {Name}, {Id}", amoUser.FirstOrDefault().Name, amoUser.FirstOrDefault().Id); } catch (NullReferenceException ex) { logger.Error(ex, "Ошибка в маппинге {@Contacts}, {@AmoUser}", contact, amoUser); } catch (Exception ex) { logger.Error(ex, "Запрос пользователя amoCRM окончился неудачей. Событие - {@Event}, {@AmoUser}, {@Contacts}", e, amoUser, contact); } if (contact != null) { foreach (var phone in contact.Phones()) { if (!(phone.Value == phone.Value.LeaveJustDigits())) { contact.Phones(phone.Key, phone.Value.LeaveJustDigits()); } } } try { if (contact.ChangeValueDelegate != null) { var dto = contact.GetChanges().Adapt <ContactDTO>(mapper); await amocrm.Contacts.Update(dto); logger.Error("Сохранены очищенные телефоны для пользователя {Name}, {Id}", contact.Name, contact.Id); } } catch (Exception ex) { var info = new MessageLocation(this) { Metod = MethodBase.GetCurrentMethod().Name }; logger.Error("Ошибка, {@Message}, {@Location}", ex.Message, info); } }
/// <summary> /// Raise the error returned by Aspects CompileTimeValidate method. /// </summary> /// <param name="aspectType"> The Aspect Class Type that raise the error. </param> /// <param name="verifiedMethod"> The class Type given to the CompileTimeValidate method. </param> /// <param name="message"> The message to give explaining the error. </param> /// <returns> always false as an error has occurred. </returns> public static bool RaiseError( Type aspectType, MethodBase verifiedMethod, string message) { message = string.Concat(aspectType.Name, " : \r\n\r\n ", message); Message.Write(MessageLocation.Of(verifiedMethod), SeverityType.Error, aspectType.Name, string.Format(message, verifiedMethod.Name)); return(false); }
public MessageUser(string title, string mesage, string description, MessageLocation trayLocation) { InitializeComponent(); TrayLocation = trayLocation; TrayTitle = title; TrayMesage = mesage; TrayImageDescription = description; Show(true); }
public override bool CompileTimeValidate(LocationInfo locationInfo) { if (!locationInfo.PropertyInfo.CanRead || !locationInfo.PropertyInfo.CanWrite) { return(false); } Message.Write(MessageLocation.Of(locationInfo.PropertyInfo), SeverityType.Info, "ModelErrorCode", "Added Change tracking changelogging to: " + locationInfo.DeclaringType.FullName); return(base.CompileTimeValidate(locationInfo)); }
public override bool CompileTimeValidate(LocationInfo locationInfo) { base.CompileTimeValidate(locationInfo); if (locationInfo.LocationKind != LocationKind.Property || !IsAccepted(locationInfo)) { return(false); } Message.Write(MessageLocation.Of(locationInfo), SeverityType.ImportantInfo, "Info", $"'LazyDataAccessAttribute' applied on {locationInfo.DeclaringType.FullName}.{locationInfo.PropertyInfo.Name}"); return(true); }
public MessageUser(string title, string mesage, string description, MessageLocation trayLocation, MessageBtns buttons, int timeToClose) { InitializeComponent(); TrayLocation = trayLocation; TrayTitle = title; TrayMesage = mesage; TrayImageDescription = description; Choosebtns(buttons); AutoCloseTimeOut = timeToClose; Show(true); }
private bool SetLocationTemplate(MessageViewModel message, MessageLocation location, string title) { Visibility = Visibility.Visible; HideThumbnail(); SetTitle(GetFromLabel(message, title)); SetService(location.LivePeriod > 0 ? Strings.Resources.AttachLiveLocation : Strings.Resources.AttachLocation); SetMessage(string.Empty); return(true); }
public override bool CompileTimeValidate(_Assembly assembly) { IEnumerable <object> myAttributes = typeof(Program).GetCustomAttributes(inherit: true) .Where(atr => atr.GetType() == typeof(MyAttribute)); if (!myAttributes.Any()) { Message.Write(MessageLocation.Of(typeof(Program)), SeverityType.Error, "DESIGN1", "You haven't marked {0} with {1}", typeof(Program), typeof(MyAttribute)); } return(base.CompileTimeValidate(assembly)); }
public static void ValidateHasRaiseMethod(LocationInfo locationInfo) { var method = GetRaiseMethod(locationInfo.DeclaringType); if (method == null || method.ReturnType != typeof(void) || !method.GetParameters().Select(parameter => parameter.ParameterType).SequenceEqual(new[] { typeof(string) })) { var message = $"{locationInfo.DeclaringType.Name} should contains a method annotated with " + $"{typeof(RaisesNotifyPropertyChangedAttribute).Name} that has a signature like {typeof(Action<string>).Name} " + $"if it uses the {typeof(SmartNotifyPropertyChangedAttribute).Name} attribute on a property."; MessageSource.MessageSink.Write(new Message(MessageLocation.Of(locationInfo.PropertyInfo), SeverityType.Error, "AF0001", message, "", locationInfo.DeclaringType.Assembly.ToString(), null)); } }
private bool SetLocationTemplate(MessageViewModel message, MessageLocation location, string title) { Visibility = Visibility.Visible; if (ThumbRoot != null) { ThumbRoot.Visibility = Visibility.Collapsed; } TitleLabel.Text = GetFromLabel(message, title); ServiceLabel.Text = location.LivePeriod > 0 ? Strings.Resources.AttachLiveLocation : Strings.Resources.AttachLocation; MessageLabel.Text = string.Empty; return(true); }
private void VerifySerializable(TypeDefDeclaration type, MessageLocation location) { if (!IsSerializable(type)) { // This does not work properly on .NET Core. // PostSharp has difficulty understanding that some classes in .NET Core are serializable. // In addition, some fields are not meant to be serialized so it's better not to emit a warning for those // as well. // Message.Write(location, SeverityType.Warning, "DSER001", // "A type (" + type.Name + // ") is not serializable, but it's not in the same assembly so I cannot modify it."); } }
public override bool CompileTimeValidate(MethodBase method) { if (IsIgnorable) { ParameterInfo lastParam = method.GetParameters().Last(); if (lastParam.ParameterType != typeof(bool)) { Message.Write(MessageLocation.Of(method), SeverityType.Error, "CUSTOM03", String.Format("Method '{0}' must have the last parameter of bool type if IsIgnorable flag is set", method.Name)); return(false); } } return(base.CompileTimeValidate(method)); }
private void IdentifyAndMakeSerializableRecursively(ITypeSignature type, MessageLocation location) { switch (type.TypeSignatureElementKind) { case TypeSignatureElementKind.Intrinsic: // This works automatically for most, but: // Consider an error for object, IntPtr, but also consider that those fields may be marked as [NonSerialized]. // In the future, we might want to exclude such fields. break; case TypeSignatureElementKind.TypeDef: TypeDefDeclaration typeDef = (TypeDefDeclaration)type; if (typeDef.DeclaringAssembly == this.Project.Module.DeclaringAssembly) { MakeSerializableRecursively(typeDef); } else { VerifySerializable(typeDef, location); } break; case TypeSignatureElementKind.TypeRef: IdentifyAndMakeSerializableRecursively(type.GetTypeDefinition(), location); break; case TypeSignatureElementKind.GenericInstance: GenericTypeInstanceTypeSignature genericInstanceSignature = type as GenericTypeInstanceTypeSignature; IdentifyAndMakeSerializableRecursively(genericInstanceSignature.ElementType, location); foreach (ITypeSignature argument in genericInstanceSignature.GenericArguments) { IdentifyAndMakeSerializableRecursively(argument, location); } break; case TypeSignatureElementKind.Array: ArrayTypeSignature arraySignature = type as ArrayTypeSignature; IdentifyAndMakeSerializableRecursively(arraySignature.ElementType, location); break; default: // Other possible signature types can be ignored: // Pointers: they cannot be serialized // Custom modifiers: they should not be used on fields. break; } }
public void ToDelimitedString_WithAllProperties_ReturnsCorrectlySequencedFields() { IType hl7Type = new MessageLocation { SegmentId = "1", SegmentSequence = 2, FieldPosition = 3, FieldRepetition = 4, ComponentNumber = 5, SubComponentNumber = 6 }; string expected = "1^2^3^4^5^6"; string actual = hl7Type.ToDelimitedString(); Assert.Equal(expected, actual); }
public async void DoAction(object sender, CrmEvent e) { if (e.Entity != "contacts" || String.IsNullOrEmpty(e.EntityId) || e.ContactType != "contact") { return; } try { var amoUser = amoManager.Contacts.Get().SetParam(prm => prm.Id = int.Parse(e.EntityId)) .Execute() .Result .FirstOrDefault(); var contact = amoUser.Adapt <Contact>(mapper); var hasGuid = contact.Guid(); if (!String.IsNullOrEmpty(hasGuid)) { return; } var guid = await new LookForContact(database, logger).Find(contact); if (!String.IsNullOrEmpty(guid)) { contact.Guid(guid); await amoManager.Contacts.Update( contact.GetChanges().Adapt <ContactDTO>(mapper) ); logger.Information("Обновление Guid - {Guid}, для пользователя Id - {User}", guid, amoUser.Id); } } catch (Exception ex) { var info = new MessageLocation(this) { Metod = MethodBase.GetCurrentMethod().Name }; logger.Error("Ошибка, {@Message}, По адресу - {@Location}", ex.Message, info); } }
/// <summary>Method executed at build time.</summary> public override void CompileTimeInitialize(MethodBase method, AspectInfo aspectInfo) { this.instanceName = method.DeclaringType.FullName + "." + method.Name; if (showWarningOnlyOnce) { return; } showWarningOnlyOnce = true; Message.Write( MessageLocation.Of(method), SeverityType.Warning, "StackOverflowDetectionAspect", "Getting a StackTrace is very expensive. This aspect should only be used to debug a known issue and should be removed after the issue is located, Method: {0} and other!", method.DeclaringType.Name); }
private void Validate(ICodeReference codeReference) { string usingNamespace = GetNamespace(codeReference.ReferencingDeclaration); string usedNamespace = GetNamespace(codeReference.ReferencedDeclaration); if (usingNamespace.Equals(usedNamespace, StringComparison.Ordinal)) { return; } if (this.namespaces.Any( x => usingNamespace.Equals(x, StringComparison.Ordinal) || (usingNamespace.StartsWith(x, StringComparison.Ordinal) && usingNamespace[x.Length] == '.'))) { return; } object[] arguments = new object[] { /*...*/ }; Message.Write(MessageLocation.Of(codeReference.ReferencingDeclaration), SeverityType.Warning, "ErrorCode", "Access error message.", arguments); }
public void FromDelimitedString_WithAllProperties_ReturnsCorrectlyInitializedFields() { IType expected = new MessageLocation { SegmentId = "1", SegmentSequence = 2, FieldPosition = 3, FieldRepetition = 4, ComponentNumber = 5, SubComponentNumber = 6 }; IType actual = new MessageLocation(); actual.FromDelimitedString("1^2^3^4^5^6"); expected.Should().BeEquivalentTo(actual); }
private void setInfo(GameObject ArObject, double lat, double longi) { // TODO: Guardar nombre, id, latitud, longitud MessageLocation messLoc = ArObject.GetComponent <MessageLocation>(); messLoc.Lat = lat; messLoc.Long = longi; messLoc.Message = "Escribir descripcion..."; messLoc.latitud.text = messLoc.Lat.ToString(); messLoc.longitud.text = messLoc.Long.ToString(); messLoc.setDescription(messLoc.Message); // Agregar a la lista ARObject baseClassAR = (ARObject)messLoc; addToList(messLoc); }
public override bool CompileTimeValidate(Type type) { var notAllowed = type.GetInterfaces() .Except(types) .Select(i => i.Name) .ToList(); if (notAllowed.Any()) { var messageLocation = MessageLocation.Of(type.GetConstructors().First()); var messageText = $"There should be only IWeapon/IShield implementation in the {type.Name} class (was found {string.Join(",", notAllowed)})"; var message = new Message(messageLocation, SeverityType.Error, "f001", messageText, "", "file", null); Message.Write(message); return(false); } return(base.CompileTimeValidate(type)); }
public override bool CompileTimeValidate(MethodBase method) { if (!typeof(A.Core.Interface.IService).IsAssignableFrom(method.DeclaringType)) { Message.Write(MessageLocation.Of((MemberInfo)method), SeverityType.Error, "998", string.Format("Declaring class {0} has to implement IService interface", _className)); } var methodInfo = method as MethodInfo; if (methodInfo != null) { var returnType = methodInfo.ReturnType; if (IsDisallowedCacheReturnType(returnType)) { Message.Write(MessageLocation.Of(method), SeverityType.Error, "998", string.Format("Methods with return type {0} can't be cached!", returnType.Name)); return(false); } } return(true); }
private async Task <string> GetGuid(string phone, string email) { flGUIDs query = null; try { query = await database.Persons.GetGuidByPhoneOrEmail(phone, email); } catch (Exception ex) { var info = new MessageLocation(this) { Metod = MethodBase.GetCurrentMethod().Name }; logger.Error("Ошибка, {@Message}, По адресу - {@Location}", ex.Message, info); } return(query?.GUID); }
static IEnumerable <MessageLocation> SplitToMessages(string sample, string headerRe) { Regex re; try { re = new Regex(headerRe, headerReOptions); } catch { yield break; } int pos = 0; MessageLocation loc = new MessageLocation(); for (;;) { Match m = re.Match(sample, pos); if (!m.Success || m.Length == 0) { break; } if (loc.HeaderLength != 0) { loc.TotalLength = m.Index - loc.Begin; yield return(loc); } loc.Begin = m.Index; loc.HeaderLength = m.Length; pos = m.Index + m.Length; } if (loc.HeaderLength != 0) { loc.TotalLength = sample.Length - loc.Begin; yield return(loc); } }
public static void NotySuccessModal(this ControllerBase controller,string message, bool isSticky = false,MessageLocation location=MessageLocation.center) { var notyMessage = new NotyMessage { Type = AlertType.success, IsSticky = isSticky, Message = message, Location = location, CloseAnimation = AnimationTypes.bounceIn, OpenAnimation = AnimationTypes.bounceOut, IsModal = true, CloseWith = MessageCloseType.click }; controller.AddNotyAlert(notyMessage); }