private void CheckAllMessages(ContractFailureKind kind, string messageStart, Action <string, Exception, string, ContractFailureKind, Func <string> > fnAssert) { foreach (Exception ex in new [] { null, new ArgumentNullException() }) { fnAssert(messageStart + ".", ex, null, kind, () => { return(ContractHelper.RaiseContractFailedEvent(kind, null, null, ex)); }); fnAssert(messageStart + ". Message", ex, null, kind, () => { return(ContractHelper.RaiseContractFailedEvent(kind, "Message", null, ex)); }); fnAssert(messageStart + ": Condition", ex, "Condition", kind, () => { return(ContractHelper.RaiseContractFailedEvent(kind, null, "Condition", ex)); }); fnAssert(messageStart + ": Condition Message", ex, "Condition", kind, () => { return(ContractHelper.RaiseContractFailedEvent(kind, "Message", "Condition", ex)); }); } }
public static IEnumerable <string> CreateModelFromInterface(Type type, Action <Type, List <string> > createAttributes = null, Action <Type, PropertyInfo, List <string> > createPropertyAttributes = null) { type.CheckArgument(nameof(type)); var result = new List <string>(); var entityName = CreateEntityNameFromInterface(type); var properties = ContractHelper.GetAllProperties(type); createAttributes?.Invoke(type, result); result.Add($"public partial class {entityName} : {type.FullName}"); result.Add("{"); result.AddRange(CreatePartialStaticConstrutor(entityName)); result.AddRange(CreatePartialConstrutor("public", entityName)); foreach (var item in ContractHelper.FilterPropertiesForGeneration(properties)) { createPropertyAttributes?.Invoke(type, item, result); result.AddRange(CreateProperty(item)); } result.AddRange(CreateCopyProperties(type)); result.AddRange(CreateFactoryMethods(type, false)); result.Add("}"); return(result); }
private Contracts.IGeneratedItem CreateEntityFromContract(Type type, Common.ItemType itemType) { type.CheckArgument(nameof(type)); var baseItfc = GetPersistenceBaseContract(type); var contractHelper = new ContractHelper(type); var result = new Models.GeneratedItem(Common.UnitType.Logic, itemType) { FullName = CreateEntityFullNameFromInterface(type), FileExtension = StaticLiterals.CSharpFileExtension, }; result.SubFilePath = $"{result.FullName}{result.FileExtension}"; CreateEntityAttributes(type, result.Source); result.Add($"partial class {contractHelper.EntityName} : {type.FullName}"); result.Add("{"); result.AddRange(CreatePartialStaticConstrutor(contractHelper.EntityName)); result.AddRange(CreatePartialConstrutor("public", contractHelper.EntityName)); foreach (var item in ContractHelper.GetEntityProperties(type).Where(p => CanCreateProperty(type, p.Name))) { var codeLines = new List <string>(CreateProperty(item)); AfterCreateProperty(type, item, codeLines); result.AddRange(codeLines); } result.AddRange(CreateCopyProperties(type)); result.AddRange(CreateEquals(type)); result.AddRange(CreateGetHashCode(type)); result.AddRange(CreateFactoryMethods(type, baseItfc != null)); result.Add("}"); result.EnvelopeWithANamespace(CreateNameSpace(type), "using System;"); result.FormatCSharpCode(); return(result); }
/// <summary> /// Validation logic that will determine if this command should be enabled for execution. /// </summary> /// <param name="result">The target model data that will be used to determine if this command should be enabled.</param> /// <returns>Boolean flag that will tell code factory to enable this command or disable it.</returns> public override async Task <bool> EnableCommandAsync(VsCSharpSource result) { //Result that determines if the the command is enabled and visible in the context menu for execution. bool isEnabled = false; try { if (!result.IsLoaded) { return(false); } if (!result.SourceCode.Classes.Any()) { return(false); } isEnabled = result.SourceCode.Classes.Any(c => ContractHelper.GetSubscriptions(c) != null); } catch (Exception unhandledError) { _logger.Error($"The following unhandled error occured while checking if the solution explorer C# document command {commandTitle} is enabled. ", unhandledError); isEnabled = false; } return(isEnabled); }
public static IEnumerable <string> CreateTypeImports(Type type) { type.CheckArgument(nameof(type)); var result = new List <string>(); var properties = ContractHelper.GetAllProperties(type); var entityName = CreateEntityNameFromInterface(type); foreach (var propertyInfo in properties) { if (propertyInfo.PropertyType.IsEnum) { var typeName = $"{propertyInfo.PropertyType.Name}"; if (typeName.Equals(entityName) == false) { var subPath = GeneratorObject.CreateSubPathFromType(propertyInfo.PropertyType).ToLower(); result.Add(CreateImport(typeName, subPath)); } } else if (propertyInfo.PropertyType.IsGenericType) { Type subType = propertyInfo.PropertyType.GetGenericArguments().First(); if (subType.IsInterface) { var typeName = subType.Name[1..];
public static MethodContract /*?*/ ExtractContracts(IContractAwareHost contractAwareHost, PdbReader /*?*/ pdbReader, ContractExtractor extractor, ISourceMethodBody methodBody) { var definingUnit = TypeHelper.GetDefiningUnit(methodBody.MethodDefinition.ContainingType.ResolvedType); var methodIsInReferenceAssembly = ContractHelper.IsContractReferenceAssembly(contractAwareHost, definingUnit); var oldAndResultExtractor = new OldAndResultExtractor(contractAwareHost, methodBody, extractor.IsContractMethod); var localsInitializedWithFields = FindLocals.FindSetOfLocals(methodBody); var har = new HermansAlwaysRight(contractAwareHost, extractor, methodBody, methodIsInReferenceAssembly, oldAndResultExtractor, pdbReader); har.Rewrite(methodBody); if (har.extractor.currentMethodContract == null) { return(null); } // The decompiler will have introduced locals if there were any anonymous delegates in the contracts // Such locals are initialized with the fields of the iterator class. // The contract that comes back from here will have those fields replaced with whatever the iterator captured // (parameters, locals). So the locals in the contract need to be replaced with the iterator fields so that // next replacement will see the right thing (i.e., the fields) and replace them! Phew! var localReplacer = new LocalReplacer(contractAwareHost, localsInitializedWithFields); localReplacer.Rewrite(har.extractor.currentMethodContract); // also need to rewrite the remainder of the body localReplacer.Rewrite(methodBody); return(har.extractor.currentMethodContract); }
public override void TraverseChildren(IMethodDefinition methodDefinition) { if (AttributeHelper.Contains(methodDefinition.Attributes, this.host.PlatformType.SystemRuntimeCompilerServicesCompilerGeneratedAttribute)) { return; } if (ContractHelper.IsInvariantMethod(this.host, methodDefinition)) { return; } if (IsGetter(methodDefinition) || IsSetter(methodDefinition)) { return; } IMethodContract methodContract; if (this.showInherited) { methodContract = ContractHelper.GetMethodContractForIncludingInheritedContracts(this.host, methodDefinition); } else { methodContract = ContractHelper.GetMethodContractFor(this.host, methodDefinition); } Indent(); var methodSig = MemberHelper.GetMethodSignature(methodDefinition, NameFormattingOptions.Signature | NameFormattingOptions.ParameterName | NameFormattingOptions.ParameterModifiers); Console.WriteLine(methodSig); this.indentLevel++; PrintMethodContract(methodContract); this.indentLevel--; }
private Contracts.IGeneratedItem CreateModelFromContract(Type type, Common.UnitType unitType, Common.ItemType itemType) { type.CheckArgument(nameof(type)); var modelName = CreateModelNameFromInterface(type); var typeProperties = ContractHelper.GetAllProperties(type); var interfaces = GetInterfaces(type); var result = new Models.GeneratedItem(unitType, itemType) { FullName = CreateModelFullNameFromInterface(type), FileExtension = StaticLiterals.CSharpFileExtension, }; result.SubFilePath = $"{result.FullName}{result.FileExtension}"; CreateModelAttributes(type, result.Source); result.Add($"public partial class {modelName} : {type.FullName}"); result.Add("{"); result.AddRange(CreatePartialStaticConstrutor(modelName)); result.AddRange(CreatePartialConstrutor("public", modelName)); foreach (var item in ContractHelper.FilterPropertiesForGeneration(typeProperties)) { CreateModelPropertyAttributes(type, item, result.Source); result.AddRange(CreateProperty(item)); } result.AddRange(CreateCopyProperties(type)); foreach (var item in interfaces.Where(e => ContractHelper.HasCopyable(e))) { result.AddRange(CreateCopyProperties(item)); } result.AddRange(CreateFactoryMethods(type, false)); result.Add("}"); result.EnvelopeWithANamespace(CreateModelsNamespace(type), "using System;"); result.FormatCSharpCode(); return(result); }
public override void TraverseChildren(ITypeDefinition typeDefinition) { if (AttributeHelper.Contains(typeDefinition.Attributes, this.host.PlatformType.SystemRuntimeCompilerServicesCompilerGeneratedAttribute)) { return; } if (ContractHelper.IsContractClass(this.host, typeDefinition)) { return; } if (typeDefinition.IsEnum) { return; } Console.WriteLine(TypeHelper.GetTypeName(typeDefinition, NameFormattingOptions.TypeParameters)); this.indentLevel++; var unit = TypeHelper.GetDefiningUnit(typeDefinition); if (unit != null) { var ce = this.host.GetContractExtractor(unit.UnitIdentity); if (ce != null) { PrintTypeContract(ce.GetTypeContractFor(typeDefinition)); } } base.TraverseChildren(typeDefinition); this.indentLevel--; }
private void initConfig() { JToken cfg = config["TaskList"].Where(p => p["taskName"].ToString() == name() && p["taskNet"].ToString() == networkType()).ToArray()[0]["taskInfo"]; mongodbConnStr = Config.notifyDbConnInfo.connStr; mongodbDatabase = Config.notifyDbConnInfo.connDB; auctionStateCol = cfg["auctionStateCol"].ToString(); cgasBalanceCol = cfg["cgasBalanceCol"].ToString(); RegAddr = cfg["registerAddress"].ToString(); bonusAddr = cfg["bonusAddress"].ToString(); apiUrl = cfg["apiUrl"].ToString(); regscripthash = cfg["regscripthash"].ToString(); reconciliaRecord = cfg["reconciliaRecord"].ToString(); reconciliaHours = int.Parse(cfg["reconciliaHours"].ToString()); // 合约调用 ContractHelper.setApiUrl(apiUrl); ContractHelper.setRegHash(regscripthash); cfg = cfg["mailInfo"]; mkc = new MailKitClient(new MailConfig { mailFrom = cfg["mailFrom"].ToString(), mailPwd = cfg["mailPwd"].ToString(), smtpHost = cfg["smtpHost"].ToString(), smtpPort = int.Parse(cfg["smtpPort"].ToString()), subject = cfg["subject"].ToString(), body = cfg["body"].ToString(), listener = cfg["listener"].ToString(), smtpEnableSsl = cfg["useSsl"].ToString() == "1" }); initSuccFlag = true; }
private static void AssertMustUseRewriter(ContractFailureKind kind, string contractKind) { if (Contract._assertingMustUseRewriter) { Assert.Fail("Asserting that we must use the rewriter went reentrant.", "Didn't rewrite this mscorlib?"); } Contract._assertingMustUseRewriter = true; Assembly assembly1 = typeof(Contract).Assembly; StackTrace stackTrace = new StackTrace(); Assembly assembly2 = (Assembly)null; for (int index = 0; index < stackTrace.FrameCount; ++index) { Assembly assembly3 = stackTrace.GetFrame(index).GetMethod().DeclaringType.Assembly; if (assembly3 != assembly1) { assembly2 = assembly3; break; } } if (assembly2 == (Assembly)null) { assembly2 = assembly1; } string name = assembly2.GetName().Name; ContractHelper.TriggerFailure(kind, Environment.GetResourceString("MustUseCCRewrite", (object)contractKind, (object)name), (string)null, (string)null, (Exception)null); Contract._assertingMustUseRewriter = false; }
public void AddContract <Contract>(ChannelConfig config) { var cType = typeof(Contract); ContractHelper.ValidateContract(this.type.GetTypeInfo(), cType.GetTypeInfo()); this.ChannelConfigs.Add(cType.FullName, config); }
private static void AssertMustUseRewriter(ContractFailureKind kind, string contractKind) { if (Contract._assertingMustUseRewriter) { System.Diagnostics.Assert.Fail("Asserting that we must use the rewriter went reentrant.", "Didn't rewrite this mscorlib?"); } Contract._assertingMustUseRewriter = true; Assembly assembly = typeof(Contract).Assembly; StackTrace stackTrace = new StackTrace(); Assembly assembly2 = null; for (int i = 0; i < stackTrace.FrameCount; i++) { Assembly assembly3 = stackTrace.GetFrame(i).GetMethod().DeclaringType.Assembly; if (assembly3 != assembly) { assembly2 = assembly3; break; } } if (assembly2 == null) { assembly2 = assembly; } string name = assembly2.GetName().Name; ContractHelper.TriggerFailure(kind, Environment.GetResourceString("MustUseCCRewrite", new object[] { contractKind, name }), null, null, null); Contract._assertingMustUseRewriter = false; }
protected override async Task Execute(CancellationToken token) { log.LogInformation("Starting..."); if (!client.Connect()) { log.LogError("Connection failed"); return; } List <Task> tasks = new List <Task>(); for (int i = 0; i < 10; i++) { double strike = config.Strike + i * 10; var request = historicalDataManager() .Request( new MarketDataRequest( ContractHelper.GetOptionsContract(config.Symbol, strike, config.Expiry, OptionType.CALL), DateTime.UtcNow.Date, new Duration(5, DurationType.Months), BarSize.Hour, WhatToShow.MIDPOINT)); var task = serializer.Save($"{config.Symbol}_{config.Expiry}_{config.Type}_{strike}_historic.csv", request, token); tasks.Add(task); } await Task.WhenAll(tasks).ConfigureAwait(false); log.LogInformation("History request completed"); }
public static ulong Sub(this ulong a, ulong b) { ContractHelper.Assert(b <= a); ulong c = a - b; return(c); }
/// <summary> /// /// </summary> /// <param name="code"></param>S /// <param name="message"></param> /// <param name="httpStatusCode"></param> /// <param name="useServiceErrorMessage">If true, then the service error message will be used</param> public WebError(WebErrorCode code, string message, HttpStatusCode httpStatusCode, bool useServiceErrorMessage = false) { Code = code; Message = ContractHelper.RequiresNotNull(message); HttpStatusCode = httpStatusCode; UseServiceErrorMessage = useServiceErrorMessage; MessageFields = new ExpandoObject(); }
public static ulong Add(this ulong a, ulong b) { ulong c = a + b; ContractHelper.Assert(c >= a); return(c); }
/// <summary> /// Adds all the entries in a <see cref="IEnumerable{T}"/> to the target <see cref="ICollection{T}"/> /// </summary> /// <typeparam name="T"></typeparam> /// <param name="target"></param> /// <param name="source"></param> public static void AddRange <T>(this ICollection <T> target, IEnumerable <T> source) { ContractHelper.RequiresNotNull(target); foreach (var element in ContractHelper.RequiresNotNull(source)) { target.Add(element); } }
public static ulong Div(this ulong a, ulong b) { ContractHelper.Assert(b > 0); ulong c = a / b; return(c); }
public WebError(string message) { Code = WebErrorCode.BadRequest; Message = ContractHelper.RequiresNotNull(message); HttpStatusCode = HttpStatusCode.BadRequest; UseServiceErrorMessage = false; MessageFields = new ExpandoObject(); }
// [Ignore ("This causes NUnit crash on .NET 4.0")] public void TestTriggerFailure() { try { ContractHelper.TriggerFailure(ContractFailureKind.Assert, "Display", null, "Condition", null); Assert.Fail("TestTriggerFailure() failed to throw exception"); } catch (Exception ex) { Assert.AreEqual("Display", ex.Message, "TestTriggerFailure() wrong message"); } }
static void ReportFailure(ContractFailureKind kind, string userMessage, string conditionText, Exception innerException) { string msg = ContractHelper.RaiseContractFailedEvent(kind, userMessage, conditionText, innerException); // if msg is null, then it has been handled already, so don't do anything here if (msg != null) { ContractHelper.TriggerFailure(kind, msg, userMessage, conditionText, innerException); } }
private static void AssertMustUseRewriter(ContractFailureKind kind, string contractKind) { if (_assertingMustUseRewriter) { System.Diagnostics.Assert.Fail("Asserting that we must use the rewriter went reentrant.", "Didn't rewrite this mscorlib?"); } _assertingMustUseRewriter = true; ContractHelper.TriggerFailure(kind, "Must use the rewriter when using Contract." + contractKind, null, null, null); _assertingMustUseRewriter = false; }
public void TestTriggerFailure() { try { ContractHelper.TriggerFailure(ContractFailureKind.Assert, "Display", null, "Condition", null); Assert.Fail("TestTriggerFailure() failed to throw exception"); } catch (Exception ex) { Assert.IsInstanceOfType(typeof(NotImplementedException), ex, "TestTriggerFailure() wrong exception type"); //Assert.AreEqual ("Expression: Condition" + Environment.NewLine + "Description: Display", ex.Message, "TestTriggerFailure() wrong message"); } }
internal static void ReportFailure(ContractFailureKind kind, string msg, string conditionTxt, Exception inner) { string msg1 = ContractHelper.RaiseContractFailedEvent(kind, msg, conditionTxt, inner); if (msg1 == null) { return; } // ISSUE: reference to a compiler-generated method __ContractsRuntime.TriggerFailure(kind, msg1, msg, conditionTxt, inner); }
private static void ReportFailure(ContractFailureKind failureKind, string userMessage, string conditionText, Exception innerException) { if ((failureKind < ContractFailureKind.Precondition) || (failureKind > ContractFailureKind.Assume)) { throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", new object[] { failureKind }), "failureKind"); } string displayMessage = ContractHelper.RaiseContractFailedEvent(failureKind, userMessage, conditionText, innerException); if (displayMessage != null) { ContractHelper.TriggerFailure(failureKind, displayMessage, userMessage, conditionText, innerException); } }
protected override async Task Execute(CancellationToken token) { log.LogInformation("Starting..."); if (!client.Connect()) { log.LogError("Connection failed"); return; } var stream = realTimeBarsManager.Request(ContractHelper.GetStockContract(config.Symbol), WhatToShow.BID_ASK); await serializer.Save($"{config.Symbol}_realtime.csv", stream, token).ConfigureAwait(false); log.LogInformation("Realtime request completed"); }
/// <summary> /// Diese Methode erstellt den Programmcode fuer das Vergleichen der Eigenschaften. /// </summary> /// <param name="type">Die Schnittstellen-Typ Information.</param> /// <returns>Die Equals-Methode als Text.</returns> internal static IEnumerable <string> CreateEquals(Type type) { type.CheckArgument(nameof(type)); var result = new List <string>(); var counter = 0; var properties = ContractHelper.GetAllProperties(type); var filteredProperties = ContractHelper.FilterPropertiesForGeneration(properties); if (filteredProperties.Any()) { result.Add($"public override bool Equals(object obj)"); result.Add("{"); result.Add($"if (obj is not {type.FullName} instance)"); result.Add("{"); result.Add("return false;"); result.Add("}"); result.Add("return base.Equals(instance) && Equals(instance);"); result.Add("}"); result.Add(string.Empty); result.Add($"protected bool Equals({type.FullName} other)"); result.Add("{"); result.Add("if (other == null)"); result.Add("{"); result.Add("return false;"); result.Add("}"); foreach (var pi in filteredProperties) { if (pi.CanRead) { var codeLine = counter == 0 ? "return " : " && "; if (pi.PropertyType.IsValueType) { codeLine += $"{pi.Name} == other.{pi.Name}"; } else { codeLine += $"IsEqualsWith({pi.Name}, other.{pi.Name})"; } result.Add(codeLine); counter++; } } if (counter > 0) { result[^ 1] = $"{result[^1]};";
public Contracts.IGeneratedItem CreateContract(Type type, IEnumerable <Type> types) { type.CheckArgument(nameof(type)); var subPath = CreateSubPathFromType(type); var entityName = CreateEntityNameFromInterface(type); var fileName = $"{ConvertFileName(entityName)}.{CodeExtension}"; var properties = ContractHelper.GetAllProperties(type); var declarationTypeName = string.Empty; var result = new Models.GeneratedItem(Common.UnitType.AngularApp, Common.ItemType.TypeScriptContract) { FullName = CreateTypeScriptFullName(type), FileExtension = CodeExtension, }; result.SubFilePath = Path.Combine(ProjectContractsPath, subPath, fileName); StartCreateContract(type, result.Source); result.Add($"export interface {entityName}" + " {"); foreach (var item in properties) { if (declarationTypeName.Equals(item.DeclaringType.Name) == false) { declarationTypeName = item.DeclaringType.Name; result.Add($"/** {declarationTypeName} **/"); } result.AddRange(CreateTypeScriptProperty(item)); } result.AddRange(CreateContactToContractFromContracts(type, types)); result.Add("}"); result.FormatCSharpCode(); result.Source.Insert(result.Source.Count - 1, StaticLiterals.AngularCustomCodeBeginLabel); result.Source.Insert(result.Source.Count - 1, StaticLiterals.AngularCustomCodeEndLabel); var imports = new List <string>(); imports.AddRange(CreateTypeImports(type)); imports.AddRange(CreateContactToContractImports(type, types)); imports.Add(StaticLiterals.AngularCustomImportBeginLabel); imports.Add(StaticLiterals.AngularCustomImportEndLabel); InsertTypeImports(imports, result.Source); FinishCreateContract(type, result.Source); return(result); }
// todo: is ulong the stratis equivalent of uint256 or does that need to get ported as well? public static ulong Mul(this ulong a, ulong b) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return(0); } ulong c = a * b; ContractHelper.Assert(c / a == b); return(c); }
private void btnSyncFromExcel_Click(object sender, RibbonControlEventArgs e) { var inspector = _app.ActiveInspector(); var caption = inspector.Caption; var mail = inspector.CurrentItem as MailItem; //var session = inspector.Session; //var a = inspector.AttachmentSelection; if (mail == null) { return; } try { var contracts = ContractHelper.GetContracts(ContractHelper.GetContractFile()); var helper = new ContractHelper(this._app); helper.SyncContract(contracts); } finally { GC.Collect(); } MessageBox.Show(Resources.Messagebox_Info_SyncFinished); }