text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
C_sharp : Consider the following code block : The output is : 3,2 . I 'm trying to understand what happens behind the scenes when this code is running.The compiler generates this new class : The question if how does the x variable get 's changed . How does the x inside < > _DiplayClass1 is changing the x inside Program class . Is it doing something like this behind the scenes ? <code> int x = 1 ; D foo = ( ) = > { Console.WriteLine ( x ) ; x = 2 ; } ; x = 3 ; foo ( ) ; Console.WriteLine ( x ) ; var temp = new < > c_DisplayClass1 ( ) ; temp.x = this.x ; temp. < Main > b_0 ( ) ; this.x = temp.x ; | Deep diving into the implementation of closures |
C_sharp : I have an application that works but after a while when I debug on my iPhone it hangs the phone and the only way I can recover is a hard reset of the button on the side and the home button . First of all , could that be because my application has a memory leak ? Here 's the code for the application . In particular , I am looking at the BeginInvokeOnMainThread method . Can someone tell me if they can see if there could be any problems with the way that it is implemented ? Also , what 's the purpose of the .ContinueWith ( ( arg ) . <code> namespace Japanese { public partial class PhrasesFrame : Frame { CancellationTokenSource cts = new CancellationTokenSource ( ) ; public PhrasesFrame ( PhrasesPage phrasesPage ) { InitializeComponent ( ) ; this.phrasesPage = phrasesPage ; AS.phrasesFrame = this ; Device.BeginInvokeOnMainThread ( ( ) = > ShowCards ( cts.Token ) .ContinueWith ( ( arg ) = > { } ) ) ; } public void Disappearing ( ) { cts.Cancel ( ) ; } public async Task ShowCards ( CancellationToken ct ) { AS.cardCountForSelectedCategories = App.DB.GetCardCountForSelectedCategories ( ) ; while ( ! ct.IsCancellationRequested ) { await Task.Delay ( 500 ) ; } } } } | Could a BeginInvokeOnMainThread method be looping and causing a memory leak ? |
C_sharp : Is it possible to check if a type is part of a namespace without using harcoded strings ? I 'm trying to do something like : orto avoidThese examples do n't compile but should give an idea of what I 'm trying to achieve.I ca n't use nameof ( System.Data ) because it only returns `` Data '' .I would like to find a way to check if a class if part of a namespace without the need to have that namespace in a string . <code> Type type = typeof ( System.Data.Constraint ) ; if ( type.Namespace == System.Data.ToString ( ) ) { ... } Type type = typeof ( System.Data.Constraint ) ; if ( type.Namespace == System.Data ) { ... } Type type = typeof ( System.Data.Constraint ) ; if ( type.Namespace == `` System.Data '' ) { ... } | Check if a type belongs to a namespace without hardcoded strings |
C_sharp : I 've been studying Tasks in .net 4.0 and their cancellation . I like the fact that TPL tries to deal with cancellation correctly in cooperative manner.However , what should one do in situation where a call inside a task is blocking and takes a long time ? For examle IO/Network.Obviously cancelling writes would be dangerous . But those are examples.Example : How would I cancel this ? DownloadFile can take a long time . <code> Task.Factory.StartNew ( ( ) = > WebClient client = new WebClient ( ) ; client.DownloadFile ( url , localPath ) ; ) ; | What would be a good way to Cancel long running IO/Network operation using Tasks ? |
C_sharp : I have this simple LINQ queryHere DesignationID is a nullable field : In objectcontext the query is translated to : While the same query in dbcontext it is translated to : Why does objectcontext handle NULL differently than dbcontext ? <code> from e in Employees where e.DesignationID ! =558select e SELECT [ Extent1 ] . [ EmployeeID ] AS [ EmployeeID ] , [ Extent1 ] . [ EmployeeCode ] AS [ EmployeeCode ] , [ Extent1 ] . [ EmployeeName ] AS [ EmployeeName ] , [ Extent1 ] . [ DesignationID ] AS [ DesignationID ] FROM [ dbo ] . [ setupEmployees ] AS [ Extent1 ] WHERE 558 < > [ Extent1 ] . [ DesignationID ] SELECT [ Extent1 ] . [ EmployeeID ] AS [ EmployeeID ] , [ Extent1 ] . [ EmployeeCode ] AS [ EmployeeCode ] , [ Extent1 ] . [ EmployeeName ] AS [ EmployeeName ] , [ Extent1 ] . [ DesignationID ] AS [ DesignationID ] FROM [ dbo ] . [ setupEmployees ] AS [ Extent1 ] WHERE NOT ( ( 558 = [ Extent1 ] . [ DesignationID ] ) AND ( [ Extent1 ] . [ DesignationID ] IS NOT NULL ) ) | NULL handling in dbcontext and objectcontext |
C_sharp : In the software I am writing I will read some data from an external device ( connected via USB ) . The drivers I have been given ( dll file ) are not thread safe and only one instance can be used at a time . I have to write a wrapper to these drivers in C # . Given that I have a multi-threaded application , I would like to make sure that : Always only one instance is used ( probably the wrapper being a singleton ? ) .It can be disposed of to release the drivers and resources there ( IDisposable ? ) .From Disposable Singleton I can see that the opinions are divided , can a singleton be IDisposable or not . Maybe there is a better solution to both ? Any help welcome.For now I have an IDisposable singleton , like below : <code> using System ; using System.Runtime.InteropServices ; namespace Philips.Research.Myotrace.DataReading.Devices { class MyDevice : IDisposable { private static volatile MyDeviceInstance ; private static object SyncRoot = new Object ( ) ; private bool disposed = false ; private MyDevice ( ) { //initialize unmanaged resources here ( call LoadLibrary , Initialize , Start etc ) } public MyDevice GetInstance ( ) { if ( Instance == null ) { lock ( SyncRoot ) { if ( Instance == null ) { Instance = new MyDevice ( ) ; } } } return Instance ; } public void Dispose ( ) { this.Dispose ( true ) ; } protected virtual void Dispose ( bool disposing ) { if ( ! this.disposed ) { if ( disposing ) { //dispose of unmanaged resources here ( call Stop and Close from reflection code Instance = null ; } this.disposed = true ; } } [ DllImport ( `` devicedrivers.dll '' ) ] private static extern bool Initialize ( ) ; [ DllImport ( `` devicedrivers.dll '' ) ] private static extern bool LoadLibrary ( ) ; [ DllImport ( `` devicedrivers.dll '' ) ] private static extern bool Start ( ) ; [ DllImport ( `` devicedrivers.dll '' ) ] private static extern bool Stop ( ) ; [ DllImport ( `` devicedrivers.dll '' ) ] private static extern bool Close ( ) ; //and few more } } | How to make sure we have only one instance , and it is disposed in a correct way |
C_sharp : what happens when I include the same field twice , meaningly I take from db an entity and I use the EF .include option . What I mean is this : I have : This is the model : so by including ( by mistake ) the student twice ( since my person has ONLY a student ) , is there an issue ? P.S . I only want it included ONCE ! since I have only a single student.Does ef complain about this ? I tried it and it seemed ok , but I do not know the implications of this . Can anyone explain/elaborate ? Searched a bit but could n't identify any issues . <code> .Include ( x = > x.Student ) .Include ( x = > x.Car ) .Include ( x = > x.Student ) Person has a StudentPerson has a car | Behaviour when including the same field twice in entity framework linq |
C_sharp : I have code that creates a cancellation tokenCode that uses it : and code that later cancels this Cancellation Token if the user moves away from the screen where the code above is running : Regarding cancellation , is this the correct way to cancel the token when it 's being used in a Task ? In particular I checked this question : Use of IsCancellationRequested property ? and it 's making me think that I am not doing the cancel the correct way or perhaps in a way that can cause an exception . Also , in this case after I have cancelled then should I be doing a cts.Dispose ( ) ? <code> public partial class CardsTabViewModel : BaseViewModel { public CancellationTokenSource cts ; public async Task OnAppearing ( ) { cts = new CancellationTokenSource ( ) ; // < < runs as part of OnAppearing ( ) await GetCards ( cts.Token ) ; public async Task GetCards ( CancellationToken ct ) { while ( ! ct.IsCancellationRequested ) { App.viewablePhrases = App.DB.GetViewablePhrases ( Settings.Mode , Settings.Pts ) ; await CheckAvailability ( ) ; } } public void OnDisappearing ( ) { cts.Cancel ( ) ; | Is the correct way to cancel a cancellation token used in a task ? |
C_sharp : These two methods exhibit repetition : How can I refactor to eliminate this repetition ? UPDATE : Oops , I neglected to mention an important point . FooEditDto is a subclass of FooDto . <code> public static Expression < Func < Foo , FooEditDto > > EditDtoSelector ( ) { return f = > new FooEditDto { PropertyA = f.PropertyA , PropertyB = f.PropertyB , PropertyC = f.PropertyC , PropertyD = f.PropertyD , PropertyE = f.PropertyE } ; } public static Expression < Func < Foo , FooListDto > > ListDtoSelector ( ) { return f = > new FooDto { PropertyA = f.PropertyA , PropertyB = f.PropertyB , PropertyC = f.PropertyC } ; } | Refactor To Eliminate Repetition In Lambda Expression |
C_sharp : I have noticed this piece of code : What is the purpose of @ ? Are there other uses ? <code> FileInfo [ ] files =new DirectoryInfo ( @ '' C : \ '' ) .GetFiles ( ) ; | What are all the usages of ' @ ' in C # ? |
C_sharp : With the following one-to-one models , both with navigation properties : -Foo has an optional Bar.Bar has a required Foo.I have the following mapping on Bar : -Which creates the foreign key on the Bar table named 'FooId'.All this works fine , except it generates the sql for Foo with a 'Left Outer Join ' to Bar on all queries when its not needed.Looking closer it only returns the Bar 's Id.Searching stack I can see most suggestions to use .WithMany instead of .WithOptional , but I need the navigation properties.Any suggestions ? <code> public class Foo { public int Id { get ; set ; } public virtual Bar Bar { get ; set ; } } public class Bar { public int Id { get ; set ; } public virtual Foo Foo { get ; set ; } } HasRequired ( x = > x.Foo ) .WithOptional ( x = > x.Bar ) .Map ( x = > x.MapKey ( `` FooId '' ) ) ; SELECT .. [ Extent2 ] . [ Id ] AS [ Id1 ] FROM [ dbo ] . [ Foo ] AS [ Extent1 ] LEFT OUTER JOIN [ dbo ] . [ Bar ] AS [ Extent2 ] ON [ Extent1 ] . [ Id ] = [ Extent2 ] . [ FooId ] | EF - WithOptional - Left Outer Join ? |
C_sharp : When inheriting an inherited class , the new / override behaviour is not what I would expect : As class C overrides the sayHi ( ) method I would expect the output to be From C. Why does the B class 's new modifier take precedence here ? What is the use case for that ? Especially as it breaks the obvious use case of having C really override A.Note that the above code was run on Mono 2.10 running on a Debian-derived distro . But I have confirmed the same behaviour using the C # compiler in MS Visual Studio . <code> $ cat Program.csusing System ; class A { public virtual void SayHi ( ) { Console.WriteLine ( `` From A '' ) ; } } class B : A { public new virtual void SayHi ( ) { Console.WriteLine ( `` From B '' ) ; } } class C : B { public override void SayHi ( ) { Console.WriteLine ( `` From C '' ) ; } } public class Program { public static void Main ( ) { A p = new C ( ) ; p.SayHi ( ) ; } } $ ./Program.exe From A | What is the use case for this inheritance idiosyncrasy ? |
C_sharp : This seems very strange to me , if I do then it works perfectly fine , but if I dothen the scripts section will not get rendered and I would get `` The following sections have been defined but have not been rendered for the layout page `` ~/Views/Shared/_Layout.cshtml '' : `` scripts '' . '' errorAny idea why RenderSection/Script.Render can not be inside a code block ? Edit : I have tried to put a break point inside the code block and the break point is getting hit when the page loads , and the RenderSection method executes without any exception <code> @ RenderSection ( `` scripts '' , required : false ) @ { RenderSection ( `` scripts '' , required : false ) ; } | Razor : Render does not work inside code block |
C_sharp : I have a method like so : ... now , the variables a , b , c , and d will never be `` unassigned '' by the point where they would be referenced , but the compiler does n't see it that way . Is there a way I can force the compiler to just `` build it anyway '' ? It seems silly to initialize these values ahead of time . <code> public static long ? FromIpv4ToLong ( this string ipAddress ) { var octets = ipAddress.Split ( IpSplitChar ) ; if ( octets.Length ! = 4 ) return null ; var success = long.TryParse ( octets [ 0 ] , out long a ) & & long.TryParse ( octets [ 1 ] , out long b ) & & long.TryParse ( octets [ 2 ] , out long c ) & & long.TryParse ( octets [ 3 ] , out long d ) ; if ( ! success ) return null ; return ( ( 16777216L * a ) + ( 65536L * b ) + ( 256L * c ) + d ) ; } | Suppress `` Use of unassigned local variable '' error ? |
C_sharp : I have an object with properties names that exactly name the field names inside the DB table but I 'm not sure how to insert it . The only thing different is the DB table name . So it 's an object with a name of different model/mapped table but I want it to be inserted into a table with a different name than the model . I tried this : Where e.g . Object is FooBarObj and properties are int Id , string Foo , string Bar and the DBInformation has the field names : Id , Foo , and Bar but the table is n't called FooBarObj , it 's called DBInformation . How can I insert something like this ? I 'm using DapperEDIT : Can I have two table attributes for FooBar model ? E.g . [ Table ( `` DBInformation '' ) ] and [ Table ( `` FooBar '' ) ] .I have a weird edge case where I want to insert into FooBar if this scenario occurs , if another scenario occurs , insert into DBInformation . That 's the problem I 'm currently facing and thus that 's why I ca n't just add the attribute and be done with for this problem . <code> var val = info.FooBarObj ; conn.Execute ( `` insert DBInformation ( val ) values ( @ val ) '' , new { val = val } ) ; | Inserting object that should be mapped into different DB table depending on scenario |
C_sharp : I tried to generate IL for recursive method using following strategy , Firstly I defined type using following code snippetNext I started to generate IL for recursive method as given below.For calling method itself inside the method body I used following construct , Finally save generated assembly using following method.Unfortunately this is not working since recursive method calling construct , inside the method returns null . Issue here is that recursive call inside the method ( i.e . ilOfMethod.Emit ( OpCodes.Call , typeBuilder.GetMethod ( `` MethodName '' , new System.Type [ ] { typeof ( arg1 ) , typeof ( arg2 ) , etc } ) ) ; ) returns null . Since we actually create the type inside the SaveAssembly ( ) method , this is acceptable . So my question is that : is it possible to generate IL for recursive methods using above construct ? If it is not possible , Please let me know that alternative constructs for generating IL for recursive methods . <code> private void InitializeAssembly ( string outputFileName ) { AppDomain appDomain = AppDomain.CurrentDomain ; AssemblyName assemblyName = new AssemblyName ( outputFileName ) ; assemblyBuilder = appDomain.DefineDynamicAssembly ( assemblyName , AssemblyBuilderAccess.Save ) ; moduleBuilder = assemblyBuilder.DefineDynamicModule ( outputFileName , outputFileName + `` .exe '' ) ; typeBuilder = moduleBuilder.DefineType ( typeName , TypeAttributes.Public ) ; methodBuilder = typeBuilder.DefineMethod ( `` Main '' , MethodAttributes.Static | MethodAttributes.Public , typeof ( void ) , System.Type.EmptyTypes ) ; ilGen = methodBuilder.GetILGenerator ( ) ; } MethodBuilder method = typeBuilder.DefineMethod ( “ MethodName ” , MethodAttributes.Static | MethodAttributes.Public , NodeTypeToDotNetType ( func.RetType ) , parameters ) ; ILGenerator ilOfMethod = method.GetILGenerator ( ) ; method.DefineParameter ( ) ; ilOfMethod.Emit ( OpCodes.Call , typeBuilder.GetMethod ( `` MethodName '' , new System.Type [ ] { typeof ( arg1 ) , typeof ( arg2 ) , etc } ) ) ; private void SaveAssembly ( string outputFileName ) { ilGen.Emit ( OpCodes.Ret ) ; typeBuilder.CreateType ( ) ; moduleBuilder.CreateGlobalFunctions ( ) ; assemblyBuilder.SetEntryPoint ( methodBuilder ) ; assemblyBuilder.Save ( outputFileName + `` .exe '' ) ; } | Generating IL for Recursive Methods |
C_sharp : I 'm trying to return a strongly typed Enumeration value from a string . I 'm sure there is a better way to do this . This just seems like way too much code for a simple thing like this : Ideas ? Based on the feedback I got from the community , I have decided to use a method extension that converts a string to an enumeration . It takes one parameter ( the default enumeration value ) . That default also provides the type , so the generic can be inferred and does n't need to be specified explicitly using < > . The method is now shortened to this : Very cool solution that can be reused in the future . <code> public static DeviceType DefaultDeviceType { get { var deviceTypeString = GetSetting ( `` DefaultDeviceType '' ) ; if ( deviceTypeString.Equals ( DeviceType.IPhone.ToString ( ) ) ) return DeviceType.IPhone ; if ( deviceTypeString.Equals ( DeviceType.Android.ToString ( ) ) ) return DeviceType.Android ; if ( deviceTypeString.Equals ( DeviceType.BlackBerry.ToString ( ) ) ) return DeviceType.BlackBerry ; if ( deviceTypeString.Equals ( DeviceType.Other.ToString ( ) ) ) return DeviceType.Other ; return DeviceType.IPhone ; // If no default is provided , use this default . } } public static DeviceType DefaultDeviceType { get { return GetSetting ( `` DefaultDeviceType '' ) .ToEnum ( DeviceType.IPhone ) ; } } | How to return a Enum value from a string ? |
C_sharp : In CLR via C # , Richter notes that initializing fields in a class declaration , like soresults in inserting statements at the beginning of each constructor that set the fields to the provided values . As such , the line int x = 3 ; above will be responsible for two separate initializations -- one in the parameterless constructor and one in the constructor that takes an int argument.Richter goes on to say : This means that you should be aware of code explosion [ ... ] If you have several initialized instance fields and a lot of overloaded constructor methods , you should consider defining the fields without the initialization , creating a single constructor that performs the common initialization , and having each constructor explicitly call the common initialization constructor . This approach will reduce the size of the generated code.I 'm having trouble envisioning a scenario in which this would become a noticeable issue , which makes me wonder if I 'm missing something here . For instance , if we imagine that our class has ten constructors and a hundred fields and it takes , say , sixteen bytes of native machine code to perform an initialization then we 're talking about a total of 16 kB of generated native code . Surely that 's a negligible amount of memory on any computer from this century , right ? I imagine using generics could multiply that by a small factor , but still the impact on the working set seems quite small.Question : Am I missing something here , and , if so , what ? While my question is mainly theoretical -- I want to test my own understanding -- it 's also a bit practical , as initializing the fields where they 're declared seems to produce substantially more readable code than using a centralized constructor like Richter suggests . <code> class C { int x = 3 ; int y = 4 ; public C ( ) { ... } public C ( int z ) { ... } ... } | What is a real-life example of detrimental code explosion caused by field initializations ? |
C_sharp : I had a discussion in another thread , and found out that class methods takes precedence over extension methods with the same name and parameters . This is good as extension methods wo n't hijack methods , but assume you have added some extension methods to a third party library : Works as expected : ThirdParty.MyMethod - > `` My extension method '' But then ThirdParty updates it 's library and adds a method exactly like your extension method : ThirdPart.MyMethod - > `` Third party method '' Now suddenly code will behave different at runtime as the third party method has `` hijacked '' your extension method ! The compiler does n't give any warnings.Is there a way to enable such warnings or otherwise avoid this ? <code> public class ThirdParty { } public static class ThirdPartyExtensions { public static void MyMethod ( this ThirdParty test ) { Console.WriteLine ( `` My extension method '' ) ; } } public class ThirdParty { public void MyMethod ( ) { Console.WriteLine ( `` Third party method '' ) ; } } public static class ThirdPartyExtensions { public static void MyMethod ( this ThirdParty test ) { Console.WriteLine ( `` My extension method '' ) ; } } | Extension methods overridden by class gives no warning |
C_sharp : I have a code in PCL that I want to migrate to .NetStandard . Unfortunately tho , my code is dependent on .Net reflection and I cant find some of the methods previously available . So here is the list of methods or properties that I cant find under .NetStandard . Can any one point me in right direction about how to refactor my code ? <code> Type.IsInstanceOfType ( ) Type.IsAssignableFrom ( ) Type.GetNestedTypes ( ) Type.GetConstructors ( ) Type.IsClassType.IsEnumType.IsValueType | .NetStandard : Missing Type Methods and Properties |
C_sharp : In the snippet below , a task creates two child tasks using the TaskCreationOptions.AttachedToParent , which means the parent task will wait for the child tasks to finish . Question is - why does n't the parent task return correct value [ 102 ] ? Does it first determine its return value and then wait for the child tasks to finish . If so , then what is the point of creating parent-child relationship ? The output : <code> void Main ( ) { Console.WriteLine ( `` Main start . `` ) ; int i = 100 ; Task < int > t1 = new Task < int > ( ( ) = > { Console.WriteLine ( `` In parent start '' ) ; Task c1 = Task.Factory.StartNew ( ( ) = > { Thread.Sleep ( 1000 ) ; Interlocked.Increment ( ref i ) ; Console.WriteLine ( `` In child 1 : '' + i ) ; } , TaskCreationOptions.AttachedToParent ) ; Task c2 = Task.Factory.StartNew ( ( ) = > { Thread.Sleep ( 2000 ) ; Interlocked.Increment ( ref i ) ; Console.WriteLine ( `` In child 2 : '' + i ) ; } , TaskCreationOptions.AttachedToParent ) ; Console.WriteLine ( `` In parent end '' ) ; return i ; } ) ; t1.Start ( ) ; Console.WriteLine ( `` Calling Result . `` ) ; Console.WriteLine ( t1.Result ) ; Console.WriteLine ( `` Main end . `` ) ; } Main start.Calling Result.In parent startIn parent endIn child 1:101In child 2:102100Main end . | Returning value from Parent-Child tasks |
C_sharp : I 'm a big fan of CodeRush and their philosophy around templates . At my current job , we 'll be doing a large amount of pairing and the consensus is a preference for ReSharper ( v6 ) , which pretty much puts me in a place where I MUST use it.I 'm not looking to start a CodeRush/Resharper war here . There are plenty of things to like about Resharper , but there 's one thing I 'm having a hard time getting past in ReSharper.ReSharper 's Live template mechanism , wile good , does n't have built-in notions for typing the way CodeRush does ( at least not as I can tell ) . A simple example is as follows . To gen the following code : In CodeRush ... I could type `` as '' ( ' a ' for AutoProperty and 's ' for string ) , then simply change the name of the property.In ReSharper , I need to type `` prop '' ( for Property ) , then set the type and and name.There does not seem to be a similar notion for type awareness or type shortcuts in ReSharper 's Live Templates . As such , there does n't appear to be anything akin to the numerous two and three character templates to get you pre-typed variables , properties , methods , etc ... So , finally the question after all that background . Is there any way to replicate this notion of `` typed templates '' in ReSharper without creating a new live template for every template/type combination ? <code> public String MyStringProperty { get ; set ; } | CodeRush style typed templates for ReSharper |
C_sharp : I have a .sql file with stored procedures definitions.I need to write a small program in C # that reads the file and obtains a list with the stored procedures signatures . For example , this list should look like this : Is there a way to do this using Regex ? What is the best approach ? <code> [ dbo ] . [ procedureOne ] ( int , int , varchar ( 250 ) out , nvarchar ) [ dbo ] . [ procedureTwo ] ( int , varchar ( 255 ) ) [ dbo ] . [ procedureThree ] ( ) [ dbo ] . [ amazingSP ] ( datetime , datetime ) | How to parse a stored procedure signature in C # from plain text |
C_sharp : To avoid old-fashioned non-generic syntax when searching for attributes of a known type , one usually uses the extension methods in System.Reflection.CustomAttributeExtensions class ( since .NET 4.5 ) .However this appears to fail if you search for an attribute on the return parameter of an overridden method ( or an accessor of an overridden property/indexer ) .I am experiencing this with .NET 4.6.1.Simple reproduction ( complete ) : The code may look `` too long to read '' , but it is really just an overridden method with an attribute on its return parameter and the obvious attempt to retrieve that attribute instance.Stack trace : Am I doing anything obviously wrong ? Is this a bug , and if yes , is it well-known , and is it an old bug ? <code> using System ; using System.Reflection ; namespace ReflectionTrouble { class B { // [ return : MyMark ( `` In base class '' ) ] // uncommenting does not help public virtual int M ( ) = > 0 ; } class C : B { [ return : MyMark ( `` In inheriting class '' ) ] // commenting away attribute does not help public override int M ( ) = > -1 ; } [ AttributeUsage ( AttributeTargets.ReturnValue , AllowMultiple = false , Inherited = false ) ] // commenting away AttributeUsage does not help sealed class MyMarkAttribute : Attribute { public string Descr { get ; } public MyMarkAttribute ( string descr ) { Descr = descr ; } public override string ToString ( ) = > $ '' MyMark ( { Descr } ) '' ; } static class Program { static void Main ( ) { var derivedReturnVal = typeof ( C ) .GetMethod ( `` M '' ) .ReturnParameter ; // usual new generic syntax ( extension method in System.Refelction namespace ) : var attr = derivedReturnVal.GetCustomAttribute < MyMarkAttribute > ( ) ; // BLOWS UP HERE , System.IndexOutOfRangeException : Index was outside the bounds of the array . Console.WriteLine ( attr ) ; // old non-generic syntax without extension method works : var attr2 = ( ( MyMarkAttribute [ ] ) ( derivedReturnVal.GetCustomAttributes ( typeof ( MyMarkAttribute ) , false ) ) ) [ 0 ] ; // OK Console.WriteLine ( attr2 ) ; } } } Unhandled Exception : System.IndexOutOfRangeException : Index was outside the bounds of the array . at System.Attribute.GetParentDefinition ( ParameterInfo param ) at System.Attribute.InternalParamGetCustomAttributes ( ParameterInfo param , Type type , Boolean inherit ) at System.Attribute.GetCustomAttributes ( ParameterInfo element , Type attributeType , Boolean inherit ) at System.Attribute.GetCustomAttribute ( ParameterInfo element , Type attributeType , Boolean inherit ) at System.Reflection.CustomAttributeExtensions.GetCustomAttribute [ T ] ( ParameterInfo element ) at ReflectionTrouble.Program.Main ( ) in c : \MyPath\Program.cs : line 38 | Reflection with generic syntax fails on a return parameter of an overridden method |
C_sharp : Why do n't we get compile errors on inline code errors in asp.net mvc views f.eksThe code above will build just fine . Wrong spelling in webform controls will give you an error so I ca n't see why this is n't supported in asp.net mvcEDIT : Luckily there seem to be a fix included in the first RC for asp.net mvchttp : //weblogs.asp.net/scottgu/archive/2008/12/19/asp-net-mvc-design-gallery-and-upcoming-view-improvements-with-the-asp-net-mvc-release-candidate.aspx <code> < h1 > < % = ViewData.Model.Title.Tostrig ( ) % > < /h1 > | Build does not catch errors in the View in asp.net mvc |
C_sharp : The following program does not compile , because in the line with the error , the compiler chooses the method with a single T parameter as the resolution , which fails because the List < T > does not fit the generic constraints of a single T. The compiler does not recognize that there is another method that could be used . If I remove the single-T method , the compiler will correctly find the method for many objects.I 've read two blog posts about generic method resolution , one from JonSkeet here and another from Eric Lippert here , but I could not find an explanation or a way to solve my problem.Obviously , having two methods with different names would work , but I like the fact that you have a single method for those cases . <code> namespace Test { using System.Collections.Generic ; public interface SomeInterface { } public class SomeImplementation : SomeInterface { } public static class ExtensionMethods { // comment out this line , to make the compiler chose the right method on the line that throws an error below public static void Method < T > ( this T parameter ) where T : SomeInterface { } public static void Method < T > ( this IEnumerable < T > parameter ) where T : SomeInterface { } } class Program { static void Main ( ) { var instance = new SomeImplementation ( ) ; var instances = new List < SomeImplementation > ( ) ; // works instance.Method ( ) ; // Error 1 The type 'System.Collections.Generic.List < Test.SomeImplementation > ' // can not be used as type parameter 'T ' in the generic type or method // 'Test.ExtensionMethods.Method < T > ( T ) ' . There is no implicit reference conversion // from 'System.Collections.Generic.List < Test.SomeImplementation > ' to 'Test.SomeInterface ' . instances.Method ( ) ; // works ( instances as IEnumerable < SomeImplementation > ) .Method ( ) ; } } } | Generic extension method resolution fails |
C_sharp : I 'm a C # developer who is working through `` Real World Haskell '' in order to truly understand functional programming , so that when I learn F # , I 'll really grok it and not just `` write C # code in F # '' , so to speak.Well , today I came across an example which I thought I understood 3 different times , only to then see something I missed , update my interpretation , and recurse ( and curse too , believe me ) .Now I believe that I do actually understand it , and I have written a detailed `` English interpretation '' below . Can you Haskell gurus please confirm that understanding , or point out what I have missed ? Note : The Haskell code snippet ( quoted directly from the book ) is defining a custom type that is meant to be isomorphic to the built in Haskell list type.The Haskell code snippetEDIT : After some responses , I see one misunderstanding I made , but am not quite clear on the Haskell `` parsing '' rules that would correct that mistake . So I 've included my original ( incorrect ) interpretation below , followed by a correction , followed by the question that still remains unclear to me.EDIT : Here is my original ( incorrect ) `` English interpretation '' of the snippetI am defining a type called `` List '' .The List type is parameterised . It has a single type parameter.There are 2 value constructors which can be used to make instances of List . One value constructor is called `` Nil '' and the other value constructor is called `` Cons '' .If you use the `` Nil '' value constructor , then there are no fields.The `` Cons '' value constructor has a single type parameter.If you use the `` Cons '' value constructor , there are 2 fields which must be provided . The first required field is an instance of List . The second required field is an instance of a . ( I have intentionally omitted anything about `` defining Show '' because it is not part of what I want to focus on right now ) .The corrected interpretation would be as follows ( changes in BOLD ) I am defining a type called `` List '' .The List type is parameterised . Ithas a single type parameter.There are 2 value constructors which can be used to make instances of List . One value constructor is called `` Nil '' and the other value constructor is called `` Cons '' . If you use the `` Nil '' value constructor , then there are no fields.5 . ( this line has been deleted ... it is not accurate ) The `` Cons '' value constructor has a single type parameter.If you use the `` Cons '' value constructor , there are 2 fields which must be provided . The first required field is an instance of a . The second required field is an instance of `` List-of-a '' . ( I have intentionally omitted anything about `` defining Show '' because it is not part of what I want to focus on right now ) .The question which is still unclearThe initial confusion was regarding the portion of the snippet that reads `` Cons a ( List a ) '' . In fact , that is the part that is still unclear to me.People have pointed out that each item on the line after the `` Cons '' token is a type , not a value . So that means this line says `` The Cons value constructor has 2 fields : one of type ' a ' and the other of type 'list-of-a ' . `` That is very helpful to know . However , something is still unclear . When I create instances using the Cons value constructor , those instances `` interpret '' the first ' a ' as meaning `` place the value passed in here . '' But they do not interpret the second ' a ' the same way . For example , consider this GHCI session : When I type `` Cons 0 Nil '' , it uses the `` Cons '' value constructor to create an instance of List . From 0 , it learns that the type parameter is `` Integer '' . So far , no confusion.However , it also determines that the value of the first field of the Cons is 0 . Yet it determines nothing about the value of the second field ... it only determines that the second field has a type of `` List Integer '' .So my question is , why does `` a '' in the first field mean `` the type of this field is ' a ' and the value of this field is ' a ' '' , while `` a '' in the second field means only `` the type of this field is 'List of a ' '' ? EDIT : I believe I have now seen the light , thanks to several of the responses . Let me articulate it here . ( And if somehow it is still incorrect in some fashion , please by all means let me know ! ) In the snippet `` Cons a ( List a ) '' , we are saying that the `` Cons '' value constructor has two fields , and that the first field is of type ' a ' , and that the second field is of type 'List of a'.That is all we are saying ! In particular , we are saying NOTHING about values ! This is a key point I was missing.Later , we want to create an instance , using the `` Cons '' value constructor . We type this into the interpreter : `` Cons 0 Nil '' . This explicitly tells the Cons value constructor to use 0 for the value of the first field , and to use Nil as the value for the second field . And that 's all there is to it . Once you know that the value constructor definition specifies nothing but types , everything becomes clear.Thanks everyone for the helpful responses . And as I said , if anything is still off , please by all means tell me about it . Thanks . <code> data List a = Cons a ( List a ) | Nil defining Show *Main > Cons 0 NilCons 0 Nil*Main > Cons 1 itCons 1 ( Cons 0 Nil ) *Main > | Please confirm or correct my `` English interpretation '' of this Haskell code snippet |
C_sharp : I have a list of recipes obtained from a database that looks like this : RecipeNode , among other things , has a property that references one or more tags ( Such as Dinner , Breakfast , Side , Vegetarian , Holiday , and about 60 others ) .Finding a random recipe from _recipeList in O ( 1 ) would of course be easy , however what I need to do is find a random recipe that has , say , 5 in the Tags in O ( 1 ) .Right now , my only idea is to make an array of List < RecipeNodes > , keyed by tag . For example : Then , _recipeListByTag [ 5 ] would contain a list of all the recipes that have a 5 in the Tags array . I could then choose a random allowed tag and a random recipe within that tag in O ( 1 ) .The drawback of this approach is the size of this multidimensional array would be Recipes * Tags ( eg , the sum of Tags.length across all recipes ) , which starts to take up a lot of memory since I 'm storing a potentially huge number of recipes in this array . Of course , since RecipeNode is a reference type , I 'm only repeating the 4byte pointers to the recipes , so this still might be the best way to go.Is there a more efficient data structure or algorithm I could use to allow me to find a random recipe that contains a certain allowed tag ? Thanks ! <code> List < RecipeNode > _recipeList ; public sealed class RecipeNode { public Guid RecipeId ; public Byte [ ] Tags ; //Tags such as 1 , 5 , 6 , 8 , 43 // ... More stuff } List < RecipeNode > [ ] _recipeListByTag ; | How to pick a random element from an array that matches a certain criteria in O ( 1 ) |
C_sharp : I 've created an EF Core model from an existing database and all operations on entities work EXCEPT for updates ; on updates EF Core is using an incorrect database name . eg . When I perform an update I get a SqlException : Invalid object name 'BirdBrain.dbo.services'.. BirdBrainContext is the name of my DbContext , but the database I 'm connecting to is BirdBrain_test.I tried updating from EF Core 2.1 to EF Core 2.2 but the issue persists . When connecting to the production database named BirdBrain the same code functions perfectly.I am initializing my context using a connection string like the following and I do not know how this leads to updates being run against 'BirdBrain.dbo.services ' when the database is BirdBrain_test.Relevant DbContext codeThe table for the associated I am using the TableAttribute to refer to the table name.Relevant Update codeGets , Inserts , and Deletes work on this same table.EDIT : I added EF Core logging as Ivan Stoev suggested and pasted the results for the update below . It looks like EF is connecting to the BirdBrain_test database and running a UPDATE [ services ] ... as opposed to UPDATE [ BirdBrain ] . [ dbo ] . [ services ] as the error would suggest . Still not sure what is going on . <code> Server=**** ; Database=BirdBrain_test ; User Id=**** ; Password=**** ; Trusted_Connection=False ; Multisubnetfailover=true ; public class BirdBrainContextFactory { private readonly string _connectionString ; public BirdBrainContextFactory ( string connectionString ) { _connectionString = connectionString ; } public BirdBrainContext Create ( ) { var optionsBuilder = new DbContextOptionsBuilder < BirdBrainContext > ( ) ; optionsBuilder.UseSqlServer ( _connectionString ) ; return new BirdBrainContext ( optionsBuilder.Options ) ; } } public class BirdBrainContext : DbContext { public BirdBrainContext ( DbContextOptions < BirdBrainContext > options ) : base ( options ) { } public DbSet < Service > Services { get ; set ; } protected override void OnModelCreating ( ModelBuilder modelBuilder ) { modelBuilder.Entity < Service > ( entity = > { entity.HasIndex ( e = > e.Tag ) .IsUnique ( ) ; entity.Property ( e = > e.CreatedAt ) .HasDefaultValueSql ( `` ( getutcdate ( ) ) '' ) ; entity.Property ( e = > e.UpdatedAt ) .HasDefaultValueSql ( `` ( getutcdate ( ) ) '' ) ; } ) ; } } [ Table ( `` services '' ) ] public class Service { ... } public Service UpdateService ( Service service ) { using ( var context = _contextFactory.Create ( ) ) { EnforceServiceExists ( context , service ) ; context.Entry ( service ) .State = EntityState.Modified ; context.SaveChanges ( ) ; return service ; } } Microsoft.EntityFrameworkCore.DbUpdateException HResult=0x80131500 Message=An error occurred while updating the entries . See the inner exception for details . Source=Microsoft.EntityFrameworkCore.Relational StackTrace : at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute ( IRelationalConnection connection ) at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute ( DbContext _ , ValueTuple ` 2 parameters ) at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute [ TState , TResult ] ( TState state , Func ` 3 operation , Func ` 3 verifySucceeded ) at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute ( IEnumerable ` 1 commandBatches , IRelationalConnection connection ) at Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges ( IReadOnlyList ` 1 entries ) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges ( IReadOnlyList ` 1 entriesToSave ) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges ( Boolean acceptAllChangesOnSuccess ) at Microsoft.EntityFrameworkCore.DbContext.SaveChanges ( Boolean acceptAllChangesOnSuccess ) at Microsoft.EntityFrameworkCore.DbContext.SaveChanges ( ) at DataService.BirdBrainContext.SaveChanges ( ) in C : \git\BirdBrainAPI\src\DataService\BirdBrainContext.cs : line 180 ... Inner Exception 1 : SqlException : Invalid object name 'BirdBrain.dbo.services ' . dbug : Microsoft.EntityFrameworkCore.Database.Connection [ 20001 ] Opened connection to database 'BirdBrain_test ' on server '****'.dbug : Microsoft.EntityFrameworkCore.Database.Transaction [ 20200 ] Beginning transaction with isolation level 'ReadCommitted'.dbug : Microsoft.EntityFrameworkCore.Database.Command [ 20100 ] Executing DbCommand [ Parameters= [ @ p19= ' ? ' ( DbType = Int32 ) , @ p0= ' ? ' ( DbType = DateTime ) , ... ] , CommandType='Text ' , CommandTimeout='30 ' ] SET NOCOUNT ON ; UPDATE [ services ] SET [ created_at ] = @ p0 , ... , [ updated_at ] = @ p18 WHERE [ id ] = @ p19 ; SELECT @ @ ROWCOUNT ; fail : Microsoft.EntityFrameworkCore.Database.Command [ 20102 ] Failed executing DbCommand ( 61ms ) [ Parameters= [ @ p19= ' ? ' ( DbType = Int32 ) , @ p0= ' ? ' ( DbType = DateTime ) , ... ] , CommandType='Text ' , CommandTimeout='30 ' ] SET NOCOUNT ON ; UPDATE [ services ] SET [ created_at ] = @ p0 , ... , [ updated_at ] = @ p18 WHERE [ id ] = @ p19 ; SELECT @ @ ROWCOUNT ; System.Data.SqlClient.SqlException ( 0x80131904 ) : Invalid object name 'BirdBrain.dbo.services ' . at System.Data.SqlClient.SqlConnection.OnError ( SqlException exception , Boolean breakConnection , Action ` 1 wrapCloseInAction ) at System.Data.SqlClient.SqlInternalConnection.OnError ( SqlException exception , Boolean breakConnection , Action ` 1 wrapCloseInAction ) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning ( TdsParserStateObject stateObj , Boolean callerHasConnectionLock , Boolean asyncClose ) at System.Data.SqlClient.TdsParser.TryRun ( RunBehavior runBehavior , SqlCommand cmdHandler , SqlDataReader dataStream , BulkCopySimpleResultSet bulkCopyHandler , TdsParserStateObject stateObj , Boolean & dataReady ) at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData ( ) at System.Data.SqlClient.SqlDataReader.get_MetaData ( ) at System.Data.SqlClient.SqlCommand.FinishExecuteReader ( SqlDataReader ds , RunBehavior runBehavior , String resetOptionsString ) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds ( CommandBehavior cmdBehavior , RunBehavior runBehavior , Boolean returnStream , Boolean async , Int32 timeout , Task & task , Boolean asyncWrite , SqlDataReader ds ) at System.Data.SqlClient.SqlCommand.RunExecuteReader ( CommandBehavior cmdBehavior , RunBehavior runBehavior , Boolean returnStream , TaskCompletionSource ` 1 completion , Int32 timeout , Task & task , Boolean asyncWrite , String method ) at System.Data.SqlClient.SqlCommand.ExecuteReader ( CommandBehavior behavior ) at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader ( CommandBehavior behavior ) at System.Data.Common.DbCommand.ExecuteReader ( ) at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute ( IRelationalConnection connection , DbCommandMethod executeMethod , IReadOnlyDictionary ` 2 parameterValues ) ClientConnectionId : b2b87fd1-8e34-4fcf-80f1-290de30b28ddError Number:208 , State:1 , Class:16 | Entity Framework throws exception on updates only - Invalid object name 'dbo.BirdBrain.service ' |
C_sharp : Just out of curiousity ( not really expecting a measurable result ) which of the following codes are better in case of performance ? In the first example I use char , while in the second using strings in Contains ( ) and Replace ( ) Would the first one have better performance because of the less memory-consuming `` char '' or does the second perform better , because the compiler does not have to cast in this operation ? ( Or is this all nonsense , cause the CLR generates the same code in both variations ? ) <code> private void ReplaceChar ( ref string replaceMe ) { if ( replaceMe.Contains ( ' a ' ) ) { replaceMe=replaceMe.Replace ( ' a ' , ' b ' ) ; } } private void ReplaceString ( ref string replaceMe ) { if ( replaceMe.Contains ( `` a '' ) ) { replaceMe=replaceMe.Replace ( `` a '' , `` b '' ) ; } } | Performance char vs string |
C_sharp : When I use code with generic : where TParent : IEnityI catch the exception : The member 'Id ' is not supported in the 'Where ' Mobile Services query expression 'Convert ( prnt ) .Id'.But if I change the generic to type : I have normal result.Why ? And how can I use generic ? <code> var parenttable = MobileService.GetTable < TParent > ( ) ; var testid = await parenttable.Where ( prnt = > prnt.Id == 20 ) .ToListAsync ( ) ; public interface IEnity { int Id { get ; set ; } } var parenttable = MobileService.GetTable < Category > ( ) ; var testid = await parenttable.Where ( prnt = > prnt.Id == 20 ) .ToListAsync ( ) ; | Mobile Services query exception |
C_sharp : IntroductionConsider this simple ( and bad ) C # class : Both methods M and L have serious issues.In M , we ask if a value of the non-nullable struct DateTime is equal to null via the lifted == operator ( which exists since DateTime overloads operator == ) . This is always falls , and the compiler can tell at compile-time , so we have a branch ( `` Yes '' ) which is unreachable.In N we ask if o is an instance of the static class Nullable which can never be the case ( note , the static class Nullable is not the same as the struct Nullable < > ) . Again , this is a developer mistake , and the `` Yes '' statement is unreachable.We do want a compile-time warning ( or `` warning as error '' ) in these cases , right ? As it seems , through gradual accumulation of compiler errors and/or omissions in the old C # compiler that was used for C # 1.0 through 5.0 , the expected compile-time warnings failed to appear with the old compiler . Luckily we have Roslyn/C # 6.0/Visual Studio 2015 now , and expect to get a warning . But no , because of the desire to not emit warnings from Roslyn that where not present with the old compiler ( backwards compatibility ? ) , these situations are still not warned against.However , if you compile from the command line , with csc.exe , you can use : and you will get the warnings you want ! /features : strict makes csc.exe include warnings that the old C # compiler `` fogot '' .My questionHow do I specify the equivalent of /features : strict to msbuild.exe command line or in the .csproj file ? Sometimes , e.g . when we have XAML in our build project , it is not easy to use csc.exe directly , we have to use a .csproj file and compile through msbuild.exe . <code> using System ; namespace N { static class C { static void M ( DateTime d ) { if ( d == null ) Console.WriteLine ( `` Yes '' ) ; else Console.WriteLine ( `` No '' ) ; } static void L ( object o ) { if ( o is Nullable ) Console.WriteLine ( `` Yes '' ) ; else Console.WriteLine ( `` No '' ) ; } } } csc.exe /features : strict ... ... | How to specify the equivalent of /features : strict ( of csc.exe ) to msbuild.exe or in the .csproj file ? |
C_sharp : I am trying to get certain bytes to write on an Image , for example : `` །༉ᵒᵗᵗ͟ᵋༀ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ . . . `` When I display it on an image but I am getting the following instead ... Image : I have tried changing the Encoding Type of the string , when I receive the bytes and there is no set font but I have tried all default Microsoft fonts as well as a few custom ones I found on the Internet . What am I doing Wrong ? Edit : The original was using Graphics.DrawString . I have tried TextRenderer and it came out with almost the same results.Image : This is the code I 'm using to generate the image : The variable cmd.AllArguments is passed down into the method , I believe the string is Encoded using windows-1252 . <code> string text = `` [ rotten4pple ] །༉ᵒᵗᵗ͟ᵋༀ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ . . . `` ; var font = new Font ( `` Arial '' , 8 , FontStyle.Regular ) ; var bitmap = new Bitmap ( 1 , 1 ) ; var size = Graphics.FromImage ( bitmap ) .MeasureString ( text , font ) ; bitmap = new Bitmap ( ( int ) size.Width + 4 , ( int ) size.Height + 4 ) ; using ( var gfx = Graphics.FromImage ( bitmap ) ) { gfx.Clear ( Color.White ) ; TextRenderer.DrawText ( gfx , cmd.AllArguments , font , new Point ( 2 , 2 ) , Color.Black , Color.White ) ; } | Drawing Bytes on an Image |
C_sharp : I am using this action-link to send a route value id to controller but my id value like this config.xmland here is my action-link The question is when I want to click this link browser understand this as a url that ends with config.xml like this and does n't go to the controller it returns 404 - not found.How to prevent this from happening and make this config.xml as a parameter not as a file ? here is my route alsoalso i tried instead id , filename but nothing changed and here is my controller <code> @ Html.ActionLink ( `` Destroy '' , `` DeleteFile '' , `` Files '' , new { id = `` config.xml '' } ) http : //localhost:12380/Files/DeleteFile/config.xml routes.MapRoute ( name : `` delete files '' , url : `` Files/DeleteFile/ { id } '' , defaults : new { controller = `` Files '' , action = `` DeleteFile '' , id= UrlParameter.Optional } ) ; [ HttpGet ] public ActionResult DeleteFile ( string id ) { return view ( `` DeleteFile '' ) ; } | ActionLink route values containing specific characters |
C_sharp : I 'm making a GenericTable as a custom implementation of GridView that will display the values of any list of objects that 's inserted.To use the control on an aspx page it needs to be a UserControl , so the GridView is included as a component in the GenericTable : This works fine for the first use of my control , it 's added on the aspx page . It seems that doing that adds some sort of magic that initiates the control components.When the user clicks on an item that has properties of it 's own , the GenericTable should insert a row below the current row and spawn a new GenericTable that will show said properties . table is the DataTable that I use to set the GridView contents : When I try to activate the newly made GenericTable , after this code , it 's grid is null.Is there a way to initialize the same magic that happens when this control is located in the aspx code ? Update : Maybe the problem lies in how the table is stored between postbacks , currently I 'm using the session , maybe there 's a better way to remember user input ? The whole GenericTable code : <code> < % @ Control Language= '' C # '' AutoEventWireup= '' true '' CodeBehind= '' GenericTable.ascx.cs '' Inherits= '' CASH.WebApplication.Controls.GenericTable '' % > < div style= '' width : 100 % ; overflow : scroll '' > < asp : GridView ID= '' grid '' runat= '' server '' > < /asp : GridView > < /div > var data = table.NewRow ( ) ; var child = new GenericTable ( ) ; data [ 0 ] = child ; table.Rows.InsertAt ( data , row ) ; grid.DataSource = table ; grid.DataBind ( ) ; // The extra row is displayed now , initialize components in the aspx code ? child.MakeTable ( ) ; // Throws exception because it 's ` grid ` property is null . using Project.DomainModel.Models ; using System ; using System.Collections.Generic ; using System.Data ; using System.IO ; using System.Linq ; using System.Reflection ; using System.Web.UI ; using System.Web.UI.WebControls ; namespace CASH.WebApplication.Controls { public partial class GenericTable : UserControl { private PropertyInfo [ ] properties ; //private GridView gridView ; private DataTable table = new DataTable ( ) ; private Dictionary < int , int > ingedrukt = new Dictionary < int , int > ( ) ; protected void Page_Init ( object sender , EventArgs e ) { grid.RowCommand += WeergaveDossiers_RowCommand ; } protected void Page_Load ( object sender , EventArgs e ) { if ( ! IsPostBack ) { for ( int i = 0 ; i < grid.Rows.Count ; i++ ) { grid.Rows [ i ] .Cells [ 0 ] .ColumnSpan = 0 ; } } else { properties = ( PropertyInfo [ ] ) Session [ `` properties '' ] ; table = ( DataTable ) Session [ `` table '' ] ; ingedrukt = ( Dictionary < int , int > ) Session [ `` ingedrukt '' ] ; foreach ( var knop in ingedrukt ) { DetailRijToevoegen ( knop.Key , knop.Value ) ; } } grid.DataBind ( ) ; } protected void SaveInSession ( ) { Session [ `` properties '' ] = properties ; Session [ `` table '' ] = table ; Session [ `` ingedrukt '' ] = ingedrukt ; } protected void WeergaveDossiers_RowCommand ( object sender , GridViewCommandEventArgs e ) { int row = int.Parse ( ( string ) e.CommandArgument ) + 1 ; int col = GetKolomIndex ( e.CommandName ) + 1 ; if ( ingedrukt.ContainsKey ( row ) ) { if ( ingedrukt [ row ] ! = col ) { //DetailRijVerwijderen ( row ) ; //ingedrukt.Remove ( row ) ; //ingedrukt [ row ] = col ; } } else { ingedrukt [ row ] = col ; } //DetailRijToevoegen ( row , col ) ; SaveInSession ( ) ; } protected void DetailRijToevoegen ( int row , int col ) { var data = table.NewRow ( ) ; var child = new GenericTable ( ) ; child.grid = new GridView ( ) ; data [ 0 ] = child ; table.Rows.InsertAt ( data , row ) ; grid.DataSource = table ; grid.DataBind ( ) ; var cells = grid.Rows [ row ] .Cells ; // Only keep the first cell while ( cells.Count > 1 ) { cells.RemoveAt ( 1 ) ; } child.MaakTable ( new List < object > ( ) { table.Rows [ row ] [ col ] } ) ; grid.Columns [ 0 ] .Visible = true ; grid.Rows [ row ] .Cells [ 0 ] .ColumnSpan = table.Columns.Count ; } protected void DetailRijVerwijderen ( int row ) { } protected int GetKolomIndex ( string naam ) { for ( int i = 0 ; i < properties.Length ; i++ ) { if ( properties [ i ] .Name == naam ) { return i ; } } throw new InvalidDataException ( `` Kolom naam `` + naam + `` niet bekend '' ) ; } public void MaakTable ( IEnumerable < object > data ) { properties = data.First ( ) .GetType ( ) .GetProperties ( ) .Where ( p = > p.CanRead ) .ToArray ( ) ; grid.AutoGenerateColumns = false ; var details = new BoundField ( ) ; details.DataField = `` Details '' ; grid.Columns.Add ( details ) ; table.Columns.Add ( new DataColumn ( `` Details '' , typeof ( object ) ) ) ; foreach ( var veld in properties ) { table.Columns.Add ( new DataColumn ( veld.Name , ( veld.Name == `` Id '' ? typeof ( object ) : veld.PropertyType ) ) ) ; grid.Columns.Add ( MaakKolom ( veld ) ) ; } foreach ( var entry in data ) { var row = table.NewRow ( ) ; int col = 0 ; foreach ( var veld in properties ) { row [ ++col ] = veld.GetValue ( entry ) ; } table.Rows.Add ( row ) ; } grid.DataSource = table ; SaveInSession ( ) ; } protected DataControlField MaakKolom ( PropertyInfo veld ) { DataControlField field ; if ( typeof ( Entity ) .IsAssignableFrom ( veld.PropertyType ) ) { field = new ButtonField ( ) ; ( ( ButtonField ) field ) .DataTextField = veld.Name ; ( ( ButtonField ) field ) .ButtonType = ButtonType.Button ; ( ( ButtonField ) field ) .CommandName = veld.Name ; } else if ( veld.PropertyType == typeof ( bool ) ) { field = new CheckBoxField ( ) ; ( ( CheckBoxField ) field ) .DataField = veld.Name ; } else if ( veld.PropertyType.IsEnum ) { field = new TemplateField ( ) ; // ( ( TemplateField ) field ) .ItemTemplate = ( ITemplate ) new Label ( ) // { // Text = `` # DataBinder.Eval ( \ '' '' + veld.Name + `` \ '' ) '' , // } ; } else if ( veld.PropertyType == typeof ( DateTime ) ) { field = new TemplateField ( ) ; //field.DatePicker = true ; } else { field = new BoundField ( ) ; ( ( BoundField ) field ) .DataField = veld.Name ; } field.HeaderText = veld.Name ; return field ; } protected void OnRowDataBound ( object sender , GridViewRowEventArgs e ) { if ( e.Row.RowType == DataControlRowType.DataRow ) { } } } } | Why are components of my custom control not initiated ? |
C_sharp : I am trying to write a single macro method in Kentico ( v8.2.x , or v9.0 ) that is cached appropriately , and exposes a POCO with a few public members.Debugging in Visual Studio , I can see that the query is running fine , and an object instance is returned exactly how I want . Furthermore , inspecting the cached items using the Debug application in Kentico also shows the full POCO instance data is cached as expected.However , when invoking the macro , I only seem to be able to read my string representation of the object.It is a macro that extends the CurrentUserInfo type , so I am trying to invoke it like this : But attempts to retrieve any of the nested properties fails.I am sure it is just that I have failed to do something ( like register these properties correctly ) . But from the documentation , I have seen lots of things that it could be . For example : Named sourceNamed callback sourceAnonymous sourceOr registering them as separate fields somehowHere is the macro itself : And the ClientInfo class is pretty straight-forward : What is the easiest way for me to be able to access the properties , in a manner similar to the following ? <code> { % CurrentUser.ClientStatus ( ) % } /// < summary > /// A class containing custom user-extension macros./// < /summary > [ assembly : RegisterExtension ( typeof ( CustomUserMacros ) , typeof ( CurrentUserInfo ) ) ] public class CustomUserMacros : MacroMethodContainer { /// < summary > /// Retrieves data regarding user client . /// < /summary > /// < param name= '' context '' > The context. < /param > /// < param name= '' parameters '' > The parameters. < /param > /// < returns > Data regarding user client information. < /returns > [ MacroMethod ( typeof ( ClientInfo ) , `` Retrieves client info . `` , 1 ) ] [ MacroMethodParam ( 0 , `` user '' , typeof ( CurrentUserInfo ) , `` The user . '' ) ] public static object ClientStatus ( EvaluationContext context , params object [ ] parameters ) { ClientInfo retVal = null ; if ( parameters ! = null & & parameters.Length > 0 & & parameters [ 0 ] .GetType ( ) == typeof ( CurrentUserInfo ) ) { var siteName = SiteContext.CurrentSiteName ; var userGuid = ( ( CurrentUserInfo ) parameters [ 0 ] ) .UserGUID ; var uInfo = UserInfoProvider.GetUserInfoByGUID ( userGuid ) ; retVal = CacheHelper.Cache ( cs = > new ClientInfo ( uInfo , siteName ) , new CacheSettings ( 60 , typeof ( CustomUserMacros ) , `` ClientStatus '' , userGuid ) ) ; } return retVal ; } } public class ClientInfo { public string Summary { get ; private set ; } public CustomTableItem ClientRecord { get ; private set ; } public IEnumerable < string > MediaPaths { get ; private set ; } public ClientInfo ( UserInfo userInfo , string siteCodeName ) { // ... // Set properties , etc ... } public override string ToString ( ) { return Summary ; } } { % CurrentUser.ClientStatus ( ) .ClientRecord [ `` < Column Name > '' ] % } | Accessing nested properties in a Kentico custom object macro method |
C_sharp : I ’ m trying to adhere to good OO design principles and design patterns and such . So while developing this C # application of mine I can often find multiple solutions to design and architecture issues , I always want to find and implement the more “ canonical ” one in the hopes of building highly maintainable and flexible software and also become a better OO programmer.So suppose I have these two abstract classes : Character and Weapon . Derived classes might be Sword and Staff from Weapon , and Warrior and Mage from Character , etc . ( this is all hypothetical , not related to my actual software ! ) .Every Character has a Weapon , but for every implementation of Character I know what implementation of Weapon it will have . For instance , I know ( and I want to enforce ! ) that at runtime every instance of Warrior will have a Weapon of type Sword . Of course I could do this : But this way , every time I want to use my Weapon object properly inside a Warrior , I have to perform a cast , which I believe to be a not so great of a practice . Also I have no means to prevent myself from messing up , that is , there is no type safety ! An ideal solution would be to be able to override the Weapon weapon property in the Warrior class with a Sword weapon property , that way I have type safety and if the user uses my Warrior as a Character , he can still use my Sword as a Weapon . Sadly , it doesn ’ t seem like C # supports this kind of construct.So here are my questions : is this some kind of classical OO problem , with a name and a well-documented solution ? In that case I would very much like to know the name of the problem and the solutions . Some links to good reading material would be very helpful ! If not , what kind of class design would you propose in order to maintain functionality and enforce type safety in an elegant and idiomatic way ? Thanks for reading ! <code> abstract class Weapon { public string Name { get ; set ; } } abstract class Character { public Weapon weapon { get ; set ; } } class Sword : Weapon { public void Draw ( ) { } } class Warrior : Character { public Warrior ( ) { weapon = new Sword ( ) ; } } | Enforcing type safety of inherited members in inherited classes |
C_sharp : How is it possible to read the values , let 's say : '99 ' from an assembly containing this code ? What I have done so farThe method in ILDASM : The compiler created the struct < PrivateImplementationDetails > { 975506E6-7C24-4C2B-8956-C1B9CF8B80C4 } with the field $ $ method0x6000001-1 for the initialization value and uses RuntimeHelpers.InitializeArray in order to initialize the new array at runtime . The original values defined in C # seem to be stored in the field and get copied by using the field handle ? But how are the values laid out ? There must be some better/easier way to read those constants from the assembly ? <code> using Sytem ; public class Class1 { public Class1 ( ) { // array initializer , want to read '99 ' , '100 ' ... from assembly var a = new double [ , ] { { 1 , 2 , 3 } , { 99 , 100 , 101 } } ; // ... } } .method /*06000001*/ public hidebysig specialname rtspecialname instance void .ctor ( ) cil managed// SIG : 20 00 01 { // Method begins at RVA 0x2080 // Code size 29 ( 0x1d ) .maxstack 3 .locals /*11000001*/ init ( [ 0 ] float64 [ 0 ... ,0 ... ] a ) .language ' { 3F5162F8-07C6-11D3-9053-00C04FA302A1 } ' , ' { 994B45C4-E6E9-11D2-903F-00C04FA302A1 } ' , ' { 5A869D0B-6611-11D3-BD2A-0000F80849BD } '// Source File ' c : \Users\heini19\Documents\Visual Studio 2013\Projects\WcfService1\ClassLibrary1\Class1.cs ' //000005 : public Class1 ( ) { IL_0000 : /* 02 | */ ldarg.0 IL_0001 : /* 28 | ( 0A ) 000011 */ call instance void [ mscorlib/*23000001*/ ] System.Object/*01000001*/ : :.ctor ( ) /* 0A000011 */ IL_0006 : /* 00 | */ nop IL_0007 : /* 00 | */ nop//000006 : // array initializer , want to read '99 ' , '100 ' etc.//000007 : var a = new double [ , ] { { 1 , 2 , 3 } , { 99 , 100 , 101 } } ; IL_0008 : /* 18 | */ ldc.i4.2 IL_0009 : /* 19 | */ ldc.i4.3 IL_000a : /* 73 | ( 0A ) 000012 */ newobj instance void float64 [ 0 ... ,0 ... ] /*1B000001*/ : :.ctor ( int32 , int32 ) /* 0A000012 */ IL_000f : /* 25 | */ dup IL_0010 : /* D0 | ( 04 ) 000001 */ ldtoken field valuetype ' < PrivateImplementationDetails > { 975506E6-7C24-4C2B-8956-C1B9CF8B80C4 } '/*02000003*//'__StaticArrayInitTypeSize=48'/*02000004*/ ' < PrivateImplementationDetails > { 975506E6-7C24-4C2B-8956-C1B9CF8B80C4 } '/*02000003*/ : : ' $ $ method0x6000001-1 ' /* 04000001 */ IL_0015 : /* 28 | ( 0A ) 000014 */ call void [ mscorlib/*23000001*/ ] System.Runtime.CompilerServices.RuntimeHelpers/*01000015*/ : :InitializeArray ( class [ mscorlib/*23000001*/ ] System.Array/*01000016*/ , valuetype [ mscorlib/*23000001*/ ] System.RuntimeFieldHandle/*01000017*/ ) /* 0A000014 */ IL_001a : /* 0A | */ stloc.0//000008 : // ... //000009 : } IL_001b : /* 00 | */ nop IL_001c : /* 2A | */ ret } // end of method Class1 : :.ctor | How to read array initializer values from .NET assembly |
C_sharp : For my application I 'd like to use all the built in manipulation possibilities , like e.g . zoom . But if the user presses 3 fingers on the screen I 'd like to show a specific UI element . So what is the best way to check if the user has pressed 3 fingers at the same time and next to each other on the screen ? ( without disabling the built-in manipulation possibilties ) .My first approach was to register the TouchDown event on the top Grid element of my layout . In the event handler I get the contact . But what to do there ? Just check if the contact is a fingerprint , store it in a List , and check if the list already contains two similar conacts ? Or is there a more sexy solution ? Thanks ! Edit : Following the answer i wrote two methods : They have to be rewritten , but it works . And the threshold ( atm 100 ) has to be adjusted . <code> private void OnContactDown ( object sender , ContactEventArgs e ) { if ( this.ContactsOver.Count == 3 ) { Console.WriteLine ( `` 3 contacts down . Check proximity '' ) ; if ( areNear ( this.ContactsOver ) ) { Console.WriteLine ( `` 3 fingers down ! `` ) ; } } } private Boolean areNear ( ReadOnlyContactCollection contacts ) { if ( Math.Abs ( contacts.ElementAt ( 0 ) .GetCenterPosition ( this ) .X - contacts.ElementAt ( 1 ) .GetCenterPosition ( this ) .X ) < 100 & & Math.Abs ( contacts.ElementAt ( 0 ) .GetCenterPosition ( this ) .Y - contacts.ElementAt ( 1 ) .GetCenterPosition ( this ) .Y ) < 100 & & Math.Abs ( contacts.ElementAt ( 1 ) .GetCenterPosition ( this ) .X - contacts.ElementAt ( 2 ) .GetCenterPosition ( this ) .X ) < 100 & & Math.Abs ( contacts.ElementAt ( 1 ) .GetCenterPosition ( this ) .Y - contacts.ElementAt ( 2 ) .GetCenterPosition ( this ) .Y ) < 100 & & Math.Abs ( contacts.ElementAt ( 0 ) .GetCenterPosition ( this ) .X - contacts.ElementAt ( 2 ) .GetCenterPosition ( this ) .X ) < 100 & & Math.Abs ( contacts.ElementAt ( 0 ) .GetCenterPosition ( this ) .Y - contacts.ElementAt ( 2 ) .GetCenterPosition ( this ) .Y ) < 100 ) { return true ; } else { return false ; } } | How to check if 3 fingers are placed on the screen |
C_sharp : I have run into a strange performance issue , and it would be great with an explanation to the behavior I 'm experiencing . I 'm using System.Drawing.Region.IsVisible ( PointF ) to determine if a point is inside a polygon . This usually works very well , but yesterday I noticed that the performance of the IsVisible method becomes very slow if the polygon is complex and it consists of large x- and y values . Below is some code to reproduce the issue ( and an image that shows the shape of the polygon ) , sorry for the large array sizes , but the polygon needs to be quite complex before the issue appears . When calling IsVisible on the original points my machine takes 460 651 milliseconds to finish , whereas when I first divide all points by 1000 , and then call the method , it takes 1 millisecond . Why I 'm I seeing such a big difference in the timing ? I did not think the actual values of a float would affect performance . <code> using System ; using System.Diagnostics ; using System.Drawing ; using System.Drawing.Drawing2D ; using System.Linq ; namespace PerformanceTest { class Program { static void Main ( string [ ] args ) { // Create complex polygon with large x and y values float [ ] xValues = { 1.014498E+07f , 1.016254E+07f , 1.019764E+07f , 1.021519E+07f , 1.023274E+07f , 1.026785E+07f , 1.026785E+07f , 1.02854E+07f , 1.02854E+07f , 1.030295E+07f , 1.03205E+07f , 1.033805E+07f , 1.035561E+07f , 1.037316E+07f , 1.039071E+07f , 1.040826E+07f , 1.042581E+07f , 1.044337E+07f , 1.046092E+07f , 1.047847E+07f , 1.049602E+07f , 1.051357E+07f , 1.054868E+07f , 1.056623E+07f , 1.058378E+07f , 1.060133E+07f , 1.061888E+07f , 1.061888E+07f , 1.063644E+07f , 1.065399E+07f , 1.068909E+07f , 1.068909E+07f , 1.070664E+07f , 1.07242E+07f , 1.074175E+07f , 1.074175E+07f , 1.07593E+07f , 1.07593E+07f , 1.077685E+07f , 1.07944E+07f , 1.07944E+07f , 1.081196E+07f , 1.081196E+07f , 1.081196E+07f , 1.082951E+07f , 1.084706E+07f , 1.084706E+07f , 1.086461E+07f , 1.086461E+07f , 1.088216E+07f , 1.089971E+07f , 1.091727E+07f , 1.093482E+07f , 1.098747E+07f , 1.100503E+07f , 1.102258E+07f , 1.104013E+07f , 1.105768E+07f , 1.107523E+07f , 1.107523E+07f , 1.109279E+07f , 1.109279E+07f , 1.109279E+07f , 1.109279E+07f , 1.109279E+07f , 1.111034E+07f , 1.111034E+07f , 1.111034E+07f , 1.111034E+07f , 1.111034E+07f , 1.112789E+07f , 1.112789E+07f , 1.112789E+07f , 1.114544E+07f , 1.116299E+07f , 1.118054E+07f , 1.11981E+07f , 1.12332E+07f , 1.125075E+07f , 1.12683E+07f , 1.128586E+07f , 1.130341E+07f , 1.135606E+07f , 1.137361E+07f , 1.139117E+07f , 1.140872E+07f , 1.144382E+07f , 1.146137E+07f , 1.147893E+07f , 1.149648E+07f , 1.151403E+07f , 1.153158E+07f , 1.154913E+07f , 1.156669E+07f , 1.156669E+07f , 1.158424E+07f , 1.158424E+07f , 1.158424E+07f , 1.158424E+07f , 1.158424E+07f , 1.158424E+07f , 1.158424E+07f , 1.158424E+07f , 1.158424E+07f , 1.158424E+07f , 1.158424E+07f , 1.156669E+07f , 1.156669E+07f , 1.151403E+07f , 1.149648E+07f , 1.149648E+07f , 1.149648E+07f , 1.149648E+07f , 1.149648E+07f , 1.149648E+07f , 1.149648E+07f , 1.149648E+07f , 1.149648E+07f , 1.153158E+07f , 1.154913E+07f , 1.156669E+07f , 1.156669E+07f , 1.158424E+07f , 1.160179E+07f , 1.160179E+07f , 1.161934E+07f , 1.165444E+07f , 1.1672E+07f , 1.168955E+07f , 1.17071E+07f , 1.172465E+07f , 1.17422E+07f , 1.175976E+07f , 1.177731E+07f , 1.179486E+07f , 1.181241E+07f , 1.182996E+07f , 1.184752E+07f , 1.186507E+07f , 1.188262E+07f , 1.190017E+07f , 1.190017E+07f , 1.191772E+07f , 1.191772E+07f , 1.193528E+07f , 1.193528E+07f , 1.193528E+07f , 1.193528E+07f , 1.193528E+07f , 1.193528E+07f , 1.193528E+07f , 1.193528E+07f , 1.193528E+07f , 1.193528E+07f , 1.193528E+07f , 1.193528E+07f , 1.193528E+07f , 1.193528E+07f , 1.193528E+07f , 1.193528E+07f , 1.193528E+07f , 1.193528E+07f , 1.193528E+07f , 1.193528E+07f , 1.195283E+07f , 1.197038E+07f , 1.198793E+07f , 1.200548E+07f , 1.202303E+07f , 1.204059E+07f , 1.205814E+07f , 1.207569E+07f , 1.209324E+07f , 1.211079E+07f , 1.212835E+07f , 1.21459E+07f , 1.216345E+07f , 1.2181E+07f , 1.219855E+07f , 1.221611E+07f , 1.221611E+07f , 1.223366E+07f , 1.225121E+07f , 1.226876E+07f , 1.226876E+07f , 1.228631E+07f , 1.230386E+07f , 1.230386E+07f , 1.230386E+07f , 1.232142E+07f , 1.232142E+07f , 1.232142E+07f , 1.232142E+07f , 1.232142E+07f , 1.232142E+07f , 1.232142E+07f , 1.232142E+07f , 1.235652E+07f , 1.235652E+07f , 1.237407E+07f , 1.237407E+07f , 1.239162E+07f , 1.239162E+07f , 1.240918E+07f , 1.242673E+07f , 1.242673E+07f , 1.244428E+07f , 1.247938E+07f , 1.249694E+07f , 1.251449E+07f , 1.253204E+07f , 1.254959E+07f , 1.256714E+07f , 1.258469E+07f , 1.260225E+07f , 1.263735E+07f , 1.26549E+07f , 1.267245E+07f , 1.269001E+07f , 1.270756E+07f , 1.272511E+07f , 1.272511E+07f , 1.274266E+07f , 1.274266E+07f , 1.276021E+07f , 1.276021E+07f , 1.277776E+07f , 1.277776E+07f , 1.277776E+07f , 1.277776E+07f , 1.279532E+07f , 1.279532E+07f , 1.279532E+07f , 1.281287E+07f , 1.281287E+07f , 1.281287E+07f , 1.281287E+07f , 1.281287E+07f , 1.281287E+07f , 1.281287E+07f , 1.281287E+07f , 1.281287E+07f , 1.281287E+07f , 1.281287E+07f , 1.281287E+07f , 1.281287E+07f , 1.281287E+07f , 1.281287E+07f , 1.279532E+07f , 1.277776E+07f , 1.276021E+07f , 1.276021E+07f , 1.274266E+07f , 1.274266E+07f , 1.272511E+07f , 1.272511E+07f , 1.272511E+07f , 1.274266E+07f , 1.276021E+07f , 1.279532E+07f , 1.281287E+07f , 1.283042E+07f , 1.284797E+07f , 1.286552E+07f , 1.288308E+07f , 1.290063E+07f , 1.291818E+07f , 1.293573E+07f , 1.295328E+07f , 1.295328E+07f , 1.297084E+07f , 1.297084E+07f , 1.298839E+07f , 1.298839E+07f , 1.298839E+07f , 1.298839E+07f , 1.298839E+07f , 1.298839E+07f , 1.298839E+07f , 1.298839E+07f , 1.298839E+07f , 1.298839E+07f , 1.298839E+07f , 1.298839E+07f , 1.298839E+07f , 1.298839E+07f , 1.298839E+07f , 1.298839E+07f , 1.298839E+07f , 1.298839E+07f , 1.298839E+07f , 1.298839E+07f , 1.298839E+07f , 1.298839E+07f , 1.300594E+07f , 1.300594E+07f , 1.302349E+07f , 1.304104E+07f , 1.305859E+07f , 1.30937E+07f , 1.311125E+07f , 1.31288E+07f , 1.314635E+07f , 1.316391E+07f , 1.318146E+07f , 1.319901E+07f , 1.321656E+07f , 1.323411E+07f , 1.325167E+07f , 1.325167E+07f , 1.326922E+07f , 1.326922E+07f , 1.328677E+07f , 1.330432E+07f , 1.330432E+07f , 1.330432E+07f , 1.332187E+07f , 1.333943E+07f , 1.335698E+07f , 1.335698E+07f , 1.337453E+07f , 1.339208E+07f , 1.340963E+07f , 1.340963E+07f , 1.342718E+07f , 1.344474E+07f , 1.346229E+07f , 1.347984E+07f , 1.349739E+07f , 1.351494E+07f , 1.355005E+07f , 1.35676E+07f , 1.36027E+07f , 1.363781E+07f , 1.367291E+07f , 1.367291E+07f , 1.370801E+07f , 1.372557E+07f , 1.376067E+07f , 1.377822E+07f , 1.381333E+07f , 1.383088E+07f , 1.384843E+07f , 1.386598E+07f , 1.390109E+07f , 1.391864E+07f , 1.391864E+07f , 1.393619E+07f , 1.395374E+07f , 1.397129E+07f , 1.398884E+07f , 1.40064E+07f , 1.402395E+07f , 1.405905E+07f , 1.409416E+07f , 1.412926E+07f , 1.414681E+07f , 1.418191E+07f , 1.419947E+07f , 1.421702E+07f , 1.423457E+07f , 1.426967E+07f , 1.430478E+07f , 1.433988E+07f , 1.435743E+07f , 1.437499E+07f , 1.439254E+07f , 1.439254E+07f , 1.442764E+07f , 1.442764E+07f , 1.444519E+07f , 1.446274E+07f , 1.446274E+07f , 1.446274E+07f , 1.446274E+07f , 1.446274E+07f , 1.446274E+07f , 1.446274E+07f , 1.446274E+07f , 1.446274E+07f , 1.446274E+07f , 1.446274E+07f , 1.444519E+07f , 1.442764E+07f , 1.441009E+07f , 1.439254E+07f , 1.437499E+07f , 1.435743E+07f , 1.433988E+07f , 1.432233E+07f , 1.430478E+07f , 1.430478E+07f , 1.426967E+07f , 1.426967E+07f , 1.423457E+07f , 1.421702E+07f , 1.418191E+07f , 1.414681E+07f , 1.412926E+07f , 1.409416E+07f , 1.405905E+07f , 1.402395E+07f , 1.40064E+07f , 1.395374E+07f , 1.393619E+07f , 1.391864E+07f , 1.390109E+07f , 1.390109E+07f , 1.388353E+07f , 1.388353E+07f , 1.388353E+07f , 1.388353E+07f , 1.388353E+07f , 1.388353E+07f , 1.388353E+07f , 1.388353E+07f , 1.388353E+07f , 1.388353E+07f , 1.390109E+07f , 1.391864E+07f , 1.393619E+07f , 1.395374E+07f , 1.398884E+07f , 1.398884E+07f , 1.40064E+07f , 1.402395E+07f , 1.402395E+07f , 1.40415E+07f , 1.405905E+07f , 1.40766E+07f , 1.412926E+07f , 1.414681E+07f , 1.416436E+07f , 1.418191E+07f , 1.419947E+07f , 1.421702E+07f , 1.423457E+07f , 1.423457E+07f , 1.423457E+07f , 1.423457E+07f , 1.423457E+07f , 1.423457E+07f , 1.423457E+07f , 1.423457E+07f , 1.423457E+07f , 1.423457E+07f , 1.423457E+07f , 1.423457E+07f , 1.423457E+07f , 1.421702E+07f , 1.419947E+07f , 1.418191E+07f , 1.416436E+07f , 1.416436E+07f , 1.412926E+07f , 1.411171E+07f , 1.409416E+07f , 1.40766E+07f , 1.405905E+07f , 1.40415E+07f , 1.402395E+07f , 1.40064E+07f , 1.397129E+07f , 1.397129E+07f , 1.395374E+07f , 1.393619E+07f , 1.393619E+07f , 1.391864E+07f , 1.391864E+07f , 1.390109E+07f , 1.388353E+07f , 1.388353E+07f , 1.386598E+07f , 1.384843E+07f , 1.383088E+07f , 1.379577E+07f , 1.376067E+07f , 1.372557E+07f , 1.370801E+07f , 1.369046E+07f , 1.365536E+07f , 1.363781E+07f , 1.362026E+07f , 1.36027E+07f , 1.358515E+07f , 1.35676E+07f , 1.35325E+07f , 1.351494E+07f , 1.349739E+07f , 1.347984E+07f , 1.346229E+07f , 1.344474E+07f , 1.339208E+07f , 1.337453E+07f , 1.335698E+07f , 1.333943E+07f , 1.332187E+07f , 1.332187E+07f , 1.330432E+07f , 1.326922E+07f , 1.325167E+07f , 1.323411E+07f , 1.321656E+07f , 1.319901E+07f , 1.316391E+07f , 1.314635E+07f , 1.31288E+07f , 1.311125E+07f , 1.307615E+07f , 1.304104E+07f , 1.302349E+07f , 1.300594E+07f , 1.300594E+07f , 1.300594E+07f , 1.300594E+07f , 1.300594E+07f , 1.300594E+07f , 1.300594E+07f , 1.302349E+07f , 1.304104E+07f , 1.307615E+07f , 1.30937E+07f , 1.311125E+07f , 1.314635E+07f , 1.316391E+07f , 1.318146E+07f , 1.319901E+07f , 1.321656E+07f , 1.323411E+07f , 1.323411E+07f , 1.323411E+07f , 1.323411E+07f , 1.325167E+07f , 1.325167E+07f , 1.325167E+07f , 1.325167E+07f , 1.325167E+07f , 1.325167E+07f , 1.325167E+07f , 1.325167E+07f , 1.325167E+07f , 1.325167E+07f , 1.325167E+07f , 1.325167E+07f , 1.325167E+07f , 1.325167E+07f , 1.323411E+07f , 1.323411E+07f , 1.321656E+07f , 1.319901E+07f , 1.318146E+07f , 1.316391E+07f , 1.314635E+07f , 1.31288E+07f , 1.305859E+07f , 1.304104E+07f , 1.298839E+07f , 1.295328E+07f , 1.291818E+07f , 1.288308E+07f , 1.286552E+07f , 1.284797E+07f , 1.283042E+07f , 1.279532E+07f , 1.277776E+07f , 1.276021E+07f , 1.272511E+07f , 1.270756E+07f , 1.269001E+07f , 1.26549E+07f , 1.263735E+07f , 1.260225E+07f , 1.258469E+07f , 1.256714E+07f , 1.256714E+07f , 1.254959E+07f , 1.253204E+07f , 1.253204E+07f , 1.253204E+07f , 1.251449E+07f , 1.251449E+07f , 1.251449E+07f , 1.251449E+07f , 1.251449E+07f , 1.249694E+07f , 1.249694E+07f , 1.249694E+07f , 1.249694E+07f , 1.247938E+07f , 1.247938E+07f , 1.246183E+07f , 1.244428E+07f , 1.240918E+07f , 1.239162E+07f , 1.235652E+07f , 1.233897E+07f , 1.230386E+07f , 1.226876E+07f , 1.225121E+07f , 1.221611E+07f , 1.219855E+07f , 1.219855E+07f , 1.2181E+07f , 1.216345E+07f , 1.216345E+07f , 1.21459E+07f , 1.21459E+07f , 1.212835E+07f , 1.212835E+07f , 1.212835E+07f , 1.212835E+07f , 1.212835E+07f , 1.211079E+07f , 1.211079E+07f , 1.211079E+07f , 1.211079E+07f , 1.211079E+07f , 1.211079E+07f , 1.211079E+07f , 1.211079E+07f , 1.211079E+07f , 1.211079E+07f , 1.211079E+07f , 1.211079E+07f , 1.211079E+07f , 1.211079E+07f , 1.211079E+07f , 1.211079E+07f , 1.211079E+07f , 1.211079E+07f , 1.211079E+07f , 1.209324E+07f , 1.207569E+07f , 1.207569E+07f , 1.204059E+07f , 1.202303E+07f , 1.200548E+07f , 1.198793E+07f , 1.197038E+07f , 1.195283E+07f , 1.193528E+07f , 1.191772E+07f , 1.190017E+07f , 1.188262E+07f , 1.186507E+07f , 1.181241E+07f , 1.181241E+07f , 1.179486E+07f , 1.177731E+07f , 1.177731E+07f , 1.177731E+07f , 1.175976E+07f , 1.175976E+07f , 1.17422E+07f , 1.17422E+07f , 1.17422E+07f , 1.17422E+07f , 1.17422E+07f , 1.17422E+07f , 1.172465E+07f , 1.172465E+07f , 1.172465E+07f , 1.172465E+07f , 1.172465E+07f , 1.172465E+07f , 1.172465E+07f , 1.172465E+07f , 1.172465E+07f , 1.172465E+07f , 1.17071E+07f , 1.168955E+07f , 1.1672E+07f , 1.163689E+07f , 1.161934E+07f , 1.160179E+07f , 1.156669E+07f , 1.154913E+07f , 1.151403E+07f , 1.149648E+07f , 1.147893E+07f , 1.146137E+07f , 1.144382E+07f , 1.144382E+07f , 1.139117E+07f , 1.139117E+07f , 1.137361E+07f , 1.137361E+07f , 1.137361E+07f , 1.137361E+07f , 1.137361E+07f , 1.137361E+07f , 1.135606E+07f , 1.135606E+07f , 1.135606E+07f , 1.135606E+07f , 1.135606E+07f , 1.135606E+07f , 1.135606E+07f , 1.135606E+07f , 1.135606E+07f , 1.135606E+07f , 1.133851E+07f , 1.133851E+07f , 1.133851E+07f , 1.133851E+07f , 1.133851E+07f , 1.130341E+07f , 1.130341E+07f , 1.128586E+07f , 1.12683E+07f , 1.125075E+07f , 1.121565E+07f , 1.116299E+07f , 1.112789E+07f , 1.107523E+07f , 1.105768E+07f , 1.102258E+07f , 1.098747E+07f , 1.095237E+07f , 1.091727E+07f , 1.089971E+07f , 1.088216E+07f , 1.086461E+07f , 1.082951E+07f , 1.081196E+07f , 1.081196E+07f , 1.07944E+07f , 1.07944E+07f , 1.077685E+07f , 1.07593E+07f , 1.07593E+07f , 1.074175E+07f , 1.074175E+07f , 1.074175E+07f , 1.074175E+07f , 1.074175E+07f , 1.074175E+07f , 1.074175E+07f , 1.074175E+07f , 1.074175E+07f , 1.07593E+07f , 1.07593E+07f , 1.077685E+07f , 1.07944E+07f , 1.07944E+07f , 1.081196E+07f , 1.082951E+07f , 1.082951E+07f , 1.086461E+07f , 1.088216E+07f , 1.089971E+07f , 1.089971E+07f , 1.091727E+07f , 1.091727E+07f , 1.091727E+07f , 1.091727E+07f , 1.091727E+07f , 1.091727E+07f , 1.089971E+07f , 1.088216E+07f , 1.082951E+07f , 1.07944E+07f , 1.07593E+07f , 1.070664E+07f , 1.068909E+07f , 1.067154E+07f , 1.065399E+07f , 1.063644E+07f , 1.061888E+07f , 1.060133E+07f , 1.058378E+07f , 1.056623E+07f , 1.054868E+07f , 1.051357E+07f , 1.049602E+07f , 1.047847E+07f , 1.046092E+07f , 1.042581E+07f , 1.039071E+07f , 1.030295E+07f , 1.026785E+07f , 1.023274E+07f , 1.019764E+07f , 1.018009E+07f , 1.016254E+07f , 1.014498E+07f , 1.010988E+07f , 1.009233E+07f , 1.007478E+07f , 1.005722E+07f , 1.003967E+07f , 1.002212E+07f , 9969464f , 9916809f , 9881705f , 9864154f , 9846602f , 9829050f , 9811497f , 9793945f , 9776394f , 9741290f , 9723738f , 9688635f , 9653531f , 9653531f , 9618427f , 9618427f , 9600875f , 9600875f , 9600875f , 9583323f , 9565771f , 9565771f , 9530667f , 9530667f , 9530667f , 9530667f , 9530667f , 9530667f , 9530667f , 9530667f , 9548219f , 9565771f , 9583323f , 9618427f , 9653531f , 9671083f , 9688635f , 9706186f , 9741290f , 9758842f , 9811497f , 9829050f , 9864154f , 9881705f , 9916809f , 9934361f , 9951913f , 9987016f , 1.000457E+07f , 1.003967E+07f , 1.005722E+07f , 1.007478E+07f , 1.010988E+07f , 1.014498E+07f , 1.016254E+07f , 1.016254E+07f , 1.018009E+07f , 1.019764E+07f , 1.021519E+07f , 1.023274E+07f , 1.023274E+07f , 1.023274E+07f , 1.023274E+07f , 1.023274E+07f , 1.023274E+07f , 1.023274E+07f , 1.023274E+07f , 1.021519E+07f , 1.019764E+07f , 1.016254E+07f , 1.014498E+07f , 1.012743E+07f , 1.009233E+07f , 1.003967E+07f , 1.000457E+07f , 9951913f , 9934361f , 9899257f , 9881705f , 9864154f , 9846602f , 9829050f , 9793945f , 9758842f , 9723738f , 9688635f , 9653531f , 9635979f , 9618427f , 9583323f , 9565771f , 9530667f , 9513116f , 9495564f , 9478012f , 9460460f , 9460460f , 9442908f , 9425357f , 9425357f , 9407805f , 9390253f , 9390253f , 9372701f , 9372701f , 9372701f , 9372701f , 9372701f , 9372701f , 9372701f , 9372701f , 9372701f , 9372701f , 9372701f , 9372701f , 9390253f , 9407805f , 9425357f , 9460460f , 9495564f , 9513116f , 9583323f , 9600875f , 9635979f , 9653531f , 9688635f , 9706186f , 9723738f , 9758842f , 9793945f , 9811497f , 9846602f } ; float [ ] yValues = { 7286825f , 7286825f , 7269351f , 7269351f , 7269351f , 7269351f , 7251876f , 7251876f , 7234401f , 7234401f , 7234401f , 7234401f , 7234401f , 7234401f , 7234401f , 7234401f , 7234401f , 7234401f , 7234401f , 7234401f , 7234401f , 7216927f , 7199453f , 7181979f , 7181979f , 7164504f , 7164504f , 7147029f , 7129555f , 7112081f , 7077132f , 7042183f , 7024709f , 7007235f , 6972285f , 6954811f , 6937337f , 6919863f , 6902388f , 6884913f , 6867439f , 6867439f , 6832491f , 6815016f , 6797541f , 6780067f , 6762593f , 6762593f , 6745119f , 6745119f , 6727644f , 6727644f , 6710169f , 6710169f , 6710169f , 6710169f , 6710169f , 6710169f , 6710169f , 6727644f , 6762593f , 6780067f , 6832491f , 6849965f , 6867439f , 6902388f , 6937337f , 6954811f , 6972285f , 6989760f , 7024709f , 7042183f , 7077132f , 7094607f , 7112081f , 7129555f , 7129555f , 7129555f , 7129555f , 7129555f , 7129555f , 7147029f , 7147029f , 7147029f , 7147029f , 7147029f , 7147029f , 7147029f , 7147029f , 7147029f , 7147029f , 7147029f , 7147029f , 7147029f , 7129555f , 7112081f , 7077132f , 7059657f , 7007235f , 6972285f , 6954811f , 6937337f , 6902388f , 6867439f , 6832491f , 6815016f , 6797541f , 6780067f , 6710169f , 6710169f , 6692695f , 6675221f , 6640272f , 6622797f , 6605323f , 6587849f , 6570375f , 6535425f , 6517951f , 6500477f , 6483003f , 6465528f , 6448053f , 6448053f , 6430579f , 6430579f , 6413105f , 6413105f , 6413105f , 6413105f , 6413105f , 6413105f , 6413105f , 6413105f , 6413105f , 6413105f , 6413105f , 6413105f , 6413105f , 6413105f , 6430579f , 6448053f , 6483003f , 6500477f , 6552900f , 6570375f , 6622797f , 6640272f , 6657747f , 6675221f , 6692695f , 6710169f , 6745119f , 6762593f , 6780067f , 6797541f , 6849965f , 6867439f , 6902388f , 6954811f , 6972285f , 6989760f , 7007235f , 7042183f , 7059657f , 7059657f , 7059657f , 7059657f , 7059657f , 7059657f , 7059657f , 7059657f , 7059657f , 7059657f , 7059657f , 7059657f , 7059657f , 7059657f , 7059657f , 7059657f , 7042183f , 7042183f , 7024709f , 7007235f , 6989760f , 6989760f , 6972285f , 6954811f , 6937337f , 6919863f , 6902388f , 6867439f , 6832491f , 6815016f , 6797541f , 6780067f , 6762593f , 6745119f , 6727644f , 6710169f , 6692695f , 6675221f , 6657747f , 6657747f , 6640272f , 6622797f , 6622797f , 6622797f , 6622797f , 6622797f , 6622797f , 6622797f , 6622797f , 6622797f , 6622797f , 6640272f , 6657747f , 6692695f , 6692695f , 6710169f , 6727644f , 6745119f , 6762593f , 6780067f , 6780067f , 6797541f , 6815016f , 6832491f , 6849965f , 6867439f , 6884913f , 6902388f , 6919863f , 6937337f , 6954811f , 6972285f , 6989760f , 7007235f , 7024709f , 7042183f , 7059657f , 7077132f , 7094607f , 7112081f , 7129555f , 7147029f , 7164504f , 7181979f , 7199453f , 7234401f , 7234401f , 7251876f , 7251876f , 7269351f , 7286825f , 7304299f , 7321773f , 7321773f , 7321773f , 7321773f , 7321773f , 7321773f , 7321773f , 7321773f , 7321773f , 7321773f , 7321773f , 7304299f , 7286825f , 7269351f , 7251876f , 7234401f , 7216927f , 7199453f , 7181979f , 7164504f , 7147029f , 7129555f , 7112081f , 7094607f , 7077132f , 7042183f , 7024709f , 7007235f , 6989760f , 6954811f , 6937337f , 6919863f , 6902388f , 6849965f , 6832491f , 6815016f , 6797541f , 6780067f , 6780067f , 6762593f , 6762593f , 6762593f , 6745119f , 6745119f , 6745119f , 6745119f , 6745119f , 6745119f , 6762593f , 6762593f , 6797541f , 6832491f , 6867439f , 6884913f , 6884913f , 6919863f , 6954811f , 6954811f , 6972285f , 6989760f , 7007235f , 7042183f , 7042183f , 7059657f , 7077132f , 7094607f , 7094607f , 7112081f , 7112081f , 7112081f , 7112081f , 7112081f , 7112081f , 7112081f , 7112081f , 7112081f , 7112081f , 7112081f , 7094607f , 7077132f , 7042183f , 7024709f , 7024709f , 7007235f , 6989760f , 6989760f , 6972285f , 6954811f , 6937337f , 6937337f , 6919863f , 6902388f , 6902388f , 6902388f , 6902388f , 6902388f , 6902388f , 6902388f , 6902388f , 6902388f , 6902388f , 6902388f , 6902388f , 6902388f , 6902388f , 6902388f , 6919863f , 6919863f , 6954811f , 6972285f , 6972285f , 6989760f , 7024709f , 7042183f , 7059657f , 7094607f , 7112081f , 7129555f , 7164504f , 7181979f , 7199453f , 7234401f , 7251876f , 7269351f , 7286825f , 7321773f , 7321773f , 7339248f , 7339248f , 7356723f , 7374197f , 7374197f , 7374197f , 7374197f , 7374197f , 7391671f , 7391671f , 7409145f , 7409145f , 7426620f , 7426620f , 7426620f , 7444095f , 7444095f , 7461569f , 7479043f , 7496517f , 7513992f , 7513992f , 7513992f , 7531467f , 7548941f , 7548941f , 7566415f , 7601364f , 7618839f , 7636313f , 7653787f , 7671261f , 7688736f , 7706211f , 7741159f , 7793583f , 7828531f , 7846005f , 7880955f , 7880955f , 7898429f , 7898429f , 7915903f , 7933377f , 7933377f , 7950852f , 7950852f , 7950852f , 7950852f , 7950852f , 7950852f , 7950852f , 7968327f , 7985801f , 8003275f , 8020749f , 8038224f , 8055699f , 8073173f , 8090647f , 8108121f , 8125596f , 8160545f , 8178019f , 8195493f , 8212968f , 8212968f , 8230443f , 8247917f , 8265391f , 8282865f , 8282865f , 8282865f , 8282865f , 8282865f , 8282865f , 8282865f , 8282865f , 8265391f , 8230443f , 8212968f , 8195493f , 8178019f , 8160545f , 8160545f , 8143071f , 8143071f , 8125596f , 8108121f , 8108121f , 8090647f , 8090647f , 8073173f , 8038224f , 8038224f , 8020749f , 8020749f , 8003275f , 7985801f , 7985801f , 7968327f , 7950852f , 7950852f , 7933377f , 7933377f , 7933377f , 7933377f , 7915903f , 7898429f , 7898429f , 7898429f , 7898429f , 7898429f , 7898429f , 7880955f , 7880955f , 7880955f , 7880955f , 7880955f , 7880955f , 7880955f , 7880955f , 7880955f , 7880955f , 7880955f , 7898429f , 7898429f , 7933377f , 7968327f , 7985801f , 8003275f , 8020749f , 8055699f , 8073173f , 8108121f , 8108121f , 8143071f , 8178019f , 8178019f , 8212968f , 8212968f , 8230443f , 8247917f , 8265391f , 8282865f , 8282865f , 8317815f , 8335289f , 8352763f , 8387712f , 8405186f , 8422661f , 8440134f , 8457609f , 8475084f , 8510033f , 8527506f , 8544981f , 8562456f , 8614878f , 8632353f , 8667302f , 8684777f , 8737200f , 8772149f , 8789622f , 8824572f , 8842046f , 8859521f , 8876994f , 8894469f , 8929418f , 8929418f , 8946893f , 8946893f , 8946893f , 8946893f , 8946893f , 8946893f , 8946893f , 8946893f , 8946893f , 8946893f , 8911944f , 8894469f , 8859521f , 8824572f , 8789622f , 8772149f , 8702250f , 8684777f , 8667302f , 8632353f , 8614878f , 8597405f , 8562456f , 8544981f , 8510033f , 8492558f , 8475084f , 8457609f , 8440134f , 8422661f , 8405186f , 8387712f , 8370237f , 8352763f , 8352763f , 8352763f , 8352763f , 8352763f , 8352763f , 8352763f , 8352763f , 8352763f , 8352763f , 8370237f , 8370237f , 8387712f , 8387712f , 8405186f , 8422661f , 8422661f , 8440134f , 8457609f , 8492558f , 8527506f , 8544981f , 8562456f , 8579930f , 8597405f , 8614878f , 8632353f , 8649828f , 8667302f , 8702250f , 8719725f , 8737200f , 8772149f , 8789622f , 8807097f , 8824572f , 8842046f , 8876994f , 8894469f , 8911944f , 8929418f , 8946893f , 8964366f , 8964366f , 8981841f , 8999316f , 9016790f , 9034265f , 9034265f , 9051738f , 9051738f , 9051738f , 9051738f , 9051738f , 9051738f , 9051738f , 9016790f , 8999316f , 8964366f , 8946893f , 8929418f , 8911944f , 8876994f , 8859521f , 8842046f , 8824572f , 8807097f , 8789622f , 8772149f , 8754674f , 8702250f , 8667302f , 8649828f , 8632353f , 8614878f , 8597405f , 8579930f , 8562456f , 8544981f , 8510033f , 8492558f , 8492558f , 8492558f , 8492558f , 8492558f , 8492558f , 8492558f , 8492558f , 8492558f , 8492558f , 8492558f , 8492558f , 8510033f , 8544981f , 8544981f , 8562456f , 8562456f , 8597405f , 8614878f , 8632353f , 8667302f , 8702250f , 8719725f , 8754674f , 8789622f , 8824572f , 8842046f , 8859521f , 8876994f , 8911944f , 8929418f , 8964366f , 8964366f , 8999316f , 9016790f , 9034265f , 9086688f , 9104162f , 9139110f , 9156585f , 9174060f , 9209009f , 9243957f , 9261432f , 9261432f , 9261432f , 9261432f , 9261432f , 9261432f , 9261432f , 9261432f , 9261432f , 9261432f , 9261432f , 9243957f , 9226482f , 9191534f , 9174060f , 9156585f , 9086688f , 9051738f , 9034265f , 8999316f , 8981841f , 8964366f , 8929418f , 8894469f , 8876994f , 8842046f , 8824572f , 8807097f , 8789622f , 8772149f , 8754674f , 8702250f , 8684777f , 8667302f , 8667302f , 8649828f , 8614878f , 8597405f , 8579930f , 8562456f , 8562456f , 8527506f , 8510033f , 8492558f , 8475084f , 8440134f , 8422661f , 8422661f , 8387712f , 8370237f , 8370237f , 8370237f , 8370237f , 8370237f , 8335289f , 8335289f , 8335289f , 8335289f , 8335289f , 8335289f , 8335289f , 8335289f , 8335289f , 8335289f , 8335289f , 8352763f , 8370237f , 8405186f , 8440134f , 8457609f , 8492558f , 8510033f , 8527506f , 8562456f , 8579930f , 8597405f , 8597405f , 8632353f , 8632353f , 8667302f , 8702250f , 8719725f , 8754674f , 8754674f , 8754674f , 8754674f , 8754674f , 8754674f , 8754674f , 8754674f , 8737200f , 8719725f , 8702250f , 8684777f , 8667302f , 8649828f , 8632353f , 8614878f , 8562456f , 8527506f , 8440134f , 8422661f , 8387712f , 8352763f , 8317815f , 8300340f , 8282865f , 8265391f , 8247917f , 8212968f , 8212968f , 8160545f , 8143071f , 8125596f , 8108121f , 8108121f , 8090647f , 8090647f , 8073173f , 8073173f , 8055699f , 8055699f , 8055699f , 8038224f , 8038224f , 8038224f , 8038224f , 8038224f , 8020749f , 8020749f , 8003275f , 8003275f , 7985801f , 7950852f , 7933377f , 7915903f , 7915903f , 7880955f , 7863480f , 7846005f , 7828531f , 7793583f , 7776108f , 7758633f , 7741159f , 7723685f , 7706211f , 7706211f , 7706211f , 7706211f , 7706211f , 7706211f , 7706211f , 7706211f , 7706211f , 7706211f , 7706211f , 7706211f , 7723685f , 7723685f , 7741159f , 7741159f , 7741159f , 7741159f , 7741159f , 7741159f , 7741159f , 7741159f , 7741159f , 7741159f , 7741159f , 7741159f , 7741159f , 7741159f , 7741159f , 7741159f , 7723685f , 7723685f , 7688736f , 7671261f , 7653787f , 7583889f , 7566415f , 7513992f , 7461569f , 7444095f , 7409145f , 7374197f , 7356723f , 7321773f , 7304299f , 7286825f , 7269351f , 7251876f , 7234401f , 7199453f , 7181979f , 7164504f , 7164504f , 7164504f , 7164504f , 7164504f , 7164504f , 7164504f , 7164504f , 7164504f , 7164504f , 7164504f , 7164504f , 7164504f , 7181979f , 7199453f } ; PointF [ ] points = xValues.Zip ( yValues , ( x , y ) = > new PointF ( x , y ) ) .ToArray ( ) ; // Create a region with the original values GraphicsPath pathWithOriginalPoints = new GraphicsPath ( ) ; pathWithOriginalPoints.AddPolygon ( points ) ; Region regionFromOriginalPoints = new Region ( pathWithOriginalPoints ) ; // Create a region with the values divided by 1000 GraphicsPath pathDividedBy1000 = new GraphicsPath ( ) ; pathDividedBy1000.AddPolygon ( points.Select ( p = > new PointF ( p.X/1000f , p.Y/1000f ) ) .ToArray ( ) ) ; Region regionDividedby1000 = new Region ( pathDividedBy1000 ) ; // Time call to Region.IsVisible ( PointF ) var stopwatch = Stopwatch.StartNew ( ) ; Console.WriteLine ( `` Computing region.IsVisible for points divided by 1000 : '' ) ; regionDividedby1000.IsVisible ( new PointF ( 0f , 0f ) ) ; var dividedBy1000Timing = stopwatch.ElapsedMilliseconds ; Console.WriteLine ( $ '' Elapsed time : { dividedBy1000Timing } ms '' ) ; stopwatch.Restart ( ) ; Console.WriteLine ( `` Computing region.IsVisible for original points '' ) ; regionFromOriginalPoints.IsVisible ( new PointF ( 0f , 0f ) ) ; var originalTiming = stopwatch.ElapsedMilliseconds ; Console.WriteLine ( $ '' Elapsed time : { originalTiming } ms '' ) ; } } } | Region.IsVisible ( PointF ) has very slow performance for large floating point values |
C_sharp : I 'm new to LINQ and PLINQ , and I 'm building a project to test them.Stub : StubCollection : then I have some methods to iterate the stubcollection and count how many stubs have the boolean set to true : foreach : it workslinq : it works ( little slower than foreach ) plinq:100 % CPU , no resultwhy ? the only difference is the AsParallel ( ) <code> class Stub { private Boolean mytf ; public Stub ( ) { Random generator = new Random ( ) ; if ( generator.NextDouble ( ) < 0.5 ) { mytf = false ; } else mytf = true ; } public Boolean tf { get { return mytf ; } } } class StubCollection : IEnumerable { Stub [ ] stubs ; public StubCollection ( int n ) { stubs = new Stub [ n ] ; for ( int i = 0 ; i < n ; i++ ) { stubs [ i ] = new Stub ( ) ; } } IEnumerator IEnumerable.GetEnumerator ( ) { return new StubIterator ( this ) ; } public class StubIterator : IEnumerator { private StubCollection sc ; private int index = -1 ; public StubIterator ( StubCollection _sc ) { sc = _sc ; } public bool MoveNext ( ) { index++ ; if ( index < sc.stubs.Length ) { return true ; } else { index = -1 ; return false ; } } public object Current { get { if ( index < = -1 ) { throw new InvalidOperationException ( ) ; } return sc.stubs [ index ] ; } } public void Reset ( ) { index = -1 ; } } } Stopwatch sw = new Stopwatch ( ) ; Int32 n = 0 ; sw.Start ( ) ; foreach ( Stub s in sc ) if ( s.tf ) n++ ; sw.Stop ( ) ; MessageBox.Show ( `` n : '' + n.ToString ( ) + `` timer : '' + sw.ElapsedMilliseconds.ToString ( ) ) ; Stopwatch sw = new Stopwatch ( ) ; Int32 n = 0 ; sw.Start ( ) ; var trueStubs = from Stub s in sc where s.tf select s ; n = trueStubs.Count ( ) ; sw.Stop ( ) ; MessageBox.Show ( `` n : '' + n.ToString ( ) + `` timer : '' + sw.ElapsedMilliseconds.ToString ( ) ) ; Stopwatch sw = new Stopwatch ( ) ; Int32 n = 0 ; sw.Start ( ) ; var trueStubs = from Stub s in sc.AsParallel ( ) where s.tf select s ; n = trueStubs.Count ( ) ; sw.Stop ( ) ; MessageBox.Show ( `` n : '' + n.ToString ( ) + `` timer : '' + sw.ElapsedMilliseconds.ToString ( ) ) ; | Application hangs using PLINQ AsParallel ( ) . No problems with LINQ |
C_sharp : I 'm trying to convert some VB.net code to C # . I used SharpDevelop to do the heavy lifting ; but the code it generated is breaking on some of the enum manipulation and I 'm not sure how to fix it manually.Original VB.net code : generated C # code : Resharper suggests adding the [ Flags ] attribute to the enum ; but doing so does n't affect the error . <code> Enum ePlacement Left = 1 Right = 2 Top = 4 Bottom = 8 TopLeft = Top Or Left TopRight = Top Or Right BottomLeft = Bottom Or Left BottomRight = Bottom Or RightEnd EnumPrivate mPlacement As ePlacement '' ... mPlacement = ( mPlacement And Not ePlacement.Left ) Or ePlacement.Right public enum ePlacement { Left = 1 , Right = 2 , Top = 4 , Bottom = 8 , TopLeft = Top | Left , TopRight = Top | Right , BottomLeft = Bottom | Left , BottomRight = Bottom | Right } private ePlacement mPlacement ; // ... //Generates CS0023 : Operator ' ! ' can not be applied to operand of type 'Popup.Popup.ePlacement'mPlacement = ( mPlacement & ! ePlacement.Left ) | ePlacement.Right ; | C # equivalent to `` Not MyEnum.SomeValue '' |
C_sharp : I am trying to automate some of our processes , one includes logging in to an external web page , clicking a link to expand details , then grab all details displayed.I have got the process logging in , and can grab all of the details once they are expanded.The problem is with clicking the link . The link is defined like below ( I have removed what the Submit method actually does as the code is long and probably irrelevant . Obviously the img is placeholder just as an example ) : I use this data as below : Upon running expandDetails.InvokeMember ( `` click '' ) ; browser_DocumentCompleted gets called again as expected but the document is same as before and expandDetails is found again with the `` closed '' id . This means that the details I am looking for are never shown.How do I get access to the document AFTER the AJAX script runs correctly ? Adding a Timer to delay checking the document does n't seem to have worked . <code> < a id= '' form : SummarySubView : closedToggleControl '' onclick= '' A4J.AJAX.Submit ( ... ) ; return false ; '' href= '' # '' > < img ... / > < /a > void browser_DocumentCompleted ( object sender , WebBrowserDocumentCompletedEventArgs e ) { WebBrowser browser = ( WebBrowser ) sender ; HtmlElement expandDetails = browser.Document.GetElementById ( `` form : SummarySubView : closedToggleControl '' ) ; //When open ID for element is `` form : SummarySubView : openToggleControl '' if ( expandDetails == null ) //If already expanded { //Stuff } else { expandDetails.InvokeMember ( `` click '' ) ; //Click on element to run AJAX } } | Screen scraping web page containing button with AJAX |
C_sharp : I have some code that maps strongly-typed business objects into anonymous types , which are then serialized into JSON and exposed via an API.After restructuring my solution into separate projects , some of my tests started to fail . I 've done a bit of digging and it turns out that Object.Equals behaves differently on anonymous types that are returned by code from a different assembly - and I 'm not sure why , or what I can do to work around it.There 's full repro code at https : //github.com/dylanbeattie/AnonymousTypeEquality but the bit that 's actually breaking is below . This code is in the Tests project : and then there is a separate class library in the solution containing only this : According to MSDN , `` two instances of the same anonymous type are equal only if all their properties are equal . '' ( my emphasis ) - so what controls whether two instances are of the same anonymous type for comparison purposes ? My two instances have equal hash codes , and both appear to be < > f__AnonymousType0 ` 2 [ System.String , System.Int32 ] - but I 'm guessing that equality for anonymous types must take the fully qualified type name into account and therefore moving code into a different assembly can break things . Anyone got a definitive source / link on exactly how this is implemented ? <code> [ TestFixture ] public class Tests { [ Test ] public void BothInline ( ) { var a = new { name = `` test '' , value = 123 } ; var b = new { name = `` test '' , value = 123 } ; Assert.That ( Object.Equals ( a , b ) ) ; // passes } [ Test ] public void FromLocalMethod ( ) { var a = new { name = `` test '' , value = 123 } ; var b = MakeObject ( `` test '' , 123 ) ; Assert.That ( Object.Equals ( a , b ) ) ; // passes } [ Test ] public void FromOtherNamespace ( ) { var a = new { name = `` test '' , value = 123 } ; var b = OtherNamespaceClass.MakeObject ( `` test '' , 123 ) ; Assert.That ( Object.Equals ( a , b ) ) ; // passes } [ Test ] public void FromOtherClass ( ) { var a = new { name = `` test '' , value = 123 } ; var b = OtherClass.MakeObject ( `` test '' , 123 ) ; /* This is the test that fails , and I can not work out why */ Assert.That ( Object.Equals ( a , b ) ) ; } private object MakeObject ( string name , int value ) { return new { name , value } ; } } namespace OtherClasses { public static class OtherClass { public static object MakeObject ( string name , int value ) { return new { name , value } ; } } } | Why does Object.Equals ( ) return false for identical anonymous types when they 're instantiated from different assemblies ? |
C_sharp : I 'm trying to find a way to delay all code that takes place after I make a service call . The reason for this delay is that my service returns code necesarry for the following functions and the result I pass is to these following functions is undefined.I have tried attaching the setTimeout ( ) to the function that is called directly after the service call , but then it just skips the function I set the timeout on and jumps to the next function ... My web method that I am calling is not that big and is not doing anything that is too intensiveI had found the delay ( ) and thought that might work , but I do n't have jquery 1.4 and ca n't use it as of yet.is there anything that can help.. ? <code> public bool GetSpreadsheetStatusForAdmin ( string cacId ) { SpreadSheetStatus result = new SpreadSheetStatus ( ) ; List < Data.Spreadsheet > spreadsheets = SpreadsheetManager.GetUserSpreadsheets ( GetCurrent.Identity ) ; if ( spreadsheets.Count ! = 0 ) { foreach ( Data.Spreadsheet spreadsheet in spreadsheets ) { if ( spreadsheet.Status == SpreadsheetStatus.Pending ) { return true ; } } } return false ; } | Jquery Delay Function Calls |
C_sharp : So now that we have generic Covariance and Contravariance on interfaces and delegates in C # , I was just curious if given a Type , you can figure out the covariance/contravariance of its generic arguments . I started trying to write my own implementation , which would look through all of the methods on a given type and see if the return types and or arguments match the types in the generic arguments . The problem is that even if I have this : using my logic , it LOOKS like it should be contravariant , but since we did n't actually specify : ( the in parameter ) it is n't actually contravariant . Which leads to my question : Is there a way to determine the variance of generic parameters ? <code> public interface IFoo < T > { void DoSomething ( T item ) ; } public interface IFoo < in T > { void DoSomething ( T item ) ; } | Is there a way to determine the Variance of an Interface / Delegate in C # 4.0 ? |
C_sharp : I have a problem in the following code : I just want to get Exception from new started task MainTask . But the result was not what I was expected.As you can see the result , task finishes before `` Waiting Ended ! ! '' console log.I do n't have a clue that why MainTask ended even if in MainTask has await command inside ? Did I missed something ? <code> static void Main ( string [ ] args ) { Task newTask = Task.Factory.StartNew ( MainTask ) ; newTask.ContinueWith ( ( Task someTask ) = > { Console.WriteLine ( `` Main State= '' + someTask.Status.ToString ( ) + `` IsFaulted= '' + someTask.IsFaulted+ '' isComplete= '' +someTask.IsCompleted ) ; } ) ; while ( true ) { } } static async Task MainTask ( ) { Console.WriteLine ( `` MainStarted ! `` ) ; Task someTask = Task.Factory.StartNew ( ( ) = > { Console.WriteLine ( `` SleepStarted ! `` ) ; Thread.Sleep ( 1000 ) ; Console.WriteLine ( `` SleepEnded ! `` ) ; } ) ; await someTask ; Console.WriteLine ( `` Waiting Ended ! ! `` ) ; throw new Exception ( `` CustomException ! `` ) ; Console.WriteLine ( `` NeverReaches here ! ! `` ) ; } MainStarted ! Main State = RanToCompletion IsFaulted = False isComplete = TrueSleepStarted ! SleepEnded ! Waiting Ended ! ! | Why Task finishes even in await |
C_sharp : I am looking at some code and I do n't understand what a particular constraint means in the following class definition : I do n't understand what this implies about parameter type T . <code> internal abstract class Entity < T > : Entity where T : Entity < T > { ... } | What does this parameter type constraint mean ? |
C_sharp : I need to apply In-Memory Cache on my website with.NetFramework 4.5.2 but I get this exception : Unity.Exceptions.ResolutionFailedException : 'Resolution of the dependency failed , type = 'Tranship.UI.Areas.Portal.Controllers.SearchResultController ' , name = ' ( none ) ' . Exception occurred while : while resolving . Exception is : InvalidOperationException - The current type , Microsoft.Extensions.Caching.Memory.IMemoryCache , is an interface and can not be constructed . Are you missing a type mapping ? I am using Asp.net MVC ( not Core ) and using Microsoft.Extensions.Caching.Memory version 1.1.2 This is my cs file : <code> using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; using Tranship.Business.Core ; using Tranship.Business.Interface ; using Tranship.DataAccess.UnitOfWork ; using Tranship.Domain.Context ; using Tranship.Domain.Model ; using Tranship.DomainService.Interface ; using Tranship.ViewModel.Model ; using Tranship.ViewModel.Mapper ; using Tranship.ViewModel.Parameter ; using Microsoft.Extensions.Caching.Memory ; namespace Tranship.DomainService.Core { public class ScheduleDomainService : IScheduleDomainService { private readonly IMemoryCache MemoryCache ; private readonly string key = `` TranshipMemoryCache '' ; public BoundedContextUnitOfWork Context { get ; set ; } public IScheduleBiz ScheduleBiz { get ; set ; } public ScheduleDomainService ( IMemoryCache memoryCache ) { Context = new BoundedContextUnitOfWork ( new BoundedContext ( ) ) ; ScheduleBiz = new ScheduleBiz ( Context ) ; MemoryCache = memoryCache ; } public List < ScheduleViewModel > GetScheduleBySearchParameter ( SearchTripParameters parameters ) { DateTime from ; DateTime to ; List < ScheduleViewModel > cacheObject = new List < ScheduleViewModel > ( ) ; if ( ! MemoryCache.TryGetValue ( key , out cacheObject ) ) { // Cache is empty or timespan has been terminated cacheObject = ScheduleBiz.GetAll ( ) ; MemoryCache.Set ( key , cacheObject , new MemoryCacheEntryOptions ( ) .SetAbsoluteExpiration ( TimeSpan.FromHours ( 1 ) ) ) ; } else { // Cache is full cacheObject = MemoryCache.Get ( key ) as List < ScheduleViewModel > ; } return cacheObject ; } } } | InvalidOperationException in Asp.Net MVC while using In-Memory Cache |
C_sharp : Possible Duplicate : Does C # support return type covariance ? I 'm not sure if I 'm just being stupid ... If I have an interface : Why ca n't I implement it like so ( I guess this would use implicit Covariance ? ) Any instance of MoopImplementor would meet the contract specified by IMoop , so it seems like this should be ok.Please enlighten me : ) EDIT : To be clear- since the implementing class returns something that inherits from the return type of the Interfaced method - I feel this should work . Specifically , a string IS an object . ( and the same goes for any other inhertiance chain ) . <code> public interface IMoop { object Moop ( ) ; } public class MoopImplementor : IMoop { string Moop ( ) ; } | Why ca n't I implement an Interface this way ? |
C_sharp : I have the following extension methods for my MessageBus : which compiles fine . However when I try to use it : I get the error that neither of the two candidate methodsare most specific . However I thought that Maybe < T > wouldbe more specific than T or is that not correct ? EDITIt gets curiouser because if I call the extension methodexplicitly then : Then it works and picks the correct method . <code> public static class MessageBusMixins { public static IDisposable Subscribe < T > ( this IObservable < T > observable , MessageBus bus ) where T : class { ... } public static IDisposable Subscribe < T > ( this IObservable < Maybe < T > > observable , MessageBus bus ) { ... } } IObservable < Maybe < string > > source = ... ; MessageBus bus = ... ; source.Subscribe ( bus ) ; MessageBus.SubscribeTo ( source , bus ) ; | C # specialization of generic extension methods |
C_sharp : I 'm exploring the feasibility of running a C # Kinect Visual Gesture Program ( something like Continuous Gesture Basics project https : //github.com/angelaHillier/ContinuousGestureBasics-WPF ) inside of a Docker for Windows container.Is this even theoretically possible ( run C # Kinect in a Docker for Windows container ? ) If the answer to 1 is yes , here are some extra details : I 'm using the microsoft/dotnet-framework:4.7 image as a basis and my initial Dockerfile looks like this : Build the image : Turn on container : Attach to a powershell session to monkey around : When I attempt to run my gesture application from the Docker container I get the following error ( which is expected since no Kinect SDK was installed in the container ) : At this point , the big question is how to install the Kinect v2 SDK [ KinectSDK-v2.0_1409-Setup.exe ] or the Kinect v2 runtime [ KinectRuntime-v2.0_1409-Setup.exe ] in the container.The installers have a EULA and according to some clever University of Wisconsin folks , there is a technique to to extract installers using Wix 's dark.exe decompiler ( https : //social.msdn.microsoft.com/Forums/en-US/a5b04520-e437-48e3-ba22-e2cdb46b4d62/silent-install-installation-instructions ? forum=kinectsdk ) ex . The issue I ran into when I got to the underlying msi files is there is no option to run them silently using msiexec.I 've figured out that the runtime installer ( Runtime installer ( KinectRuntime-x64.msi ) extracted from the Kinect v2 SDK ) makes at least the following changes in the filesystem : Creates a folder `` Kinect '' in C : \Windows\System32 and adds 3 files to System 32 : k4wcll.dllkinect20.dllmicrosoft._kinect.dllThe last three files in System32 should be the 64-bit versions ( the installer appears to have x86 and x64 versions of those 3 ) Replicating those changes by hand does not lead to success on the host machine let alone in the container.It 's currently unclear what other registry/system changes are occurring with the installer ( and whether or not that would get us over the goal line in the Docker container ) Any ideas about how to proceed from here ? <code> FROM microsoft/dotnet-framework:4.7ADD . /home/gestureWORKDIR /home/gesture $ docker build -t kinect . $ docker run -dit -- name kinectContainer kinect $ docker exec -it kinectContainer powershell Unhandled Exception : System.BadImageFormatException : Could not load file or assembly 'Microsoft.Kinect , Version=2.0.0.0 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 ' or one of its dependencies . Reference assemblies should not be loaded for execution . They can only be loaded in the Reflection-only loader context . ( Exception from HRESULT : 0x80131058 ) -- - > System.BadImageFormatException : Can not load a reference assembly for execution . erable program . Check the spelling of the name , or if a path was included , verify that the path -- - End of inner exception stack trace -- - at GestureDetector.GestureDetectorApp..ctor ( ) $ & ' C : \Program Files ( x86 ) \WiX Toolset v3.11\bin\dark.exe ' C : \installerwork\KinectRuntime-v2.0_1409-Setup.exe -x c : \installerwork\kinect_sdk_installersfiles | Is it possible to run Kinect V2 inside a Docker container ? |
C_sharp : Int32 struct does n't define operator overload method for == operator , so why does n't the code cause compile time error : <code> if ( 1 == null ) ... ; | Should n't if ( 1 == null ) cause an error ? |
C_sharp : As far as I know making class sealed gets rid of look up in VTable or am I wrong ? If I make a class sealed does this mean that all virtual methods in class hierarchy are also marked sealed ? For example : <code> public class A { protected virtual void M ( ) { ... ... .. } protected virtual void O ( ) { ... ... .. } } public sealed class B : A { // I guess I can make this private for sealed class private override void M ( ) { ... ... .. } // Is this method automatically sealed ? In the meaning that it does n't have to look in VTable and can be called directly ? // Also what about O ( ) can it be called directly too , without VTable ? } | How to get rid of virtual table ? Sealed class |
C_sharp : I have seen so many times developers using a disposable object inline , here for instance . By inline I mean : I know that the Dispose method wo n't be called , but since no reference is held to the object , how will the garbage collector handle it ? Is it safe to use a disposable object like that ? I used a DataTable in my example because it is the only concrete example I found , but my question applies to disposable objects in general . I do not personally use them like that , I just wanted to know if they are handled diffently by the GC if they are used that way . <code> var result = new DataTable ( ) .Compute ( `` 1 + 4 * 7 '' , null ) ; | Is it safe to create and use a disposable object inline ? |
C_sharp : Warning : This is merely an exercise for those whose are passionate about breaking stuff to understand their mechanics.I was exploring the limits of what I could accomplish in C # and I wrote a ForceCast ( ) function to perform a brute-force cast without any type checks . Never consider using this function in production code.I wrote a class called Original and a struct called LikeOriginal , both with two integer variables . In Main ( ) I created a new variable called orig and set it to a new instance of Original with a=7 and b=20 . When orig is cast into LikeOriginal and stored in casted , the values of cG and dG become undefined , which is to be expected as LikeOriginal is a struct and class instances contain more metadata than struct instances thus causing memory layout mismatch.Example Output : Notice , however , that when I call casted.Add ( 3 ) and cast back to Original and print the values of a and b , surprisingly they are successfully incremented by 3 , and this has been repeatable.What is confusing me is the fact that casting the class to the struct will cause cG and dG to map to class metadata , but when they are modified and cast back to a class , they map correctly with a and b.Why is this the case ? The code used : <code> Casted Original to LikeOriginal1300246376 , 5421300246376 , 542added 3Casted LikeOriginal back to Original1300246379 , 545 using System ; using System.Runtime.InteropServices ; namespace BreakingStuff { public class Original { public int a , b ; public Original ( int a , int b ) { this.a = a ; this.b = b ; } public void Add ( int val ) { } } public struct LikeOriginal { public int cG , dG ; public override string ToString ( ) { return cG + `` , `` + dG ; } public void Add ( int val ) { cG += val ; dG += val ; } } public static class Program { public unsafe static void Main ( ) { Original orig = new Original ( 7 , 20 ) ; LikeOriginal casted = ForceCast < Original , LikeOriginal > ( orig ) ; Console.WriteLine ( `` Casted Original to LikeOriginal '' ) ; Console.WriteLine ( casted.cG + `` , `` + casted.dG ) ; Console.WriteLine ( casted.ToString ( ) ) ; casted.Add ( 3 ) ; Console.WriteLine ( `` added 3 '' ) ; orig = ForceCast < LikeOriginal , Original > ( casted ) ; Console.WriteLine ( `` Casted LikeOriginal back to Original '' ) ; Console.WriteLine ( orig.a + `` , `` + orig.b ) ; Console.ReadLine ( ) ; } //performs a pointer cast but with the same memory layout . private static unsafe TOut ForceCast < TIn , TOut > ( this TIn input ) { GCHandle handle = GCHandle.Alloc ( input ) ; TOut result = Read < TOut > ( GCHandle.ToIntPtr ( handle ) ) ; handle.Free ( ) ; return result ; } private static unsafe T Read < T > ( this IntPtr address ) { T obj = default ( T ) ; if ( address == IntPtr.Zero ) return obj ; TypedReference tr = __makeref ( obj ) ; * ( IntPtr* ) ( & tr ) = address ; return __refvalue ( tr , T ) ; } } } | Why does casting a struct to a similar class sort-of work ? |
C_sharp : I am working on a Universal Windows ( UWP ) app and I want to add some page NavigationTransitions to my pages . I know that I can use default NavigationThemeTransition like the code below : but I want to create my own Navigation Transition , I searched many times but no result . I also tried to get definitions of default navigations and I were able to write some code like below but do n't know what I have to write in code blocks . Any help ? <code> < Page.Transitions > < TransitionCollection > < NavigationThemeTransition > < NavigationThemeTransition.DefaultNavigationTransitionInfo > < CommonNavigationTransitionInfo/ > < /NavigationThemeTransition.DefaultNavigationTransitionInfo > < /NavigationThemeTransition > < /TransitionCollection > < /Page.Transitions > using Windows.UI.Xaml ; using Windows.UI.Xaml.Media.Animation ; using Windows.UI.Xaml.Controls.Primitives ; namespace BindingSample2 { internal interface IWikiSedaNavigationTransitionInfo { System.Boolean IsStaggeringEnabled { get ; set ; } } public sealed class WikiSedaNavigationTransitionInfo : NavigationTransitionInfo , IWikiSedaNavigationTransitionInfo { // // Summary : // Initializes a new instance of the WikiSedaNavigationTransitionInfo class . public WikiSedaNavigationTransitionInfo ( ) { var a = this.GetNavigationStateCore ( ) ; var s = this.MemberwiseClone ( ) ; // NavigationThemeTransition theme = new NavigationThemeTransition ( ) ; var themeR = new EdgeUIThemeTransition ( ) ; themeR.Edge = EdgeTransitionLocation.Bottom ; //Transitions = collection ; } // Summary : // Identifies the CommonNavigationTransitionInfo.IsStaggerElement attached property . // // Returns : // The identifier for the CommonNavigationTransitionInfo.IsStaggerElement attached // property . public static DependencyProperty IsStaggerElementProperty { get ; } // Summary : // Identifies the IsStaggeringEnabled dependency property . // // Returns : // The identifier for the IsStaggeringEnabled dependency property . public static DependencyProperty IsStaggeringEnabledProperty { get ; } // Summary : // Gets or sets a Boolean value indicating if staggering is enabled for the navigation // transition . // // Returns : // A Boolean value indicating if staggering is enabled for the navigation transition . public System.Boolean IsStaggeringEnabled { get ; set ; } // Summary : // Returns a Boolean value indicating if the specified UIElement is the stagger // element for the navigation transition . // // Parameters : // element : // The UIElement to check as being the stagger element . // // Returns : // Returns true if element is the stagger element ; otherwise false . public static System.Boolean GetIsStaggerElement ( UIElement element ) { return false ; } // Summary : // Sets a Boolean value indicating if the specified UIElement is the stagger element // for the navigation transition . // // Parameters : // element : // The UIElement about which to set the stagger element indicator . // // value : // Set this value to true if element is the stagger element ; otherwise set it to // false . public static void SetIsStaggerElement ( UIElement element , System.Boolean value ) { } } } | Create customized NavigationTransitionInfo for Page Navigation Transitions in UWP |
C_sharp : Understanding the C # Language Specification on overload resolution is clearly hard , and now I am wondering why this simple case fails : This gives compile-time error CS0121 , The call is ambiguous between the following methods or properties : followed by my two Method function members ( overloads ) .What I would have expected was that Func < string > was a better conversion target than Func < object > , and then the first overload should be used.Since .NET 4 and C # 4 ( 2010 ) , the generic delegate type Func < out TResult > has been covariant in TResult , and for that reason an implicit conversion exists from Func < string > to Func < object > while clearly no implicit conversion can exist from Func < object > to Func < string > . So it would make Func < string > the better conversion target , and the overload resolution should pick the first overload ? My question is simply : What part of the C # Spec am I missing here ? Addition : This works fine : <code> void Method ( Func < string > f ) { } void Method ( Func < object > f ) { } void Call ( ) { Method ( ( ) = > { throw new NotSupportedException ( ) ; } ) ; } void Call ( ) { Method ( null ) ; // OK ! } | Why ca n't the compiler tell the better conversion target in this overload resolution case ? ( covariance ) |
C_sharp : I am currently teaching a colleague .Net and he asked me a question that stumped me.Why do we have to declare ? if var is implicit typing , why do we have to even declare ? becomescould become The implicit typing would still mean that this is a statically typed variable.If two different types are assigned to the variable , if they do not share a base class , ( other than object ) , that could be a compiler error.Is there a technical reason this could not be done or is it stylistically we like havein <code> Animal animal = new Animal ( ) ; var animal = new Animal ( ) ; animal = new Animal ( ) ; | Why are declarations necessary |
C_sharp : I am using an object initializer for a st object : The second initializer line gives the error : The name 'ContainedItem ' does not exist in the current context . Invalid initializer member declarator.and suggests declaring ContainedItem somewhere in local scope.Now as the first line works it can be seen that ContainedItem is in fact a valid property of Container and that MyContainer.ContainedItem is definitely not null ... so why does the following line fail to recognise it ? <code> public class Container { public Container ( ) { ContainedItem = new Item ; } public Item ContainedItem { get ; set ; } } public class Item { public string Value { get ; set ; } } var MyContainer = new Container ( ) { // I want to populate the the property Value of the property Item // with the second line rather than the first ContainedItem = new Item ( ) { Value = FooString } , // This works ContainedItem.Value = FooString // This assigns to the same member but does not work } ; | Why does n't name exist in the current context of shorthand member initialisation ? |
C_sharp : Initially I faced this issue when I was testing my code with UnitTest framework using Assert.AreEqual methods . I noticed that for UInt32 and UInt64 types different overload of AreEqual was selected ( AreEqual ( object , object ) instead of AreEqual < T > ( T , T ) ) . I did some research and got the following simple code : The Error message I get is `` The type arguments for method 'MyGenericClass.DoNothing < T > ( T , T ) ' can not be inferred from the usage . Try specifying the type arguments explicitly. '' . The workaround is relatively easy ( use explicit cast ) , so I just want to know , what is so special about UInt32 and UInt64 , what other types do n't have ( or have ) , and why UInt16 is not behaving the same way ? P.S . Oh , I almost forgot - I 've found this table of type conversions , but first of all - it is for new `` Roslyn '' compiler , and second of all - I do n't see the answer there anyway , maybe someone will point it out ? <code> public struct MyInteger { public SByte SByte { get ; set ; } public Byte Byte { get ; set ; } public UInt16 UInt16 { get ; set ; } public UInt32 UInt32 { get ; set ; } public UInt64 UInt64 { get ; set ; } public Int16 Int16 { get ; set ; } public Int32 Int32 { get ; set ; } public Int64 Int64 { get ; set ; } } public class MyGenericClass { public static void DoNothing < T > ( T expected , T actual ) { } } public class IntegerTest { public void TestIntegers ( ) { var integer = new MyInteger { SByte = 42 , Byte = 42 , Int16 = 42 , Int32 = 42 , Int64 = 42 , UInt16 = 42 , UInt32 = 42 , UInt64 = 42 } ; MyGenericClass.DoNothing ( 42 , integer.SByte ) ; // T is Int32 MyGenericClass.DoNothing ( 42 , integer.Byte ) ; // T is Int32 MyGenericClass.DoNothing ( 42 , integer.Int16 ) ; // T is Int32 MyGenericClass.DoNothing ( 42 , integer.Int32 ) ; // T is Int32 MyGenericClass.DoNothing ( 42 , integer.Int64 ) ; // T is Int64 MyGenericClass.DoNothing ( 42 , integer.UInt16 ) ; // T is Int32 MyGenericClass.DoNothing ( 42 , integer.UInt32 ) ; // Error MyGenericClass.DoNothing ( 42 , integer.UInt64 ) ; // Error MyGenericClass.DoNothing ( ( UInt32 ) 42 , integer.UInt32 ) ; // T is UInt32 MyGenericClass.DoNothing ( ( UInt64 ) 42 , integer.UInt64 ) ; // T is UInt64 } } | UInt32 and UInt64 types can not be inferred from the usage when used along with Int32 type in generic method |
C_sharp : I can not use a specific DLL in SSIS script-task . In c # console-project anything is fine . SSIS throws the error : Error : The Type `` Microsoft.SharePoint.Client.ClientRuntimeContext '' in assembly `` Microsoft.SharePoint.Client , Version=14.0.0.0 , Culture=neutral PublicKeyToken= ... . '' could not be loaded.I am running Visual Studio 2017 with Datatools . I got the libraries from NuGet-paket-manager and saved them local on C : / Microsoft.SharePoint.Client , Version 14.0.0.0 , Runtime-Version v2.0.50727Microsoft.SharePoint.Client.Runtime , Version 15.0.0.0 , Runtime-Version v4.0.30319My console-project is .NET 4.6 and i ve setted the SSIS project also to .NET 4.6 . In both cases I added the libraries with rightclick on References > Add > Search from computerI just tested a console-project without any problems : And this is the code in SSIS ( it is similar ... Just uses the object ClientContext : <code> static void Main ( string [ ] args ) { using ( ClientContext clientContext = new ClientContext ( `` urltomysite.com '' ) ) { } Console.WriteLine ( `` finished '' ) ; } public void Main ( ) { //Loading assemblies extra AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler ( CurrentDomain_AssemblyResolve ) ; AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler ( CurrentDomain_AssemblyResolve2 ) ; try { //Testing the assembly method Class1.TESTIT ( ) ; } catch ( Exception ex ) { Dts.Events.FireError ( 0 , `` Error '' , ex.Message , null , 0 ) ; Dts.TaskResult = ( int ) ScriptResults.Failure ; } } static System.Reflection.Assembly CurrentDomain_AssemblyResolve ( object sender , ResolveEventArgs args ) { return System.Reflection.Assembly.LoadFile ( System.IO.Path.Combine ( `` C : / '' , `` Microsoft.SharePoint.Client.dll '' ) ) ; } static System.Reflection.Assembly CurrentDomain_AssemblyResolve2 ( object sender , ResolveEventArgs args ) { return System.Reflection.Assembly.LoadFile ( System.IO.Path.Combine ( `` C : / '' , `` Microsoft.SharePoint.Client.Runtime.dll '' ) ) ; } class Class1 { public static void TESTIT ( ) { using ( ClientContext clientContext = new ClientContext ( `` urltomysite.com '' ) ) { } } } | SSIS how to execute dll in script-task ( SharePoint function not found ) |
C_sharp : How can I pass thru from one instantiator to another ? Suppose we had this class . How do I pass from foo ( string , string ) to foo ( Uri ) ? <code> public foo { string path { get ; private set ; } string query { get ; private set ; } public foo ( Uri someUrl ) { // ... do stuff here } public foo ( string path , string query ) { Uri someUrl = new Uri ( String.Concat ( path , query ) ; // ... do stuff here to pass thru to foo ( someUrl ) } } | Constructor chaining passing computed values for parameters |
C_sharp : In AutoMapper 2.0 I used Profiles to configure my mapping . I useSourceMemberNameTransformer and DestinationMemberNameTransformer to match my source and destination property names.In 2.1.265 these properties are no longer on Profile . Does anyone know why they were removed ? But more importantly , how can I duplicate this functionality.EditI 've been looking at the SourceMemberNamingConvention and DestinationMemberNamingConvention , but I can not find any documentation as to how those work . Does anyone have experience using a custom INamingConvention ? Edit 2Source members are generated from a 3rd party database . Typically they use all lowercase column names with underscores between words . Sometimes they leave out underscores , sometimes they throw in random capitalization.Destination members try to follow .NET naming conventions as much as possible . Underscores were removed , the first character following the underscore were capitalized . Additional case changes were made to make member names easier to read.To solve this , I setEdit 3More information for people from the future.I inspected the source to see how INamingConvention is used . The way it is designed it a little misleading . The interface is befined asHowever , AutoMapper does not user the full definition of the interface for both SourceMemberNamingConvention and DestinationMemberNamingConventionIt takes each member of the destination type and applies DestinationMemberNamingConvention.SplittingExpression . It then takes those match parts and calls string.Join using SourceMemberNamingConvention.SeparatorCharacter . It then attempts to match the source type members to the destination type members . This is a very high level overview of what is does and is not an attempt to describe the full functionality . It is merely meant to show how INamingConvention is used and to show that SourceMemberNamingConvention.SplittingExpression and DestinationMemberNamingConvention.SeparatorCharacter are never used.If you are unable to transform the destination members using this strategy , then you must manually map the properties as nemesv 's answer suggests . <code> SourceMemberNameTransformer = name = > name.Replace ( `` _ '' , `` '' ) .ToUpper ( ) DestinationMemberNameTransformer = name = > name.ToUpper ( ) public interface INamingConvention { Regex SplittingExpression { get ; } string SeparatorCharacter { get ; } } | Missing member in AutoMapper 2.1.265 |
C_sharp : I have a .NET Core 2.1 Web API service and I wish to retrieve the connection string from the appsettings.json file and use it in a separate database class I wrote . I do n't need or want to use Entity Framework , unfortunately , all MS docs only show EF examples . I 've tried about 10 different techniques , though ca n't seem to get anywhere.Here 's the appsettings.json file : And the startup.cs file : The class I 'm using to grab results from a stored procedure : I 'm thinking that maybe it would be better to just keep the connection string in a separate text file and read it that way - but would rather do it the proper way . Any help is appreciated ( yes , I 'm new to .NET Core , but had n't seen a tutorial that was n't dependent on EF ) . <code> { `` Logging '' : { `` LogLevel '' : { `` Default '' : `` Warning '' } } , `` AllowedHosts '' : `` * '' , `` ConnectionStrings '' : { `` DefaultConnection '' : `` Server=MAXIMUS,61433 ; Database=Geolocation ; Trusted_Connection=True ; MultipleActiveResultSets=true '' } } using System ; using System.Collections.Generic ; using System.Linq ; using System.Threading.Tasks ; using Microsoft.AspNetCore.Builder ; using Microsoft.AspNetCore.Hosting ; using Microsoft.AspNetCore.HttpsPolicy ; using Microsoft.AspNetCore.Mvc ; using Microsoft.EntityFrameworkCore ; using Microsoft.Extensions.Configuration ; using Microsoft.Extensions.DependencyInjection ; using Microsoft.Extensions.Logging ; using Microsoft.Extensions.Options ; namespace GeoLocationService1 { public class Startup { public Startup ( IConfiguration configuration ) { Configuration = configuration ; } public IConfiguration Configuration { get ; } // This method gets called by the runtime . Use this method to add services to the container . public void ConfigureServices ( IServiceCollection services ) { services.AddMvc ( ) .SetCompatibilityVersion ( CompatibilityVersion.Version_2_1 ) ; } // This method gets called by the runtime . Use this method to configure the HTTP request pipeline . public void Configure ( IApplicationBuilder app , IHostingEnvironment env ) { if ( env.IsDevelopment ( ) ) { app.UseDeveloperExceptionPage ( ) ; } else { app.UseHsts ( ) ; } //app.UseHttpsRedirection ( ) ; app.UseMvc ( ) ; } } } using Microsoft.Extensions.Configuration ; using System ; using System.Collections ; using System.Collections.Generic ; using System.ComponentModel ; using System.Data ; using System.Data.SqlClient ; using System.Text ; using System.Configuration ; namespace GeoLocationService1 { [ DataObject ( true ) ] public class ip2location_data { public static string GetConnStr ( ) { // ? ? ? ? ? string dbconn = `` '' ; //need to somehow get the connection string from the appsettings.json file return dbconn ; } public static string LastErrorMsg = string.Empty ; [ DataObjectMethod ( DataObjectMethodType.Select , false ) ] public static ip2location GetGeoLocationFromIP ( string IPAddress ) { ip2location O = new ip2location ( ) ; using ( SqlConnection conn = new SqlConnection ( GetConnStr ( ) ) ) { using ( SqlCommand cmd = new SqlCommand ( `` GetGeoLocationFromIP '' , conn ) ) { cmd.CommandType = CommandType.StoredProcedure ; cmd.CommandTimeout = 30 ; cmd.Parameters.AddWithValue ( `` @ IPAddress '' , IPAddress ) ; conn.Open ( ) ; try { using ( SqlDataReader rs = cmd.ExecuteReader ( CommandBehavior.CloseConnection ) ) { if ( rs.Read ( ) ) { O.country_code = rs.GetString ( rs.GetOrdinal ( O.fld_country_code ) ) ; O.country_name = rs.GetString ( rs.GetOrdinal ( O.fld_country_name ) ) ; O.region_name = rs.GetString ( rs.GetOrdinal ( O.fld_region_name ) ) ; O.city_name = rs.GetString ( rs.GetOrdinal ( O.fld_city_name ) ) ; O.zip_code = rs.GetString ( rs.GetOrdinal ( O.fld_zip_code ) ) ; O.time_zone = rs.GetString ( rs.GetOrdinal ( O.fld_time_zone ) ) ; } } LastErrorMsg = string.Empty ; } catch ( Exception ex ) { LastErrorMsg = ex.Message ; } } } return O ; } } } | How to retrieve connection string in class from .NET Core 2.1 Web API w/o Entity Framework |
C_sharp : I need help understanding Unity and how IOC works.I have this in my UnityContainerThen in my Web API controller , I understand that IService is injected by Unity because it was a registered type.My Service InterfaceMy Service Implementation has its own constructor that takes an EntityFramework DBContext object . ( EF6 ) <code> var container = new UnityContainer ( ) ; // Register types container.RegisterType < IService , Service > ( new HierarchicalLifetimeManager ( ) ) ; config.DependencyResolver = new UnityResolver ( container ) ; public class MyController : ApiController { private IService _service ; // -- -- -- - Inject dependency - from Unity 'container.RegisterType ' public MyController ( IService service ) { _service = service ; } [ HttpGet ] public IHttpActionResult Get ( int id ) { var test = _service.GetItemById ( id ) ; return Ok ( test ) ; } } public interface IService { Item GetItemById ( int id ) ; } public class Service : IService { private MyDbContext db ; // -- - how is this happening ! ? public IService ( MyDbContext context ) { // Who is calling this constructor and how is 'context ' a newed instance of the DBContext ? db = context ; } public Item GetItemById ( int id ) { // How is this working and db is n't null ? return db.Items.FirstOrDefault ( x = > x.EntityId == id ) ; } } | Web API with Unity IOC - How is my DBContext Dependecy resolved ? |
C_sharp : Is there a way to change the code generated by a quick-fix in Resharper ? It does n't seem to be in the live templates.I 'd like the 'Create Property ' quickfix for an unrecognized symbol to generate Instead of : <code> public int MyProperty { get ; set ; } protected int MyProperty { get { throw new NotImplementedException ( ) ; } set { throw new NotImplementedException ( ) ; } } | Resharper quick-fix templates |
C_sharp : I 'm having an issue getting data out of a c # array serialized class with python . I have two files containing the classes . The first I am able to loop though the array and grab the public variables . However in the second file I see the class but am Unable to access any of the variables . It 's been 10+ years since I used C # and have been beating my head against the computer . The only difference I can see is file1.bin uses String where file2.bin uses string . Any pointers would be mot helpful . ironpython used to read .bin files.File1.bin - ( simplified ) array of Resident - Can Access datafile2.bin ( simplified ) Array of Resident Info Ca n't access dataupdateAfter looking closer it appears that one class is public and the other is internal . However , I 'm not sure how to access the internal class . <code> from System.Runtime.Serialization.Formatters.Binary import BinaryFormatterfrom System.IO import FileStream , FileMode , FileAccess , FileSharefrom System.Collections.Generic import *def read ( name ) : bformatter = BinaryFormatter ( ) file_stream = FileStream ( name , FileMode.Open , FileAccess.Read , FileShare.Read ) res = bformatter.Deserialize ( file_stream ) file_stream.Close ( ) return resdef write ( name , data ) : bformatter = BinaryFormatter ( ) stream = FileStream ( name , FileMode.Create , FileAccess.ReadWrite , FileShare.ReadWrite ) bformatter.Serialize ( stream , data ) stream.Close ( ) res = read ( 'fiel2.bin ' ) for space in res : print dir ( space ) namespace RanchoCSharp { [ Serializable ] public class Resident { public Resident ( ) { } public Resident ( String fName , String lName ) { firstN = fName ; lastN = lName ; } //Invoice info public String firstN ; public String lastN ; } } namespace Rancho_Resident { [ Serializable ] class ResidentInfo { public ResidentInfo ( ) { } public string unit ; public string space ; } } | python open a serialized C # file |
C_sharp : I have read many posts with the same issue , but none help , so apologies for the duplicate question : ( Ive followed the simple sample on the JQueryUI site by hard coding values and the autocomplete works , but I need it to come from my Database.View : JS : EDIT : I added an alert on success , and the alert is being called , but there is no data ( i.e . No data being pulled from DB ) And I have added the Links required : Below is my ActionResult ( Actually a JsonResult ) & Function to pull the list of Jobs : Am I missing something or doing something wrong ? I appreciate any help , thanks ! <code> @ Html.TextBoxFor ( model = > model.Position , new { @ type = `` text '' , @ id = `` jobtitle '' , @ name = `` jobtitle '' , @ placeholder = `` Job Title '' } ) < script > $ ( function ( ) { $ ( `` # jobtitle '' ) .autocomplete ( { source : function ( request , response ) { $ .ajax ( { url : ' @ Url.Action ( `` JobsAutoFill '' , `` Account '' ) ' , data : { Prefix : request.term } , success : function ( data ) { alert ( data ) ; response ( data ) ; } } ) ; } , minLength : 1 } ) ; // $ ( `` # jobtitle '' ) .autocomplete ( { // source : `` /Account/JobsAutoFill/ '' // } ) ; } ) ; < /script > < script src= '' https : //code.jquery.com/jquery-1.12.4.js '' > < /script > < script src= '' https : //code.jquery.com/ui/1.12.1/jquery-ui.js '' > < /script > public List < Jobs > GetAllJobs ( ) { List < Jobs > JobsList = new List < Jobs > ( ) ; using ( RBotEntities EF = new RBotEntities ( ) ) { var JobsListQuery = ( from ED in EF.EmploymentDetails select new { ED.pkiEmploymentDetailID , ED.Position } ) ; foreach ( var item in JobsListQuery ) { JobsList.Add ( new Jobs { Id = item.pkiEmploymentDetailID , Name = item.Position } ) ; } } return JobsList ; } public JsonResult JobsAutoFill ( string Prefix ) { //Note : you can bind same list from database List < Jobs > ObjList = new List < Jobs > ( ) ; ObjList = GetAllJobs ( ) ; //Searching records from list using LINQ query var JobNames = ( from N in ObjList where N.Name.StartsWith ( Prefix ) select new { N.Name } ) ; return Json ( JobNames , JsonRequestBehavior.AllowGet ) ; } | JQuery UI Autocomplete not reaching ActionResult C # MVC |
C_sharp : I 'm developing a project that will use ASP.NET Web API as the data service , and a Xamarin portable app as client.I 'm trying to enable migrations in the web app , but I get the following error : As you can see , I 've tried specifying the start up project explicitly but does n't look like the enable-migrations command is so happy about it.It 's a project I just created that uses full .NET ( I 'm bound to TPT/TPH model which EF Core does n't support yet ) , so the EF version is 6.1.3 targeting .NET 4.6.1.I 'm on VS Community 2015 Update 3 Version 14.0.25431.01.UpdateCa n't reproduce , but the issue happens even when adding a dummy start up project.Cross posted issue here , please vote and share your experiments . <code> Enable-Migrations -enableautomaticmigrations -ContextTypeName MyProject.Models.ApplicationDbContext -ProjectName MyProject -StartupProjectName MyProject.App -VerboseUsing StartUp project 'MyProject.App'.Exception calling `` SetData '' with `` 2 '' argument ( s ) : `` Type 'Microsoft.VisualStudio.ProjectSystem.VS.Implementation.Package.Automation.OAProject ' in assembly 'Microsoft.VisualStudio.ProjectSystem.VS.Implementation , Version=14.1.0.0 , Culture=neutral , PublicKeyToken=b03f5f7f11d50a3a ' is not marked as serializable . `` At C : \Users\weitz\.nuget\packages\EntityFramework\6.1.3\tools\EntityFramework.psm1:718 char:5+ $ domain.SetData ( 'project ' , $ project ) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified : ( : ) [ ] , MethodInvocationException + FullyQualifiedErrorId : SerializationException Exception calling `` SetData '' with `` 2 '' argument ( s ) : `` Type 'Microsoft.VisualStudio.ProjectSystem.VS.Implementation.Package.Automation.OAProject ' in assembly 'Microsoft.VisualStudio.ProjectSystem.VS.Implementation , Version=14.1.0.0 , Culture=neutral , PublicKeyToken=b03f5f7f11d50a3a ' is not marked as serializable . `` At C : \Users\weitz\.nuget\packages\EntityFramework\6.1.3\tools\EntityFramework.psm1:719 char:5+ $ domain.SetData ( 'contextProject ' , $ contextProject ) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified : ( : ) [ ] , MethodInvocationException + FullyQualifiedErrorId : SerializationException System.NullReferenceException : Object reference not set to an instance of an object . at System.Data.Entity.Migrations.Extensions.ProjectExtensions.GetPropertyValue [ T ] ( Project project , String propertyName ) at System.Data.Entity.Migrations.MigrationsDomainCommand.GetFacade ( String configurationTypeName , Boolean useContextWorkingDirectory ) at System.Data.Entity.Migrations.EnableMigrationsCommand.FindContextToEnable ( String contextTypeName ) at System.Data.Entity.Migrations.EnableMigrationsCommand. < > c__DisplayClass2. < .ctor > b__0 ( ) at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute ( Action command ) Object reference not set to an instance of an object . **PM > ** | VS 2015 ASP.NET Web API ( EF6 ) & Xamarin Enable-Migrations fails |
C_sharp : I am trying to write my first customer Html Helper extension method following the formatAnd there seem to be several different ways to access the property name and value from the expressionandand alsoCan somebody explain the difference between these methods ? Are there any situations where one is superior to the others ? <code> public static MvcHtmlString < TModel , TProperty > MyHelperFor ( this HtmlHelper < TModel > helper , Expression < Func < TModel , TProperty > > expression ) var body = expression.Body as MemberExpression ; var propertyName = body.Member.Name ; var propertyInfo = typeof ( TModel ) .getProperty ( propertyName ) var propertyValue = propertyInfo.GetValue ( helper.ViewData.Model ) ; var metadata = ModelMetadata.FromLambdaExpression ( expression , html.ViewData ) ; var propertyName = metadata.PropertyName ; var propertyValue = metadata.Model ; TModel model = ( TModel ) helper.ViewContext.ViewData.ModelMetadata.Model ; TProperty value = expression.Compile ( ) .Invoke ( model ) ; | Difference between HtmlHelper methods for accessing properties from lambda expression |
C_sharp : UPDATE This looks to be a bug in Windows 7 . I tested the same scenario with Windows 8 and I can not replicate this there . Please see the MS Bug Report that I posted on this issue if you want more information . Thank you again to all that helped.UPDATE 2 The error happens on Server 2008 R2 as well ( Kind of expected that ) Original Submission Using the examples on the following page Date Formats I am able to control the format of my date . However , one of my clients , using Windows 7 , modified their calendar to display their short date like this 'ddd MM/dd/yy ' , see the image for the settings . .This displays the clock like this .This works fine except when I use a date on their machine . When I format the date like the following ... If I take off the ddd to display the day of week in the calendar settings and use the same format option I see the following ... The .ToShortDateString ( ) option on the date gives me `` Tue 06/04/13 '' and crashes when going into a database . This is how the issue was found.Outside of hard coding the format , i.e . joining the month to the forward slash to the day etc , does anyone know of what else I can try to get this to work ? <code> String.Format ( `` { 0 : MM/dd/yy } '' , dt ) ; //the result is 06 04 13 , notice the spaces String.Format ( `` { 0 : MM/dd/yy } '' , dt ) ; //the result is 06/04/13 , this time it has forward slashes | C Sharp DateTime Format |
C_sharp : I have been mucking around with XMLs for entity Framework . I tried to create a type of entity that could have properties injected at runtime , First I created DynamicEntity object that is dynamic then entity inherits from thispublic partial class QUOTE_HOUSE : DynamicEntity ( and it does seem to work when I set properties manually after I get data from db ) . so based on this mechanism of removing properties I tried to do another one that inserts properties into XMLs , and whole thing seems to hold up ok ( at least it does not blow up on mapping which it usually does when XMLs are not right var mappingCollection = new StorageMappingItemCollection ( conceptualCollection , storageCollection , new [ ] { mappingXml.CreateReader ( ) } ) ; ) . Problem is EF when executing query blows up with The entity type QUOTE_HOUSE is not part of the model for the current context . Description : An unhandled exception occurred during the execution of the current web request . Please review the stack trace for more information about the error and where it originated in the code . Exception Details : System.InvalidOperationException : The entity type QUOTE_HOUSE is not part of the model for the current context . [ InvalidOperationException : The entity type QUOTE_HOUSE is not part of the model for the current context . ] System.Data.Entity.Internal.InternalContext.UpdateEntitySetMappingsForType ( Type entityType ) +208 System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType ( Type entityType ) +50Which I traced to TryUpdateEntitySetMappingsForType in System.Data.Entity.Internal.InternalContext after loading pdb for EFBasically what happens my QUOTE_HOUSE is not in this._workspace.GetItemCollection ( DataSpace.OSpace ) where UpdateEntitySetMappings tries to map it from.It checks if it 's in this._entitySetMappingsCache.ContainsKey ( entityType ) ) and since it 's not it then tries update mappings iterating over this._workspace.GetItemCollection ( DataSpace.OSpace ) where my item does n't existHowever I can see that my entity does exist in this._workspace.GetItems < EntityContainer > ( DataSpace.CSpace ) .Full UpdateEntitySetMappings looks following : How do entities get into this._workspace.GetItemCollection ( DataSpace.OSpace ) ? Why would entity be in CSpace but not in OSpace ? EDIT : For those who might wan na have a crack at bounty , below are components you might need to set-up environment to reproduce the issue.Entity generated from db first , ( DynamicEntity code is above ) DbContext for database requires constructor overloadsMechanism that does column injection ( it 's a rough prototype so be forgiving to how bad it looks atm ) , when injecting try string column I know that it maps ok.Initialization : You should be able to generate oracle database from entity QUOTE_HOUSE and enter some dummy values , do n't think you need a view as it blows up on .ToList ( ) . After you generated the database add additional column to database but not model ( alter table QUOTE_HOUSE add TESTCOL Varchar2 ( 20 ) ) - to have column in database that is being injected at runtime in model . You might also need to debug EF assemblies here 's how to do it . Please let me know if you need more info or I have missed something . <code> public class DynamicEntity : DynamicObject { Dictionary < string , object > dynamicMembers = new Dictionary < string , object > ( ) ; public override bool TrySetMember ( SetMemberBinder binder , object value ) { dynamicMembers [ binder.Name ] = value ; return true ; } public override bool TryGetMember ( GetMemberBinder binder , out object result ) { if ( dynamicMembers.TryGetValue ( binder.Name , out result ) ) { return dynamicMembers.TryGetValue ( binder.Name , out result ) ; } result = `` '' ; return true ; } } private void UpdateEntitySetMappings ( ) { ObjectItemCollection objectItemCollection = ( ObjectItemCollection ) this._workspace.GetItemCollection ( DataSpace.OSpace ) ; ReadOnlyCollection < EntityType > items = this._workspace.GetItems < EntityType > ( DataSpace.OSpace ) ; Stack < EntityType > entityTypeStack = new Stack < EntityType > ( ) ; foreach ( EntityType entityType1 in items ) { entityTypeStack.Clear ( ) ; EntityType cspaceType = ( EntityType ) this._workspace.GetEdmSpaceType ( ( StructuralType ) entityType1 ) ; do { entityTypeStack.Push ( cspaceType ) ; cspaceType = ( EntityType ) cspaceType.BaseType ; } while ( cspaceType ! = null ) ; EntitySet entitySet = ( EntitySet ) null ; while ( entitySet == null & & entityTypeStack.Count > 0 ) { cspaceType = entityTypeStack.Pop ( ) ; foreach ( EntityContainer entityContainer in this._workspace.GetItems < EntityContainer > ( DataSpace.CSpace ) ) { List < EntitySetBase > list = entityContainer.BaseEntitySets.Where < EntitySetBase > ( ( Func < EntitySetBase , bool > ) ( s = > s.ElementType == cspaceType ) ) .ToList < EntitySetBase > ( ) ; int count = list.Count ; if ( count > 1 || count == 1 & & entitySet ! = null ) throw Error.DbContext_MESTNotSupported ( ) ; if ( count == 1 ) entitySet = ( EntitySet ) list [ 0 ] ; } } if ( entitySet ! = null ) { EntityType entityType2 = ( EntityType ) this._workspace.GetObjectSpaceType ( ( StructuralType ) cspaceType ) ; Type clrType1 = objectItemCollection.GetClrType ( ( StructuralType ) entityType1 ) ; Type clrType2 = objectItemCollection.GetClrType ( ( StructuralType ) entityType2 ) ; this._entitySetMappingsCache [ clrType1 ] = new EntitySetTypePair ( entitySet , clrType2 ) ; } } } public class SystemToDatabaseMapping { public SystemToDatabaseMapping ( string system , string databaseType , string database , string connectionString , Type enitityType ) { System = system ; Database = database ; DatabaseType = databaseType ; ConnectionString = connectionString ; EntityType = enitityType ; } public Type EntityType { get ; set ; } public string System { get ; set ; } public string Database { get ; set ; } public string DatabaseType { get ; set ; } public string ConnectionString { get ; set ; } public List < ColumnToModify > ColumnsToModify { get ; set ; } } public abstract class ColumnToModify { protected ColumnToModify ( string table , string column ) { Table = table ; Column = column ; } public string Table { get ; set ; } public string Column { get ; set ; } public abstract bool IsRemove { get ; } } public class ColumnToRemove : ColumnToModify { public ColumnToRemove ( string table , string column ) : base ( table , column ) { } public override bool IsRemove { get { return true ; } } } public class ColumnToAdd : ColumnToModify { public ColumnToAdd ( string table , string column , Type type ) : base ( table , column ) { this.Type = type ; } public override bool IsRemove { get { return false ; } } public Type Type { get ; set ; } } public partial class QUOTE_HOUSE : DynamicEntity { public long UNIQUE_ID { get ; set ; } } public partial class EcomEntities : DbContext { public EcomEntities ( DbConnection connectionString ) : base ( connectionString , false ) { } public virtual DbSet < QUOTE_HOUSE > QUOTE_HOUSE { get ; set ; } ... . } public static class EntityConnectionExtensions { public static IEnumerable < XElement > ElementsAnyNS < T > ( this IEnumerable < T > source , string localName ) where T : XContainer { return source.Elements ( ) .Where ( e = > e.Name.LocalName == localName ) ; } public static IEnumerable < XElement > ElementsAnyNS ( this XContainer source , string localName ) { return source.Elements ( ) .Where ( e = > e.Name.LocalName == localName ) ; } private static void ModifyNodes ( XElement element , List < ColumnToModify > tableAndColumn ) { if ( element.Attribute ( `` Name '' ) ! = null & & tableAndColumn.Any ( oo = > oo.Table == element.Attribute ( `` Name '' ) .Value ) || element.Attribute ( `` StoreEntitySet '' ) ! = null & & tableAndColumn.Any ( oo = > oo.Table == element.Attribute ( `` StoreEntitySet '' ) .Value ) ) { var matchingRemoveSelectParts = tableAndColumn.Where ( oo = > oo.IsRemove & & element.Value.Contains ( string.Format ( `` \ '' { 0 } \ '' .\ '' { 1 } \ '' AS \ '' { 1 } \ '' '' , oo.Table , oo.Column ) ) ) .ToList ( ) ; if ( matchingRemoveSelectParts.Any ( ) ) { foreach ( var matchingRemoveSelectPart in matchingRemoveSelectParts ) { var definingQuery = element.ElementsAnyNS ( `` DefiningQuery '' ) .Single ( ) ; definingQuery.Value = definingQuery.Value.Replace ( string.Format ( `` , \n\ '' { 0 } \ '' .\ '' { 1 } \ '' AS \ '' { 1 } \ '' '' , matchingRemoveSelectPart.Table , matchingRemoveSelectPart.Column ) , `` '' ) ; } } else { var nodesToRemove = element.Nodes ( ) .Where ( o = > o is XElement & & ( ( XElement ) o ) .Attribute ( `` Name '' ) ! = null & & tableAndColumn.Any ( oo = > oo.IsRemove & & ( ( XElement ) o ) .Attribute ( `` Name '' ) .Value == oo.Column ) ) ; foreach ( var node in nodesToRemove.ToList ( ) ) { node.Remove ( ) ; } if ( element.Attribute ( `` Name '' ) ! = null & & tableAndColumn.Any ( oo = > oo.Table == element.Attribute ( `` Name '' ) .Value ) ) { var elementsToAdd = tableAndColumn.Where ( o = > ! o.IsRemove & & o.Table == element.Attribute ( `` Name '' ) .Value ) ; if ( new [ ] { `` Type=\ '' number\ '' '' , `` Type=\ '' varchar2\ '' '' , `` Type=\ '' date\ '' '' } .Any ( o = > element.ToString ( ) .Contains ( o ) ) ) { foreach ( var columnToModify in elementsToAdd ) { var columnToAdd = ( ColumnToAdd ) columnToModify ; var type = new [ ] { typeof ( decimal ) , typeof ( float ) , typeof ( int ) , typeof ( bool ) } .Contains ( columnToAdd.Type ) ? `` number '' : columnToAdd.Type == typeof ( DateTime ) ? `` date '' : `` varchar2 '' ; var precision = `` '' ; var scale = `` '' ; var maxLength = `` '' ; if ( type == `` number '' ) { precision = `` 38 '' ; scale = new [ ] { typeof ( decimal ) , typeof ( float ) } .Contains ( columnToAdd.Type ) ? `` 2 '' : `` 0 '' ; } if ( type == `` varchar2 '' ) { maxLength = `` 500 '' ; } var newProperty = new XElement ( element.GetDefaultNamespace ( ) + `` Property '' , new XAttribute ( `` Name '' , columnToAdd.Column ) , new XAttribute ( `` Type '' , type ) ) ; if ( ! string.IsNullOrWhiteSpace ( precision ) ) { newProperty.Add ( new XAttribute ( `` Precision '' , precision ) ) ; } if ( ! string.IsNullOrWhiteSpace ( scale ) ) { newProperty.Add ( new XAttribute ( `` Scale '' , scale ) ) ; } if ( ! string.IsNullOrWhiteSpace ( maxLength ) ) { newProperty.Add ( new XAttribute ( `` MaxLength '' , maxLength ) ) ; } element.Add ( newProperty ) ; } } else if ( new [ ] { `` Type=\ '' Decimal\ '' '' , `` Type=\ '' String\ '' '' , `` Type=\ '' DateTime\ '' '' , `` Type=\ '' Boolean\ '' '' , `` Type=\ '' Byte\ '' '' , `` Type=\ '' Int16\ '' '' , `` Type=\ '' Int32\ '' '' , `` Type=\ '' Int64\ '' '' } .Any ( o = > element.ToString ( ) .Contains ( o ) ) ) { foreach ( var columnToModify in elementsToAdd ) { var columnToAdd = ( ColumnToAdd ) columnToModify ; var type = new [ ] { typeof ( decimal ) , typeof ( float ) , typeof ( int ) , typeof ( bool ) } .Contains ( columnToAdd.Type ) ? `` Decimal '' : columnToAdd.Type == typeof ( DateTime ) ? `` DateTime '' : `` String '' ; var precision = `` '' ; var scale = `` '' ; var maxLength = `` '' ; if ( type == `` Decimal '' ) { precision = `` 38 '' ; scale = new [ ] { typeof ( decimal ) , typeof ( float ) } .Contains ( columnToAdd.Type ) ? `` 2 '' : `` 0 '' ; } if ( type == `` String '' ) { maxLength = `` 500 '' ; } var newProperty = new XElement ( element.GetDefaultNamespace ( ) + `` Property '' , new XAttribute ( `` Name '' , columnToAdd.Column ) , new XAttribute ( `` Type '' , type ) ) ; if ( ! string.IsNullOrWhiteSpace ( precision ) ) { newProperty.Add ( new XAttribute ( `` Precision '' , precision ) ) ; } if ( ! string.IsNullOrWhiteSpace ( scale ) ) { newProperty.Add ( new XAttribute ( `` Scale '' , scale ) ) ; } if ( ! string.IsNullOrWhiteSpace ( maxLength ) ) { newProperty.Add ( new XAttribute ( `` MaxLength '' , maxLength ) ) ; newProperty.Add ( new XAttribute ( `` FixedLength '' , `` false '' ) ) ; newProperty.Add ( new XAttribute ( `` Unicode '' , `` false '' ) ) ; } element.Add ( newProperty ) ; } } } } if ( element.Attribute ( `` Name '' ) ! = null & & tableAndColumn.Any ( oo = > oo.Table == element.Attribute ( `` Name '' ) .Value ) & & element.GetNamespaceOfPrefix ( `` store '' ) ! = null & & element.Attribute ( element.GetNamespaceOfPrefix ( `` store '' ) + `` Type '' ) ! = null & & element.Attribute ( element.GetNamespaceOfPrefix ( `` store '' ) + `` Type '' ) .Value == `` Tables '' ) { var matchingAddSelectParts = tableAndColumn.Where ( o = > ! o.IsRemove & & o.Table == element.Attribute ( `` Name '' ) .Value ) ; foreach ( var matchingAddSelectPart in matchingAddSelectParts ) { var definingQuery = element.ElementsAnyNS ( `` DefiningQuery '' ) .Single ( ) ; var schemaRegex = new Regex ( string.Format ( `` \\nFROM \\\ '' ( [ a-zA-Z0-9 ] * ) \\\ '' .\\\ '' { 0 } \\\ '' '' , matchingAddSelectPart.Table ) ) ; var schema = schemaRegex.Matches ( definingQuery.Value ) [ 0 ] .Groups [ 1 ] .Value ; definingQuery.Value = definingQuery.Value.Replace ( string.Format ( `` \nFROM \ '' { 0 } \ '' .\ '' { 1 } \ '' \ '' { 1 } \ '' '' , schema , matchingAddSelectPart.Table ) , string.Format ( `` , \n\ '' { 0 } \ '' .\ '' { 1 } \ '' AS \ '' { 1 } \ '' \nFROM \ '' { 2 } \ '' .\ '' { 0 } \ '' \ '' { 0 } \ '' '' , matchingAddSelectPart.Table , matchingAddSelectPart.Column , schema ) ) ; } } if ( element.Attribute ( `` StoreEntitySet '' ) ! = null & & tableAndColumn.Any ( oo = > ! oo.IsRemove & & oo.Table == element.Attribute ( `` StoreEntitySet '' ) .Value ) ) { var matchingAddSelectParts = tableAndColumn.Where ( o = > ! o.IsRemove & & o.Table == element.Attribute ( `` StoreEntitySet '' ) .Value ) ; foreach ( var matchingAddSelectPart in matchingAddSelectParts ) { element.Add ( new XElement ( element.GetDefaultNamespace ( ) + `` ScalarProperty '' , new XAttribute ( `` Name '' , matchingAddSelectPart.Column ) , new XAttribute ( `` ColumnName '' , matchingAddSelectPart.Column ) ) ) ; } } } } public static EntityConnection Create ( List < ColumnToModify > tablesAndColumns , string connString ) { var modelNameRegex = new Regex ( @ '' .*metadata=res : \/\/\*\/ ( [ a-zA-Z. ] * ) .csdl| . * '' ) ; var model = modelNameRegex.Matches ( connString ) .Cast < Match > ( ) .SelectMany ( o = > o.Groups.Cast < Group > ( ) .Skip ( 1 ) .Where ( oo = > oo.Value ! = `` '' ) ) .Select ( o = > o.Value ) .First ( ) ; var conceptualReader = XmlReader.Create ( Assembly.GetExecutingAssembly ( ) .GetManifestResourceStream ( model + `` .csdl '' ) ) ; var mappingReader = XmlReader.Create ( Assembly.GetExecutingAssembly ( ) .GetManifestResourceStream ( model + `` .msl '' ) ) ; var storageReader = XmlReader.Create ( Assembly.GetExecutingAssembly ( ) .GetManifestResourceStream ( model + `` .ssdl '' ) ) ; var conceptualXml = XElement.Load ( conceptualReader ) ; var mappingXml = XElement.Load ( mappingReader ) ; var storageXml = XElement.Load ( storageReader ) ; foreach ( var entitySet in new [ ] { storageXml , conceptualXml } .SelectMany ( xml = > xml.Elements ( ) ) ) { if ( entitySet.Attribute ( `` Name '' ) .Value == `` ModelStoreContainer '' ) { foreach ( var entityContainerEntitySet in entitySet.Elements ( ) ) { ModifyNodes ( entityContainerEntitySet , tablesAndColumns ) ; } } ModifyNodes ( entitySet , tablesAndColumns ) ; } foreach ( var entitySet in mappingXml.Elements ( ) .ElementAt ( 0 ) .Elements ( ) ) { if ( entitySet.Name.LocalName == `` EntitySetMapping '' ) { foreach ( var entityContainerEntitySet in entitySet.Elements ( ) .First ( ) .Elements ( ) ) { ModifyNodes ( entityContainerEntitySet , tablesAndColumns ) ; } } ModifyNodes ( entitySet , tablesAndColumns ) ; } var storageCollection = new StoreItemCollection ( new [ ] { storageXml.CreateReader ( ) } ) ; var conceptualCollection = new EdmItemCollection ( new [ ] { conceptualXml.CreateReader ( ) } ) ; var mappingCollection = new StorageMappingItemCollection ( conceptualCollection , storageCollection , new [ ] { mappingXml.CreateReader ( ) } ) ; var workspace = new MetadataWorkspace ( ) ; workspace.RegisterItemCollection ( conceptualCollection ) ; workspace.RegisterItemCollection ( storageCollection ) ; workspace.RegisterItemCollection ( mappingCollection ) ; var connectionData = new EntityConnectionStringBuilder ( connString ) ; var connection = DbProviderFactories .GetFactory ( connectionData.Provider ) .CreateConnection ( ) ; connection.ConnectionString = connectionData.ProviderConnectionString ; return new EntityConnection ( workspace , connection ) ; } } public ActionResult QUOTE_HOUSE ( ) { var onlineDocs = Enumerable.Empty < QUOTE_HOUSE > ( ) ; var mappings = new List < SagaSystemToDatabaseMapping > { new SagaSystemToDatabaseMapping ( `` x '' , `` Oracle '' , `` Db1 '' , `` metadata=res : //*/Ecom.Ecom.csdl|res : //*/Ecom.Ecom.ssdl|res : //*/Ecom.Ecom.msl ; provider=Oracle.ManagedDataAccess.Client ; provider connection string= ' ... ' '' , typeof ( EcomEntities ) ) { ColumnsToModify = new List < ColumnToModify > { new ColumnToAdd ( `` QUOTE_HOUSE '' , '' TESTCOL '' , typeof ( string ) ) } } } ; var entityConnection = EntityConnectionExtensions.Create ( mappings [ 0 ] .ColumnsToModify , mappings [ 0 ] .ConnectionString ) ; using ( var db = new EcomEntities ( entityConnection ) ) { onlineDocs = db.QUOTE_HOUSE.Take ( 10 ) ; } return View ( `` QUOTE_HOUSE '' , onlineDocs.ToList ( ) ) ; } | Entity Framework entity is not in DataSpace.OSpace ( _workspace.GetItemCollection ( DataSpace.OSpace ) ) but is in DataSpace.CSpace |
C_sharp : I 've stumbled upon this code : where path is a string and the return value should be a string as well.Allthough path.Contains ' intellisense suggests a parameter , it works fine without one.How does this work exactly ? Is there any way to copy this behavior in vb.net ? <code> var knownSeparators = new [ ] { `` \\ '' , `` / '' , `` | '' , `` . '' } ; return knownSeparators.FirstOrDefault ( path.Contains ) ; | String.Contains does n't require parameters in c # ? |
C_sharp : I am creating Traces for a method and want it to use with a custom attribute . I will decorate each method with TraceMethod.eg : So here , How to call StartTrace ( ) before the SomeMethod start executing and EndTrace ( ) after the execution of SomeMethod ends ? Is it possible ? <code> [ TraceMethod ( ) ] public void SomeMethod ( ) { } public class TraceMethod : Attribute { public void StartTrace ( ) { } public void EndTrace ( ) { } } | Identity Start and End of a method |
C_sharp : This is what I am trying to getThis is how I get Foo typeThis is what I tried but could n't make it successfullyand also this ; this is method where I am trying to implement <code> ( IList < Foo > ) listPropertyInfo.GetValue ( item ) listPropertyInfo.GetValue ( item ) .GetType ( ) .GenericTypeArguments [ 0 ] Convert.ChangeType ( listPropertyInfo.GetValue ( item ) , IList < listPropertyInfo.GetValue ( item ) .GetType ( ) .GenericTypeArguments [ 0 ] > ) ( ( typeof ( IList < > ) .MakeGenericType ( listPropertyInfo.GetValue ( item ) .GetType ( ) .GenericTypeArguments.Single ( ) ) ) ) ( listPropertyInfo.GetValue ( item ) ) public static void trigger ( IList < T > result ) { foreach ( var item in result ) { foreach ( var listPropertyInfo in typeof ( T ) .GetProperties ( ) .ToList ( ) .FindAll ( x = > x.PropertyType.Name == typeof ( IList < > ) .Name ) ) { trigger ( ( IList < Foo > ) listPropertyInfo.GetValue ( item ) ) ; } } } | Changing Type at Runtime with GenericTypeArgument |
C_sharp : I have two pieces of code that are identical in C # and Java . But the Java one goes twice as fast . I want to know why . Both work with the same principal of using a big lookup table for performance.Why is the Java going 50 % faster than C # ? Java code : It just enumerates through all possible 7 card combinations . The C # version is identical except at the end it uses Console.writeLine.The lookuptable is defined as : Its size in memory is about 120 Megabytes.The C # version has the same test code . It 's measured with Stopwatch instead of nanoTime ( ) and uses Console.WriteLine instead of System.out.println ( `` '' ) but it takes at least double the time.Java takes about 400ms . For compilation in java I use the -server flag . In C # the build is set to release without debug or trace defines.What is responsible for the speed difference ? <code> int h1 , h2 , h3 , h4 , h5 , h6 , h7 ; int u0 , u1 , u2 , u3 , u4 , u5 ; long time = System.nanoTime ( ) ; long sum = 0 ; for ( h1 = 1 ; h1 < 47 ; h1++ ) { u0 = handRanksj [ 53 + h1 ] ; for ( h2 = h1 + 1 ; h2 < 48 ; h2++ ) { u1 = handRanksj [ u0 + h2 ] ; for ( h3 = h2 + 1 ; h3 < 49 ; h3++ ) { u2 = handRanksj [ u1 + h3 ] ; for ( h4 = h3 + 1 ; h4 < 50 ; h4++ ) { u3 = handRanksj [ u2 + h4 ] ; for ( h5 = h4 + 1 ; h5 < 51 ; h5++ ) { u4 = handRanksj [ u3 + h5 ] ; for ( h6 = h5 + 1 ; h6 < 52 ; h6++ ) { u5 = handRanksj [ u4 + h6 ] ; for ( h7 = h6 + 1 ; h7 < 53 ; h7++ ) { sum += handRanksj [ u5 + h7 ] ; } } } } } } } double rtime = ( System.nanoTime ( ) - time ) /1e9 ; // time given is start time System.out.println ( sum ) ; static int handRanksj [ ] ; | C # is half as slow than Java in memory access with loops ? |
C_sharp : Is there a property in some class that can tell me if the current culture is actually the default culture.Similar to how localization works with winforms . It states in a form if the language is default.lets say if i am in en-US - how can i tell via code if en.US is the actual default ? I need to implement some localization for some XML files which .net does n't support hence i want to implement my own ... And do it how winforms works i.eetcdoes a property exist ? <code> nameofxml.default.xml ( this is the default local ) nameofXml.de-de.xml ( this is german ) | c # : In a dotnet class is there a property that states if the `` Current '' culture is actual the default culture ? |
C_sharp : Is it possible to create a list of anonymous delegates in C # ? Here is code I would love to write but it does n't compile : <code> Action < int > method ; List < method > operations = new List < method > ( ) ; | Is List < T > where T is an anonymous delegate possible ? |
C_sharp : I new to C # and have a question regarding the use of `` var '' When I use the following code everything works greatBut when I change DataGridViewRow to var I get and error that states 'object ' does not contain definition for 'Cells ' and no extension method 'Cells ' accepting a first argument of type 'object ' could be found ( are you missing a using directive or an assembly reference ? ) <code> foreach ( DataGridViewRow row in myGrid.Rows ) { if ( row.Cells [ 2 ] .Value.ToString ( ) .Contains ( `` 51000 '' ) ) { row.Cells [ 0 ] .Value = `` X '' ; } } | var wo n't work with DataGridViewRow |
C_sharp : ( while trying to analyze how decimal works ) & & after reading @ jonskeet article and seeing msdn , and thinking for the last 4 hours , I have some questions : in this link they say something very simple : 1.5 x 10^2 has 2 significant figures 1.50 x 10^2 has 3 significant figures.1.500 x 10^2 has 4 significant figures etc ... ok ... we get the idea.from jon 's article : As usual , the sign is just a single bit , but there are 96 bits of mantissa and 5 bits of exponentokso max mantiss val = 2^96-1 = 79228162514264337593543950335 which is : 7.9228162514264*10^28 ( according to my iphone ... could'nt see exponent representation in windows calc . ) notice : 7.9228162514264*10^28 has 14 significant figures ( according to examples above ) now the part with the 5 bit in exponent is irrelevant because its in the denominator - so i need the min val which is 2^0question # 1 : msdn say : 28-29 significant digitsbut according to my sample ( 1.500 x 10^2 has 4 significant figures ) they have 2 significant figures which is 7.9 ( 7 and 9 ) .if msdn would have written : i would understand this , since all significant digits are in the expression.why do they write 28-29 but display 2 ? question # 2 : how will decimal representation ( mantiss & & exponent ) will be displayed for the value 0.5 ? the max denominator can be 2^32-1 -- > 31thanks guys.question # 3 :1+96+5 = 102 bits.msdn says : The decimal keyword denotes a 128-bit data type.could understnad from article why there isnt a usage to those 26 bits <code> sign * mantissa / 10^exponent ^ _ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^___ ^^^^^ 1 _ 96 5 ±79228162514264337593543950335 × 10^0 128-102 = 26 | decimal in c # misunderstanding ? |
C_sharp : One feature of coming C # 9 is so called top-level programs . So that you could just write the following without classes.and dotnet run will launch it for you.It works for me , but only if I also add a .csproj file like the one belowIs there a way to skip .csproj from the picture ? : ) So that there 's just a single Program.cs file and nothing more . <code> using System ; Console.WriteLine ( `` Hello World ! `` ) ; < Project Sdk= '' Microsoft.NET.Sdk '' > < PropertyGroup > < OutputType > Exe < /OutputType > < TargetFramework > net5.0 < /TargetFramework > < /PropertyGroup > < /Project > | C # 9 top-level programs without csproj ? |
C_sharp : I have lots of code like this : As you can see , I use the usual way of doing async operations . how do I change this code to use async await ? Preferably something like this : <code> var feed = new DataFeed ( host , port ) ; feed.OnConnected += ( conn ) = > { feed.BeginLogin ( user , pass ) ; } ; feed.OnReady += ( f ) = > { //Now I 'm ready to do stuff . } ; feed.BeginConnect ( ) ; public async void InitConnection ( ) { await feed.BeginConnect ( ) ; await feed.BeginLogin ( user , pass ) ; //Now I 'm ready } | How to convert this code to async await ? |
C_sharp : I have a method that returns an object and also has an out parameter . The method calls another method that takes in the same out paramter as another out paramter . This gives a build error on the return statement : The out parameter 'param1 ' must be assigned to before control leaves the current methodThe code looks like : param2 is manipulated in SubMethod ( ) , not in Method1 ( ) . Is there something else I need to do ? <code> public TypeA Method1 ( TypeA param1 , out bool param2 ) { / ... some logic here ... / SubMethod ( out param2 ) ; / ... some logic here ... / return param1 ; } | How to assign out parameter in function ? |
C_sharp : I created an API wrapper class library for consuming a rest API from a 3rd party.It was all working until they recently updated the API in the latest version of their product and added a namespace to the root element , now my deserialization code is failing.An example of one of my classes : If I set the Namespace property in the XmlRootAttribute to the new namespace being returned , then it works properly again.But I need to support both versions of the API ( namespaced and not ) because I can not be sure which version of the API will be available.I 'd like to get this working without duplicating classes for different versions , but not sure if it 's possible.Thanks for any input/advice . <code> [ Serializable ] [ XmlRootAttribute ( ElementName = `` exit_survey_list '' ) ] public class SupportExitSurveyCollection : ApiResult { ... . } | C # deserializing xml with multiple possible namespaces |
C_sharp : { 0 , -12 } is the part i 'm curious about..I 'm looking at this example Cheers : ) <code> Console.WriteLine ( `` { 0 , -12 } { 1 } '' , sqlReader.GetName ( 0 ) , sqlReader.GetName ( 1 ) ) ; | Can someone tell me what this means WriteLine ( `` { 0 , -12 } '' ) |
C_sharp : I have two following methodsShould second method be marked with async/await keywords or not ? <code> public async Task < bool > DoSomething ( CancellationToken.token ) { //do something async } //overload with None token public /*async*/ Task < bool > DoSomething ( ) { return /*await*/ DoSomething ( CancellationToken.None ) ; } | Should method that get Task and passes it away await it ? |
C_sharp : In my current project , a method I do n't control sends me an object of this type : I display those data in a TreeView , but I would like to display only the path ending with SampleClass objects having their Type property set to type3 , no matter the depth of this leaf.I have absolutely no clue on how to do that , can someone help me ? Thanks in advance ! EditTo explain the problem I meet with the solutions proposed by Shahrooz Jefri and dasblinkenlight , here is a picture . The left column is the original data , without filtering , and the right one is the data filtered . Both methods provide the same result.In red is the problem . <code> public class SampleClass { public SampleClass ( ) ; public int ID { get ; set ; } public List < SampleClass > Items { get ; set ; } public string Name { get ; set ; } public SampleType Type { get ; set ; } } public enum SampleType { type1 , type2 , type3 } | How to filter a recursive object ? |
C_sharp : Could someone please explain to me what the following lines of code do ? I 've searched the msdn library , but could n't really understand what it did.This is n't the full code , but I undertand the rest , it is just this part that I 'm struggling with . <code> dynamic shellApplication = Activator.CreateInstance ( Type.GetTypeFromProgID ( `` Shell.Application '' ) ) ; string path = System.IO.Path.GetDirectoryName ( filePath ) ; string fileName = System.IO.Path.GetFileName ( filePath ) ; dynamic directory = shellApplication.NameSpace ( path ) ; dynamic link = directory.ParseName ( fileName ) ; dynamic verbs = link.Verbs ( ) ; | What is this code doing ? |
C_sharp : I have the following code where I 'm printing values before the Main ( ) method gets called by using a static constructor . How can I print another value after Main ( ) has returned , without modifying the Main ( ) method ? I want output like : The `` base '' code I use : I added a static constructor to Myclass for displaying `` 1st '' Now What i need to do to is to print 3rd without modifying the Main ( ) method . How do I do that , if it is at all possible ? <code> 1st 2nd 3rd class Myclass { static void Main ( string [ ] args ) { Console.WriteLine ( `` 2nd '' ) ; } } class Myclass { static Myclass ( ) { Console.WriteLine ( `` 1st '' ) ; } //it will print 1st static void Main ( string [ ] args ) { Console.WriteLine ( `` 2nd '' ) ; // it will print 2nd } } | How do i print any value after Main ( ) method gets called ? |
C_sharp : Continuing my F # performance testing . For some more background see here : f # NativePtr.stackalloc in Struct ConstructorF # NativePtr.stackalloc Unexpected Stack OverflowNow I 've got stack arrays working in F # . However , for some reason the equivalent C # is approximately 50x faster . I 've included the ILSpy decompiled versions below and it appears only 1 line is really different ( inside stackAlloc ) .What 's going on here ? Is the unchecked arithmetic really responsible for this big difference ? Not sure how I could test this ? ? https : //msdn.microsoft.com/en-us/library/a569z7k8.aspxF # CodeC # CodeF # Version DecompiledC # Version DecompiledF # Version IL - Byte AllocationC # Version IL - Byte AllocationUpdated F # IL - IntPtr AllocationUpdated C # IL - IntPtr Allocation <code> # nowarn `` 9 '' open Microsoft.FSharp.NativeInteropopen Systemopen System.Diagnostics open System.Runtime.CompilerServices [ < MethodImpl ( MethodImplOptions.NoInlining ) > ] let stackAlloc x = let mutable ints : nativeptr < byte > = NativePtr.stackalloc x ( ) [ < EntryPoint > ] let main argv = printfn `` % A '' argv let size = 8192 let reps = 10000 stackAlloc size // JIT let clock = Stopwatch ( ) clock.Start ( ) for i = 1 to reps do stackAlloc size clock.Stop ( ) let elapsed = clock.Elapsed.TotalMilliseconds let description = `` F # NativePtr.stackalloc '' Console.WriteLine ( `` { 0 } ( { 1 } bytes , { 2 } reps ) : { 3 : # , # # 0. # # # # } ms '' , description , size , reps , elapsed ) Console.ReadKey ( ) | > ignore 0 using System ; using System.Diagnostics ; namespace CSharpLanguageFeatures { class CSharpStackArray { static void Main ( string [ ] args ) { int size = 8192 ; int reps = 10000 ; stackAlloc ( size ) ; // JIT Stopwatch clock = new Stopwatch ( ) ; clock.Start ( ) ; for ( int i = 0 ; i < reps ; i++ ) { stackAlloc ( size ) ; } clock.Stop ( ) ; string elapsed = clock.Elapsed.TotalMilliseconds.ToString ( `` # , # # 0. # # # # '' ) ; string description = `` C # stackalloc '' ; Console.WriteLine ( `` { 0 } ( { 1 } bytes , { 2 } reps ) : { 3 : # , # # 0. # # # # } ms '' , description , size , reps , elapsed ) ; Console.ReadKey ( ) ; } public unsafe static void stackAlloc ( int arraySize ) { byte* pArr = stackalloc byte [ arraySize ] ; } } } using Microsoft.FSharp.Core ; using System ; using System.Diagnostics ; using System.IO ; using System.Runtime.CompilerServices ; [ CompilationMapping ( SourceConstructFlags.Module ) ] public static class FSharpStackArray { [ MethodImpl ( MethodImplOptions.NoInlining ) ] public unsafe static void stackAlloc ( int x ) { IntPtr ints = stackalloc byte [ x * sizeof ( byte ) ] ; } [ EntryPoint ] public static int main ( string [ ] argv ) { PrintfFormat < FSharpFunc < string [ ] , Unit > , TextWriter , Unit , Unit > format = new PrintfFormat < FSharpFunc < string [ ] , Unit > , TextWriter , Unit , Unit , string [ ] > ( `` % A '' ) ; PrintfModule.PrintFormatLineToTextWriter < FSharpFunc < string [ ] , Unit > > ( Console.Out , format ) .Invoke ( argv ) ; FSharpStackArray.stackAlloc ( 8192 ) ; Stopwatch clock = new Stopwatch ( ) ; clock.Start ( ) ; for ( int i = 1 ; i < 10001 ; i++ ) { FSharpStackArray.stackAlloc ( 8192 ) ; } clock.Stop ( ) ; double elapsed = clock.Elapsed.TotalMilliseconds ; Console.WriteLine ( `` { 0 } ( { 1 } bytes , { 2 } reps ) : { 3 : # , # # 0. # # # # } ms '' , `` F # NativePtr.stackalloc '' , 8192 , 10000 , elapsed ) ; ConsoleKeyInfo consoleKeyInfo = Console.ReadKey ( ) ; return 0 ; } } using System ; using System.Diagnostics ; namespace CSharpLanguageFeatures { internal class CSharpStackArray { private static void Main ( string [ ] args ) { int size = 8192 ; int reps = 10000 ; CSharpStackArray.stackAlloc ( size ) ; Stopwatch clock = new Stopwatch ( ) ; clock.Start ( ) ; for ( int i = 0 ; i < reps ; i++ ) { CSharpStackArray.stackAlloc ( size ) ; } clock.Stop ( ) ; string elapsed = clock.Elapsed.TotalMilliseconds.ToString ( `` # , # # 0. # # # # '' ) ; string description = `` C # stackalloc '' ; Console.WriteLine ( `` { 0 } ( { 1 } bytes , { 2 } reps ) : { 3 : # , # # 0. # # # # } ms '' , new object [ ] { description , size , reps , elapsed } ) ; Console.ReadKey ( ) ; } public unsafe static void stackAlloc ( int arraySize ) { IntPtr arg_06_0 = stackalloc byte [ checked ( unchecked ( ( UIntPtr ) arraySize ) * 1 ) ] ; } } } .method public static void stackAlloc ( int32 x ) cil managed noinlining { // Method begins at RVA 0x2050 // Code size 13 ( 0xd ) .maxstack 4 .locals init ( [ 0 ] native int ints ) IL_0000 : nop IL_0001 : ldarg.0 IL_0002 : sizeof [ mscorlib ] System.Byte IL_0008 : mul IL_0009 : localloc IL_000b : stloc.0 IL_000c : ret } // end of method FSharpStackArray : :stackAlloc .method public hidebysig static void stackAlloc ( int32 arraySize ) cil managed { // Method begins at RVA 0x2094 // Code size 8 ( 0x8 ) .maxstack 8 IL_0000 : ldarg.0 IL_0001 : conv.u IL_0002 : ldc.i4.1 IL_0003 : mul.ovf.un IL_0004 : localloc IL_0006 : pop IL_0007 : ret } // end of method CSharpStackArray : :stackAlloc .method public static void stackAlloc ( int32 x ) cil managed noinlining { // Method begins at RVA 0x2050 // Code size 13 ( 0xd ) .maxstack 4 .locals init ( [ 0 ] native int ints ) IL_0000 : nop IL_0001 : ldarg.0 IL_0002 : sizeof [ mscorlib ] System.IntPtr IL_0008 : mul IL_0009 : localloc IL_000b : stloc.0 IL_000c : ret } // end of method FSharpStackArray : :stackAlloc .method public hidebysig static void stackAlloc ( int32 arraySize ) cil managed { // Method begins at RVA 0x2415 // Code size 13 ( 0xd ) .maxstack 8 IL_0000 : ldarg.0 IL_0001 : conv.u IL_0002 : sizeof [ mscorlib ] System.IntPtr IL_0008 : mul.ovf.un IL_0009 : localloc IL_000b : pop IL_000c : ret } // end of method CSharpStackArray : :stackAlloc | F # NativePtr.stackalloc slower then C # stackalloc - Decompiled Code Included |
C_sharp : I have created a sample project . I am serializing the following types : Program code ( console app for simplicity ) : The result of serialization is just perfect : result string contains all the data I 've putted to the tree before . However , deserialization of that string with the same serializer settings is incorrect : result object has no children at all . Maybe the main problem is attributes ... What 's the reason of behavior like this ? <code> [ JsonObject ( IsReference = true , ItemReferenceLoopHandling = ReferenceLoopHandling.Serialize ) ] public class SampleTree : Dictionary < string , SampleTree > { [ JsonProperty ( ReferenceLoopHandling = ReferenceLoopHandling.Serialize ) ] public SampleClass Value { get ; set ; } [ JsonProperty ( IsReference = true , ReferenceLoopHandling = ReferenceLoopHandling.Serialize ) ] public SampleTree Parent { get ; set ; } } [ JsonObject ( IsReference = true ) ] public class SampleClass { public string A { get ; set ; } public int B { get ; set ; } public bool C { get ; set ; } } static void Main ( string [ ] args ) { var tree = new SampleTree { Value = new SampleClass { A = `` abc '' , B = 1 , C = true } , Parent = null } ; var treeChild = new SampleTree { Value = new SampleClass { A = `` def '' , B = 2 , C = false } , Parent = tree } ; tree.Add ( `` firstChild '' , treeChild ) ; var serializerSettings = new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.All , ReferenceLoopHandling = ReferenceLoopHandling.Serialize , Formatting = Formatting.Indented } ; var serialized = JsonConvert.SerializeObject ( tree , serializerSettings ) ; var deserialized = JsonConvert.DeserializeObject < SampleTree > ( serialized , serializerSettings ) ; var d = deserialized ; } | Serializing and deserializing of type T , derived from Dictionary < string , T > , using Json.NET |
C_sharp : I need to use Dictionary < long , string > collections that given two instances d1 and d2 where they each have the same KeyValuePair < long , string > contents , which could be inserted in any order : ( d1 == d2 ) evaluates to trued1.GetHashCode ( ) == d2.GetHashCode ( ) The first requirement was achieved most easily by using a SortedDictionary instead of a regular Dictionary.The second requirement is necessary because I have one point where I need to store Dictionary < Dictionary < long , string > , List < string > - the main Dictionary type is used as the key for another Dictionary , and if the HashCodes do n't evaluate based on identical contents , the using ContainsKey ( ) will not work the way that I want ( ie : if there is already an item inserted into the dictionary with d1 as its key , then dictionary.ContainsKey ( d2 ) should evaluate to true.To achieve this , I have created a new object class ComparableDictionary : SortedDictionary < long , string > , and have included the following : In my unit testing , this meets the criteria for both equality and hashcodes . However , in reading Guidelines and Rules for GetHashCode , I came across the following : Rule : the integer returned by GetHashCode must never change while the object is contained in a data structure that depends on the hash code remaining stableIt is permissible , though dangerous , to make an object whose hash code value can mutate as the fields of the object mutate . If you have such an object and you put it in a hash table then the code which mutates the object and the code which maintains the hash table are required to have some agreed-upon protocol that ensures that the object is not mutated while it is in the hash table . What that protocol looks like is up to you.If an object 's hash code can mutate while it is in the hash table then clearly the Contains method stops working . You put the object in bucket # 5 , you mutate it , and when you ask the set whether it contains the mutated object , it looks in bucket # 74 and does n't find it.Remember , objects can be put into hash tables in ways that you did n't expect . A lot of the LINQ sequence operators use hash tables internally . Do n't go dangerously mutating objects while enumerating a LINQ query that returns them ! Now , the Dictionary < ComparableDictionary , List < String > > is used only once in code , in a place where the contents of all ComparableDictionary collections should be set . Thus , according to these guidelines , I think that it would be acceptable to override GetHashCode as I have done ( basing it completely on the contents of the dictionary ) .After that introduction my questions are : I know that the performance of SortedDictionary is very poor compared to Dictionary ( and I can have hundreds of object instantiations ) . The only reason for using SortedDictionary is so that I can have the equality comparison work based on the contents of the dictionary , regardless of order of insertion . Is there a better way to achieve this equality requirement without having to use a SortedDictionary ? Is my implementation of GetHashCode acceptable based on the requirements ? Even though it is based on mutable contents , I do n't think that that should pose any risk , since the only place where it is using ( I think ) is after the contents have been set.Note : while I have been setting these up using Dictionary or SortedDictionary , I am not wedded to these collection types . The main need is a collection that can store pairs of values , and meet the equality and hashing requirements defined out above . <code> public override int GetHashCode ( ) { StringBuilder str = new StringBuilder ( ) ; foreach ( var item in this ) { str.Append ( item.Key ) ; str.Append ( `` _ '' ) ; str.Append ( item.Value ) ; str.Append ( `` % % '' ) ; } return str.ToString ( ) .GetHashCode ( ) ; } | Implementation of Dictionary where equivalent contents are equal and return the same hash code regardless of order of insertion |
C_sharp : While testing the performance of floats in .NET , I stumbled unto a weird case : for certain values , multiplication seems way slower than normal . Here is the test case : Results : Why are the results so different for param = 0.9f ? Test parameters : .NET 4.5 , Release build , code optimizations ON , x86 , no debugger attached . <code> using System ; using System.Diagnostics ; namespace NumericPerfTestCSharp { class Program { static void Main ( ) { Benchmark ( ( ) = > float32Multiply ( 0.1f ) , `` \nfloat32Multiply ( 0.1f ) '' ) ; Benchmark ( ( ) = > float32Multiply ( 0.9f ) , `` \nfloat32Multiply ( 0.9f ) '' ) ; Benchmark ( ( ) = > float32Multiply ( 0.99f ) , `` \nfloat32Multiply ( 0.99f ) '' ) ; Benchmark ( ( ) = > float32Multiply ( 0.999f ) , `` \nfloat32Multiply ( 0.999f ) '' ) ; Benchmark ( ( ) = > float32Multiply ( 1f ) , `` \nfloat32Multiply ( 1f ) '' ) ; } static void float32Multiply ( float param ) { float n = 1000f ; for ( int i = 0 ; i < 1000000 ; ++i ) { n = n * param ; } // Write result to prevent the compiler from optimizing the entire method away Console.Write ( n ) ; } static void Benchmark ( Action func , string message ) { // warm-up call func ( ) ; var sw = Stopwatch.StartNew ( ) ; for ( int i = 0 ; i < 5 ; ++i ) { func ( ) ; } Console.WriteLine ( message + `` : { 0 } ms '' , sw.ElapsedMilliseconds ) ; } } } float32Multiply ( 0.1f ) : 7 msfloat32Multiply ( 0.9f ) : 946 msfloat32Multiply ( 0.99f ) : 8 msfloat32Multiply ( 0.999f ) : 7 msfloat32Multiply ( 1f ) : 7 ms | Inconsistent multiplication performance with floats |
C_sharp : I am very new to MVVM and I am stuck with data binding . I have a button on my view page which dynamically creates text boxes but I can not see how I bind these textboxes to my List in ViewModel . In my view i have : The code behind the button is : In my ViewModel i have : I am struggling to see how I get the website textboxes into the viewmodel list . Thank you for your help <code> < Button x : Name= '' btWebsite '' Grid.ColumnSpan= '' 2 '' Width= '' 50 '' Height= '' 50 '' Click= '' btWebsite_Click '' Margin= '' 23,245,259,202 '' > < StackPanel x : Name= '' pnWebsiteButton '' Orientation= '' Horizontal '' > < Image x : Name= '' imgWebsite '' Source= `` Images/webIcon.jpg '' Stretch= '' Fill '' HorizontalAlignment= '' Left '' VerticalAlignment= '' Top '' / > < /StackPanel > < /Button > < GroupBox x : Name= '' grpWebsite '' VerticalAlignment= '' Top '' HorizontalAlignment= '' Left '' Margin= '' 73,245,0,0 '' Grid.ColumnSpan= '' 2 '' Height= '' 51 '' Width= '' 170 '' BorderBrush= '' { x : Null } '' BorderThickness= '' 0 '' > < ScrollViewer x : Name= '' pnScrollWebsite '' VerticalScrollBarVisibility= '' Auto '' HorizontalScrollBarVisibility= '' Disabled '' Margin= '' 0,0,0 , -6 '' > < StackPanel x : Name= '' pnWebsite '' Orientation= '' Vertical '' Grid.ColumnSpan= '' 2 '' HorizontalAlignment= '' Left '' Margin= '' 1,2,0,0 '' VerticalAlignment= '' Top '' IsEnabled= '' True '' > < /StackPanel > < /ScrollViewer > < /GroupBox > private void btWebsite_Click ( object sender , RoutedEventArgs e ) { var newTextBox = new TextBox ( ) ; newTextBox.Text = `` type the website address ... '' ; newTextBox.Foreground = Brushes.Gray ; newTextBox.Width = 150 ; newTextBox.Name = `` txtWebsite '' + iWebsites ; pnWebsite.Children.Add ( newTextBox ) ; pnWebsite.RegisterName ( newTextBox.Name , newTextBox ) ; iWebsites++ ; } public List < string > Websites { get { return _websites ; } set { if ( value ! = _websites ) { _websites = value ; OnPropertyChanged ( `` Websites '' ) ; } } } | Dynamic textbox binding to a list |
C_sharp : I would like to determine the impact that a code change within on override of Equals ( ) in my class would have on the code.When I do Shift-F12 to find all references , Visual Studio returns 126,703 places where I am calling object.Equals ( ) .Is there a way to skip overrides of Equals ( ) method when looking for references ? <code> public override bool Equals ( object obj ) { // My code to be changed return true ; } | How to skip overrides of a method when looking for all references |
C_sharp : I have this simple code : So when I 'm creating a Data class : The list was filled with strings `` 1 '' , `` 2 '' , `` 3 '' , `` 4 '' even if it had no set.Why is this happening ? <code> public static void Main ( String [ ] args ) { Data data = new Data { List = { `` 1 '' , `` 2 '' , `` 3 '' , `` 4 '' } } ; foreach ( var str in data.List ) Console.WriteLine ( str ) ; Console.ReadLine ( ) ; } public class Data { private List < String > _List = new List < String > ( ) ; public List < String > List { get { return _List ; } } public Data ( ) { } } Data data = new Data { List = { `` 1 '' , `` 2 '' , `` 3 '' , `` 4 '' } } ; | Why am I allowed to modify properties which are readonly with object initializers ? |
C_sharp : I have a BackgroundWorker and a single ProgressBar . When working , the BackgroundWorker runs through a triple for-loop and reports progress to the ProgressBar.Currently , the progress that is being reported is only that of the outter-most loop ( xProgress ) , which works , but does not run smoothly . The goal is for the ProgressBar to also account for the progress percentages of the inner loops , so that the ProgressBar updates more smoothly and more accurately.The DoWork method : <code> private void bgw_DoWork ( object sender , DoWorkEventArgs e ) { int xMax , yMax , zMax ; xMax = 10 ; for ( int x = 1 ; x < = xMax ; x++ ) { yMax = 5 ; for ( int y = 1 ; y < = yMax ; y++ ) { zMax = new Random ( ) .Next ( 50 , 100 ) ; for ( int z = 1 ; z < = zMax ; z++ ) { Thread.Sleep ( 5 ) ; /// The process double xProgress = ( double ) x / ( double ) xMax ; double yProgress = ( double ) y / ( double ) yMax ; double zProgress = ( double ) z / ( double ) zMax ; /// The progress calculation : double progressCalc = xProgress ; int progress = ( int ) ( progressCalc * pgb.Maximum ) ; bgw.ReportProgress ( progress ) ; } } } } | How can I report progress based on multiple variables in a nested loop ( for a progress bar ) ? |
C_sharp : I 'm trying to draw a Polyline whose opacity gradually fades out as the trail progresses , mimicking the effect of a highlighter that runs out of ink . I first took a naive approach with a LinearGradientBrush.As you can see on the image below , that did n't quite work out for me . I drew two polylines starting from the position of the hand . Although the `` Bottom Left '' path is drawn correctly as a fade out , the `` Top Left '' path is drawn as a fade in , which is not what I want . It appears that the gradient 's effect is n't applied in the way that I need it to be.How can I draw a Polyline where the line gradually fades out as the path nears it end ? Edit : Here 's a new approach to my problem that I 'm currently exploring . If I use PathGeometry , can I set the brushes of individual segments of a line ? <code> LinearGradientBrush lgb = new LinearGradientBrush ( ) ; lgb.GradientStops.Add ( new GradientStop ( Color.FromArgb ( 255 , 255 , 0 , 0 ) , 0.0 ) ) ; lgb.GradientStops.Add ( new GradientStop ( Color.FromArgb ( 0 , 255 , 0 , 0 ) , 1.0 ) ) ; line.Stroke = lgb ; | Drawing a Polyline that gradually fades out |
C_sharp : I 've created a C # ASP.NET method which simply takes a string property containing JSON , both inside the same class . My issue is that whenever I type the .Deserialize method ( the commented line ) Visual Studio 2013 crashes with an `` Unhandled Exception '' in event logs.If I write the line in comments ( as above ) then remove the comments there 's no problem so the issue appears to be with Intellisense or the way I 'm writing the code - anyone have any ideas ? Crash logPlease let me know if this needs to go onto SuperUser.Edit 1 : Just to confirm this issue occurs during development , not at runtime . VS crashes when I am typing the code.Edit 2 : This issue only occurs with this particular line . The system I 'm working with is massive and I 've never seen the problem before.Edit 3 : Same issue in a brand new project - potentially a bug in VS 2013 but I do n't know what 's throwing the exception in the first place . <code> public object JSONAsObject ( ) { object obj = new object ( ) ; JavaScriptSerializer js = new JavaScriptSerializer ( ) ; // obj = js.Deserialize < object > ( this._json ) ; return obj ; } Application : devenv.exeFramework Version : v4.0.30319Description : The process was terminated due to an unhandled exception.Exception Info : System.ArgumentNullExceptionStack : at System.Text.RegularExpressions.Regex.Escape ( System.String ) at Microsoft.OneCode.Utilities.UserControl.CodeSnippetsTextBox.UpdateRegex ( ) at Microsoft.OneCode.Utilities.UserControl.CodeSnippetsTextBox.OnMyWorkCollectionChanged ( System.Object , System.Collections.Specialized.NotifyCollectionChangedEventArgs ) at System.Collections.ObjectModel.ObservableCollection ` 1 [ [ System.__Canon , mscorlib , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 ] ] .OnCollectionChanged ( System.Collections.Specialized.NotifyCollectionChangedEventArgs ) at System.Collections.ObjectModel.ObservableCollection ` 1 [ [ System.__Canon , mscorlib , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 ] ] .InsertItem ( Int32 , System.__Canon ) at System.Collections.ObjectModel.Collection ` 1 [ [ System.__Canon , mscorlib , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 ] ] .Add ( System.__Canon ) at Microsoft.OneCode.IntellisensePresenter.ViewModel.IntellisenseViewModel.UpdateCodeSnippets ( System.Collections.Generic.IEnumerable ` 1 < Microsoft.OneCode.DataModel.CodeSearchResult > ) at Microsoft.OneCode.IntellisensePresenter.ViewModel.IntellisenseViewModel+ < > c__DisplayClass5. < SearchCode > b__2 ( ) at System.Windows.Threading.ExceptionWrapper.InternalRealCall ( System.Delegate , System.Object , Int32 ) at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen ( System.Object , System.Delegate , System.Object , Int32 , System.Delegate ) at System.Windows.Threading.DispatcherOperation.InvokeImpl ( ) at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext ( System.Object ) at System.Threading.ExecutionContext.RunInternal ( System.Threading.ExecutionContext , System.Threading.ContextCallback , System.Object , Boolean ) at System.Threading.ExecutionContext.Run ( System.Threading.ExecutionContext , System.Threading.ContextCallback , System.Object , Boolean ) at System.Threading.ExecutionContext.Run ( System.Threading.ExecutionContext , System.Threading.ContextCallback , System.Object ) at System.Windows.Threading.DispatcherOperation.Invoke ( ) at System.Windows.Threading.Dispatcher.ProcessQueue ( ) at System.Windows.Threading.Dispatcher.WndProcHook ( IntPtr , Int32 , IntPtr , IntPtr , Boolean ByRef ) at MS.Win32.HwndWrapper.WndProc ( IntPtr , Int32 , IntPtr , IntPtr , Boolean ByRef ) at MS.Win32.HwndSubclass.DispatcherCallbackOperation ( System.Object ) at System.Windows.Threading.ExceptionWrapper.InternalRealCall ( System.Delegate , System.Object , Int32 ) at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen ( System.Object , System.Delegate , System.Object , Int32 , System.Delegate ) at System.Windows.Threading.Dispatcher.LegacyInvokeImpl ( System.Windows.Threading.DispatcherPriority , System.TimeSpan , System.Delegate , System.Object , Int32 ) at MS.Win32.HwndSubclass.SubclassWndProc ( IntPtr , Int32 , IntPtr , IntPtr ) | VS 2013 Crash When Using JSON Deserialize Method |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.