private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Analyze newAnalize = new Analyze { Name = "- НОВИЙ АНАЛІЗ -", AnalizeMeter = defaultMeter }; analizesList.Add(newAnalize); analizesTable.Refresh(); new Task(() => { using (DiabetContext dc = new DiabetContext()) { dc.Meters.Attach(newAnalize.AnalizeMeter); dc.Analyze.Add(newAnalize); dc.SaveChanges(); } }).Start(); }
private void analizesTable_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { if (formIsLoaded) { if (e.RowIndex > 0 && e.ColumnIndex == 1) { Analyze selectedItem = analizesTable.Rows[e.RowIndex].DataBoundItem as Analyze; MeterSelectForm mf = new MeterSelectForm(MeterType.Analize); mf.ShowDialog(); if (mf.SelectedMeter != null) { selectedItem.AnalizeMeter = mf.SelectedMeter; selectedItem.MeterId = mf.SelectedMeter.Id; analizesTable.Refresh(); } } } }
/// <summary> ///更新票据 /// </summary> /// <param name="forced">true:强制更新.false:按缓存是否到期来更新</param> public static void UpdateAccessToken(bool forced = false) { if (!forced && AccessToken_Ding.Begin.AddSeconds(ConstVars.CACHE_TIME) >= DateTime.Now) { //没有强制更新,并且没有超过缓存时间 return; } string CorpID = BP.Sys.SystemConfig.Ding_CorpID; string CorpSecret = BP.Sys.SystemConfig.Ding_CorpSecret; string TokenUrl = Urls.gettoken; string apiurl = TokenUrl + "?" + Keys.corpid + "=" + CorpID + "&" + Keys.corpsecret + "=" + CorpSecret; TokenResult tokenResult = Analyze.Get <TokenResult>(apiurl); if (tokenResult.ErrCode == ErrCodeEnum.OK) { AccessToken_Ding.Value = tokenResult.Access_token; AccessToken_Ding.Begin = DateTime.Now; } }
/// <summary> /// 发送消息 /// </summary> /// <param name="toUser">目标用户</param> /// <param name="toParty">目标部门.当toParty和toUser同时指定时,以toParty来发送。</param> /// <param name="content">消息文本</param> /// <returns></returns> private SendMessageResult SendTextMsg(string toUser, string toParty, string content, string token) { var txtmsg = new { touser = toUser, toparty = toParty, msgtype = "", //MsgType.text.ToString(), agentid = "", //ConfigHelper.FetchAgentID(), text = new { content = content } }; string apiurl = FormatApiUrlWithToken(Urls.message_send, token); string json = JsonConvert.SerializeObject(txtmsg); var result = Analyze.Post <SendMessageResult>(apiurl, json); return(result); }
public void Can_query_DateTime_column_in_select_without_any_format_parameter() { using var db = OpenDbConnection(); db.CreateTable <Analyze>(true); var obj = new Analyze { Id = 1, Date = DateTime.Now, Url = "http://www.google.com" }; db.Save(obj); var q = db.From <Analyze>().Select(i => i.Date); var sql = q.ToMergedParamsSelectStatement(); var val = db.Select <DateTime>(q).First(); Assert.That(obj.Date, Is.EqualTo(val).Within(TimeSpan.FromSeconds(1))); }
void InitIA() { Walk walk = new Walk(this.gameObject); TestItem testItem = new TestItem(this.gameObject); Analyze analyze = new Analyze(this.gameObject); p_myStateMachine = new StateMachine(this.gameObject, walk); //Walk Transitions List <Transitions> transitions = new List <Transitions>(); List <Conditions> conditions = new List <Conditions>(); ActionEnded condition = new ActionEnded(this.gameObject); conditions.Add(condition); Transitions transition = new Transitions(analyze, p_myStateMachine, conditions); transitions.Add(transition); walk.setTransitions(transitions); //Analyze Transitions transitions = new List <Transitions>(); conditions = new List <Conditions>(); SomethingBehind condition2 = new SomethingBehind(this.gameObject); conditions.Add(condition2); transition = new Transitions(testItem, p_myStateMachine, conditions); transitions.Add(transition); conditions = new List <Conditions>(); condition = new ActionEnded(this.gameObject); conditions.Add(condition); transition = new Transitions(walk, p_myStateMachine, conditions); transitions.Add(transition); analyze.setTransitions(transitions); //TestItem Transitions transitions = new List <Transitions>(); conditions = new List <Conditions>(); condition = new ActionEnded(this.gameObject); conditions.Add(condition); transition = new Transitions(walk, p_myStateMachine, conditions); transitions.Add(transition); testItem.setTransitions(transitions); }
public void ConstructorCallingSelf(DiagnosticAnalyzer analyzer) { var testCode = @" namespace RoslynSandbox { using System; public class Constructors : IDisposable { private IDisposable disposable; public Constructors() : this() { } public Constructors(IDisposable disposable) : this(IDisposable disposable) { this.disposable = disposable; } public Constructors(int i, IDisposable disposable) : this(disposable, i) { this.disposable = disposable; } public Constructors(IDisposable disposable, int i) : this(i, disposable) { this.disposable = disposable; } public void Dispose() { } } }"; var solution = CodeFactory.CreateSolution(testCode, CodeFactory.DefaultCompilationOptions(analyzer, AnalyzerAssert.SuppressedDiagnostics), AnalyzerAssert.MetadataReferences); AnalyzerAssert.NoDiagnostics(Analyze.GetDiagnostics(analyzer, solution)); }
public async Task InSetAndRaise(DiagnosticAnalyzer analyzer) { var viewModelBaseCode = @" namespace RoslynSandbox.Core { using System.ComponentModel; using System.Runtime.CompilerServices; internal abstract class ViewModelBase : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected bool TrySet<T>(ref T field, T newValue, [CallerMemberName] string propertyName = null) { return this.TrySet(ref field, newValue, propertyName); } protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }"; var testCode = @" namespace RoslynSandbox.Client { internal class Foo : RoslynSandbox.Core.ViewModelBase { private int value2; public int Value1 { get; set; } public int Value2 { get { return this.value2; } set { this.TrySet(ref this.value2, value); } } } }"; await Analyze.GetDiagnosticsAsync(analyzer, new[] { viewModelBaseCode, testCode }, AnalyzerAssert.MetadataReferences).ConfigureAwait(false); }
public static async Task InTrySet(DiagnosticAnalyzer analyzer) { var viewModelBase = @" namespace N.Core { using System.ComponentModel; using System.Runtime.CompilerServices; public abstract class ViewModelBase : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected bool TrySet<T>(ref T field, T value, [CallerMemberName] string propertyName = null) { return this.TrySet(ref field, value, propertyName); } protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }"; var code = @" namespace N.Client { public class Foo : N.Core.ViewModelBase { private int value2; public int Value1 { get; set; } public int Value2 { get { return this.value2; } set { this.TrySet(ref this.value2, value); } } } }"; await Analyze.GetDiagnosticsAsync(analyzer, new[] { viewModelBase, code }, MetadataReferences.FromAttributes()).ConfigureAwait(false); }
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e) { if (formIsLoaded) { if (e.RowIndex > 0 && e.ColumnIndex == 0) { Analyze selectedItem = analizesTable.Rows[e.RowIndex].DataBoundItem as Analyze; new Task(() => { using (DiabetContext dc = new DiabetContext()) { dc.Meters.Attach(selectedItem.AnalizeMeter); dc.Entry <Analyze>(selectedItem).State = EntityState.Modified; dc.SaveChanges(); } }).Start(); } } }
/// <summary> /// 获取token /// </summary> /// <param name="forced"></param> private static void UpdateAccessToken(bool forced = false) { //ConstVars.CACHE_TIME是缓存时间(常量,也可放到配置文件中),这样在有效期内则直接从缓存中获取票据,不需要再向服务器中获取。 if (!forced && AccessToken.Begin.AddSeconds(ConstVars.CACHE_TIME) >= DateTime.Now) { return; } string CorpID = AppSetting.corpid; string CorpSecret = AppSetting.corpsecret; string TokenUrl = Urls.gettoken; string apiurl = $"{TokenUrl}?{DDHelper . Keys . corpid}={CorpID}&{DDHelper . Keys . corpsecret}={CorpSecret}"; TokenResult tokenResult = Analyze.Get <TokenResult> (apiurl); if (tokenResult.ErrCode == ErrCodeEnum.OK) { AccessToken.Value = tokenResult.Access_token; AccessToken.Begin = DateTime.Now; } }
public static VisualData UploadActions(IFormFile imageFile) { //Create Image from File Image image = CreateImage(imageFile); //Upload DataStream to S3 using (MemoryStream memoryStream = new MemoryStream()) { image.Save(memoryStream, ImageFormat.Png); PDFIdentify.S3Upload.Upload.UploadDocument("pdfidentify", "112233.png", memoryStream, RegionEndpoint.USEast2); } //Run Textract Operations //Preserve tables bounding boxes & response.blocks TextractResponse response = Analyze.AnalyzeFile("112233.png", "https://*****:*****@"D:\OCR\PDFIdentifyC\Python\test.json"));*/ List <BoundingBoxIdentifier> bBoxIdens = new List <BoundingBoxIdentifier>(); foreach (var table in response.FilterType("TABLE")) { //Convert relative coordinate values to abs pixel values bBoxIdens.Add(CreateBBox(table, image)); } //Draw on Image var visualData = new VisualData { Colors = DrawBbOnImage(image, bBoxIdens), DataUrl = GetImageDataUrl(image), TextractResponse = response }; //Return Image DataURL & Options for Dropdown Menu return(visualData); }
public IActionResult OnPost() { if (!ModelState.IsValid) { PopulateSelectLists(); return(Page()); } var analysis = new Analyze(); analysis.CustomerId = AnalysisForm.CustomerId; analysis.AnalysisDate = DateTime.Now; _context.Analyze.Add(analysis); _context.SaveChanges(); Cst = _context.Customers .Include(x => x.Coupons) .Where(y => y.Id == AnalysisForm.CustomerId) .ToList(); CountOfCoupons = _context.Coupons .Where(y => y.CustomerId == AnalysisForm.CustomerId).Count(); TotalPriceOfCoupons = _context.Coupons .Where(y => y.CustomerId == AnalysisForm.CustomerId) .Sum(z => z.Price); MinPrice = _context.Coupons .Where(y => y.CustomerId == AnalysisForm.CustomerId) .Min(z => z.Price); MaxPrice = _context.Coupons .Where(y => y.CustomerId == AnalysisForm.CustomerId) .Max(z => z.Price); Cust = _context.Customers.ToList(); ViewData["CustomerId"] = new SelectList(Cust, "Id", "Name"); AnalysisCompleted = true; //return RedirectToPage("/Analysis", new { Id = AnalysisForm.CustomerId }); return(Page()); }
public void Can_store_and_retrieve_DateTime_Value() { using var db = OpenDbConnection(); db.CreateTable <Analyze>(true); var obj = new Analyze { Id = 1, Date = DateTime.Now, Url = "http://www.google.com" }; db.Save(obj); var id = (int)db.LastInsertId(); var target = db.SingleById <Analyze>(id); Assert.That(target, Is.Not.Null); Assert.That(target.Id, Is.EqualTo(id)); Assert.That(target.Date, Is.EqualTo(obj.Date).Within(TimeSpan.FromSeconds(1))); Assert.That(target.Url, Is.EqualTo(obj.Url)); }
/// <summary> /// Fix the solution by applying the code fix one fix at the time until it stops fixing the code. /// </summary> /// <returns>The fixed solution or the same instance if no fix.</returns> internal static async Task <Solution> ApplyAllFixableOneByOneAsync(Solution solution, DiagnosticAnalyzer analyzer, CodeFixProvider codeFix, string fixTitle, CancellationToken cancellationToken) { var fixable = await Analyze.GetFixableDiagnosticsAsync(solution, analyzer, codeFix).ConfigureAwait(false); var fixedSolution = solution; int count; do { count = fixable.Count; if (count == 0) { return(fixedSolution); } fixedSolution = await ApplyAsync(fixedSolution, codeFix, fixable[0], fixTitle, cancellationToken).ConfigureAwait(false); fixable = await Analyze.GetFixableDiagnosticsAsync(fixedSolution, analyzer, codeFix).ConfigureAwait(false); }while (fixable.Count < count); return(fixedSolution); }
public int getNouns(String command) { RepeatedField <Token> tokens = Analyze.AnalyzeSyntaxFromText(command); nouns = ""; foreach (var token in tokens) { if ((int)token.PartOfSpeech.Tag == 1 || (int)token.PartOfSpeech.Tag == 6 || (int)token.PartOfSpeech.Tag == 11) { nouns = nouns + token.Text.Content + " "; } } if (nouns == null) { return(-1); } else { return(0); } }
public static void Recursion() { var code = @" namespace RoslynSandbox { using System; public class C<T1, T2> where T1 : T2 where T2 : T1 { public static void Bar() { var type = typeof(C<,>).MakeGenericType(typeof(int), typeof(int)); } } }"; var solution = CodeFactory.CreateSolution(code, CodeFactory.DefaultCompilationOptions(Analyzer), RoslynAssert.MetadataReferences); RoslynAssert.NoDiagnostics(Analyze.GetDiagnostics(Analyzer, solution)); }
private static void InitiateSesion(Chat User, string token, Session.SessionType Type) { switch (Type) { case Session.SessionType.Pass: var ThisPoll = new Analyze(token, 1488).GetPoll(); Queue <Question> Questions = new Queue <Question>(); foreach (var question in ThisPoll.Questions) { Questions.Enqueue(question); } var ses = new Session(User, Questions, Session.SessionType.Pass, ThisPoll); SendQuestion(ses.Questions, ses.Chat); Sessions.Add(ses); break; case Session.SessionType.Create: Sessions.Add(new Session(User, null, Session.SessionType.Create, null)); break; } }
public int getVerbs(String command) { RepeatedField <Token> tokens = Analyze.AnalyzeSyntaxFromText(command); verbs = new ArrayList(); foreach (var token in tokens) { if ((int)token.PartOfSpeech.Tag == 11 || (int)token.PartOfSpeech.Tag == 1 || (int)token.PartOfSpeech.Tag == 2 || (int)token.PartOfSpeech.Tag == 3) { verbs.Add(token.Text.Content); } } if (verbs.Count == 0) { return(-1); } else { return(0); } }
public Analyze Analyze(string host, Publish publish, StartNew startNew, FromCache fromCache, int?maxHours, All all, IgnoreMismatch ignoreMismatch) { var analyzeModel = new Analyze(); // Checking host is valid before continuing if (!_urlValidation.IsValid(host)) { analyzeModel.HasErrorOccurred = true; analyzeModel.Errors.Add(new Error { message = "Host does not pass preflight validation. No Api call has been made." }); return(analyzeModel); } // Building request model var requestModel = _requestModelFactory.NewAnalyzeRequestModel(ApiUrl, "analyze", host, publish.ToString().ToLower(), startNew.ToString().ToLower(), fromCache.ToString().ToLower(), maxHours, all.ToString().ToLower(), ignoreMismatch.ToString().ToLower()); try { var webResponse = _apiProvider.MakeGetRequest(requestModel); analyzeModel = _responsePopulation.AnalyzeModel(webResponse, analyzeModel); } catch (Exception ex) { analyzeModel.HasErrorOccurred = true; analyzeModel.Errors.Add(new Error { message = ex.ToString() }); } // Checking if errors have occoured either from ethier api or wrapper if (analyzeModel.Errors.Count != 0 && !analyzeModel.HasErrorOccurred) { analyzeModel.HasErrorOccurred = true; } return(analyzeModel); }
public void Can_change_DateTime_precision() { using var db = OpenDbConnection(); #if MYSQLCONNECTOR if (MySqlConnectorDialect.Provider.GetConverter(typeof(DateTime)) is MySqlDateTimeConverterBase dateConverter) { dateConverter.Precision = 3; } #else if (MySqlDialect.Provider.GetConverter(typeof(DateTime)) is MySqlDateTimeConverterBase dateConverter) { dateConverter.Precision = 3; } #endif OrmLiteUtils.PrintSql(); db.CreateTable <Analyze>(true); var obj = new Analyze { Id = 1, Date = DateTime.Now, Url = "http://www.google.com" }; db.Save(obj); var id = (int)db.LastInsertId(); var target = db.SingleById <Analyze>(id); target.PrintDump(); var q = db.From <Analyze>() .Where(x => x.Date >= DateTime.Now.Date); var results = db.Select(q); Assert.That(results.Count, Is.EqualTo(1)); results.PrintDump(); results = db.SelectFmt <Analyze>("AnalyzeDate >= {0}", DateTime.Now.AddDays(-1)); results.PrintDump(); }
public void Can_store_and_retrieve_DateTime_Value() { using (var db = OpenDbConnection()) { db.CreateTable <Analyze>(true); var obj = new Analyze { Id = 1, Date = DateTime.Now, Url = "http://www.google.com" }; db.Save(obj); var target = db.SingleById <Analyze>(obj.Id); Assert.IsNotNull(target); Assert.AreEqual(obj.Id, target.Id); Assert.AreEqual(obj.Date.ToString("yyyy-MM-dd HH:mm:ss"), target.Date.ToString("yyyy-MM-dd HH:mm:ss")); Assert.AreEqual(obj.Url, target.Url); } }
public void WhenDupe() { this.directory.FindFile("Properties\\Resources.resx").ReplaceText( "<value>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua</value>", $"<value>Value</value>"); var sln = CodeFactory.CreateSolution(this.projectFile, MetadataReferences.FromAttributes()); var diagnostics = Analyze.GetDiagnostics(sln, Analyzer).Single(); Assert.AreEqual(4, diagnostics.Length); Assert.AreEqual("GULOC07", diagnostics[0].Id); StringAssert.EndsWith("Resources.Designer.cs", diagnostics[0].Location.SourceTree.FilePath); Assert.AreEqual("GULOC08", diagnostics[1].Id); StringAssert.EndsWith("Resources.Designer.cs", diagnostics[1].Location.SourceTree.FilePath); Assert.AreEqual("GULOC07", diagnostics[2].Id); StringAssert.EndsWith("Resources.Designer.cs", diagnostics[2].Location.SourceTree.FilePath); Assert.AreEqual("GULOC08", diagnostics[3].Id); StringAssert.EndsWith("Resources.Designer.cs", diagnostics[3].Location.SourceTree.FilePath); }
public void LazyEnumerable() { //var dt = DataTable.New.FromEnumerableLazy(TestEnumerable()); var dt = DataTable.New.FromEnumerableLazy(TestEnumerable()); // Test using the row object to lookup var y = from row in dt.Rows let i = int.Parse(row["value"]) select i; // Just taking the first element should succeed since we read lazily. // If we accidentally read the whole enumeration, we'd fail. Assert.Equal(1, y.First()); // Verify that we can read it a second time. var sample = Analyze.SampleTopN(dt, 1); AnalyzeTests.AssertEquals( @"value 1 ", sample); }
private void bSearch_Click(object sender, EventArgs e) { if (ThreadBusy) { return; } if (!ThreadBusy) { sw.Reset(); sw.Start(); Analyze._EventLogName = (string)cbCollectEventLogs.SelectedItem; Analyze._EventSource = (string)cbCollectEventSource.SelectedItem; Analyze._EventCategory = (string)cbCollectEventCategory.SelectedItem; if (chkbDate.Checked) { Analyze.SelectedDate = dateTimePicker1.Value; Analyze.SelectedStatusDate = true; } else { Analyze.SelectedStatusDate = false; } _analyze = new Analyze(); Thread th = new Thread(new ThreadStart(() => { Locks(true); ThreadBusy = true; _analyze.Work(); ThreadBusy = false; Locks(false); })); th.Start(); } }
static void Main(string[] args) { var resultFromParsing = Parser.Default.ParseArguments <CommandLineOptions>(args); if (resultFromParsing.Tag != ParserResultType.Parsed) { return; } var result = (Parsed <CommandLineOptions>)resultFromParsing; var unparsedConnectionString = result.Value.ConnectionString; var cosmosDbSqlConnectionInformation = CommandLineUtils.ParseCosmosDbConnectionString(unparsedConnectionString); var analyze = new Analyze(new CosmosDbDatabase( cosmosDbSqlConnectionInformation.accountEndpoint, cosmosDbSqlConnectionInformation.accountKey, cosmosDbSqlConnectionInformation.database, cosmosDbSqlConnectionInformation.collection )); var doit = new Do(analyze); }
/// <summary> /// 获取部门信息并保存 /// </summary> private void getDepartMentInfo( ) { string apiurl = FormatApiUrlWithToken(Urls.department_list); var result = Analyze.Get <DepartResultSet> (apiurl); List <DepartResultSet> list = XmlUtil.JsonStringToObj <DepartResultSet> (result.Json); if (list.Count > 0) { foreach (DepartResultSet depart in list) { if (depart.department.Count > 0) { //保存部门信息到数据库 isOk = _bll.SaveDepart(depart.department); } } } if (isOk == false) { Utility.LogHelper.WriteLog("部门信息保存失败"); } }
public void UseExistingInTranslateKey() { File.WriteAllText(this.fooFile.FullName, File.ReadAllText(this.fooFile.FullName).AssertReplace("One resource", "Key")); var sln = CodeFactory.CreateSolution(this.projectFile, MetadataReferences.FromAttributes()); var diagnostics = Analyze.GetDiagnostics(sln, Analyzer); var fixedSln = Roslyn.Asserts.Fix.Apply(sln, Fix, diagnostics, fixTitle: $"Use existing Properties.Resources.Key in Properties.Translate.Key(Properties.Resources.Key)"); var expected = @"// ReSharper disable UnusedMember.Global #pragma warning disable 219 #pragma warning disable GULOC06 namespace Gu.Localization.TestStub { public class Foo { public Foo() { var text = Properties.Translate.Key(nameof(Properties.Resources.Key)); } } } "; CodeAssert.AreEqual(expected, fixedSln.FindDocument("Foo.cs")); }
/// <summary> /// Fix the solution by applying the code fix one fix at the time until it stops fixing the code. /// </summary> /// <returns>The fixed solution or the same instance if no fix.</returns> internal static async Task <Solution> ApplyAllFixableScopeByScopeAsync(Solution solution, DiagnosticAnalyzer analyzer, CodeFixProvider codeFix, string fixTitle, FixAllScope scope, CancellationToken cancellationToken) { var fixable = await Analyze.GetFixableDiagnosticsAsync(solution, analyzer, codeFix).ConfigureAwait(false); var fixedSolution = solution; int count; do { count = fixable.Count; if (count == 0) { return(fixedSolution); } var diagnosticProvider = await TestDiagnosticProvider.CreateAsync(fixedSolution, codeFix, fixTitle, fixable).ConfigureAwait(false); fixedSolution = await ApplyAsync(codeFix, scope, diagnosticProvider, cancellationToken).ConfigureAwait(false); fixable = await Analyze.GetFixableDiagnosticsAsync(fixedSolution, analyzer, codeFix).ConfigureAwait(false); }while (fixable.Count < count); return(fixedSolution); }
public void Can_store_and_retrieve_DateTime_Value() { using (var db = new OrmLiteConnectionFactory(ConnectionString, FirebirdDialect.Provider).Open()) { db.CreateTable <Analyze>(true); var obj = new Analyze { Id = 1, Date = DateTime.Now, Url = "http://www.google.com" }; db.Save(obj); var id = (int)db.LastInsertId(); var target = db.SingleById <Analyze>(id); Assert.IsNotNull(target); Assert.AreEqual(id, target.Id); Assert.AreEqual(obj.Date.ToString("yyyy-MM-dd HH:mm:ss"), target.Date.ToString("yyyy-MM-dd HH:mm:ss")); Assert.AreEqual(obj.Url, target.Url); } }
void GenerateLoadIntegerLiteral(ILGenerator il, Analyze.Expressions.IntegerLiteral literal, Type tgtType) { var bigval = literal.IntValue; switch (Type.GetTypeCode(tgtType)) { case TypeCode.Byte: il.Emit(OpCodes.Ldc_I4, (byte)bigval); break; case TypeCode.Int16: il.Emit(OpCodes.Ldc_I4, (short)bigval); break; case TypeCode.Int32: il.Emit(OpCodes.Ldc_I4, (int)bigval); break; case TypeCode.Int64: il.Emit(OpCodes.Ldc_I8, (long)bigval); break; case TypeCode.SByte: il.Emit(OpCodes.Ldc_I4, (sbyte)bigval); break; case TypeCode.UInt16: il.Emit(OpCodes.Ldc_I4, (ushort)bigval); break; case TypeCode.UInt32: il.Emit(OpCodes.Ldc_I4, (uint)bigval); break; case TypeCode.UInt64: il.Emit(OpCodes.Ldc_I8, (ulong)bigval); break; case TypeCode.Char: il.Emit(OpCodes.Ldc_I4, (char)bigval); break; case TypeCode.Boolean: case TypeCode.DateTime: case TypeCode.DBNull: case TypeCode.Decimal: case TypeCode.Double: case TypeCode.Empty: case TypeCode.String: case TypeCode.Object: throw new Exception(string.Format(ErrorMessages.E_0018_Generator_InvalidNumericLiteral, bigval, tgtType.Name)); default: break; } }
void GenerateLiteralBinding(GenerateTypeInfo typeInfo, Analyze.Binding binding, Analyze.Expressions.Literal literal) { if (literal.ResolvedType == null) { Unit.AddError(new GeneratorError { Message = string.Format(ErrorMessages.E_0017_Generator_UnresolvedType, ApteridError.Truncate(literal.SyntaxNode.Text)), ErrorNode = literal.SyntaxNode }); return; } var atts = FieldAttributes.Static | FieldAttributes.InitOnly; atts |= binding.IsPublic ? FieldAttributes.Public : FieldAttributes.Private; var field = typeInfo.TypeBuilder.DefineField(binding.Name.Name, literal.ResolvedType.CLRType, atts); typeInfo.Bindings.Add(literal, field); if (literal.Value == null) { if (field.FieldType.IsValueType) field.SetConstant(Activator.CreateInstance(field.FieldType)); else field.SetConstant(null); } else { typeInfo.StaticFieldsToInit.Add(new FieldInitInfo { Node = binding.SyntaxNode, Field = field, GenLoad = il => GenerateLoadLiteral(il, literal, field.FieldType) }); } }
void GenerateField(TypeBuilder tb, Analyze.Expression expression) { }
void GenerateBinding(GenerateTypeInfo typeInfo, Analyze.Binding binding) { if (binding.Expression != null) { Analyze.Expressions.Literal literal; // literal -> static field if ((literal = binding.Expression as Analyze.Expressions.Literal) != null) { GenerateLiteralBinding(typeInfo, binding, literal); } } }
void GenerateType(GenerateTypeInfo info, Analyze.Type type) { }
public ApteridGenerator(Context context, GenerationUnit generationUnit, Analyze.Module module) { Context = context; Unit = generationUnit; Module = module; }
void GenerateLoadLiteral(ILGenerator il, Analyze.Expressions.Literal literal, Type tgtType) { MarkSequencePoint(il, literal.SyntaxNode, literal.SyntaxNode); Analyze.Expressions.IntegerLiteral intLiteral; if ((intLiteral = literal as Analyze.Expressions.IntegerLiteral) != null) { GenerateLoadIntegerLiteral(il, intLiteral, tgtType); } }