text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
C_sharp : I 'm using this code with .NET 3.0but when i tried it in .NET 2.0 , I think Action has type parameter like this : How to implement the first code in .NET 2.0 ? <code> Action xx = ( ) = > button1.Text = `` hello world '' ; this.Invoke ( xx ) ; Action < T > | Update control from another thread in C # 2.0 |
C_sharp : Could I have something like this : So , one method returning different types based on T. Of course , there would be logic inside the method to ensure it was returning the correct thing.I can never get something like this to run . It complains that it ca n't cast the return value to T : <code> int x = MyMethod < int > ( ) ; string y = MyMethod < string > ( ) ; public static T MyMethod < T > ( ) { if ( typeof ( T ) == typeof ( Int32 ) ) { return 0 ; } else { return `` nothing '' ; } } | Using generic methods , is it possible to get different types back from the same method ? |
C_sharp : In my application I have method looks like this : And each of the internal methods looks like this : For example , DoFirstSubOperation ( ) and DoSecondSubOperation ( ) complete successfully , but DoThirdSubOperation ( ) fails.How do I rollback the changes made by the first two functions ? This approach has not brought results : The only solution I see is to define the context like so : But is it acceptable to do so ? Or is there another solution ? <code> public static bool DoLargeOperation ( ) { bool res = true ; res = res & & DoFirstSubOperation ( ) ; res = res & & DoSecondSubOperation ( ) ; res = res & & DoThirdSubOperation ( ) ; return res ; } public static bool DoFirstSubOperation ( ) { using ( var context = new EntityFrameworkContext ( ) ) { // data modification . context.SaveChanges ( ) ; } } using ( var transaction = new TransactionScope ( ) ) { res = res & & DoFirstSubOperation ( ) ; res = res & & DoSecondSubOperation ( ) ; res = res & & DoThirdSubOperation ( ) ; } public static bool DoLargeOperation ( ) { bool res = true ; using ( var context = new EntityFrameworkContext ( ) ) { using ( var transaction = context.Database.BeginTransaction ( ) ) { res = res & & DoFirstSubOperation ( context ) ; res = res & & DoSecondSubOperation ( context ) ; res = res & & DoThirdSubOperation ( context ) ; if ( res ) { transaction.Commit ( ) ; } else { transaction.Rollback ( ) ; } } } return res ; } | How to use transactions for different contexts ? |
C_sharp : I have enum lets say for example : And have two classes . which have property of enum.Now in Windows Forms Designer , I want to hide the red flag only from the Color enumeration for ClassB only.I know that I can create a separated enum . but why duplicate values ? I gave a simple example only . Something I guess might help for superior who can help me at it . Descriptor API . which I hate . ; ( Maybe something like TypeDescriptor.AddAttributes ( object , new BrowsableAttribute ( false ) ) ; This answer will not work in this case . I do n't want to apply Browsable attribute to the enum flags because it hides that flag in property grid for all classes . I want to be able to hide specific enum values for specific classes only , not for all classes . <code> public enum Color { red , green , blue } public class ClassA { public Color Color { get ; set ; } } public class ClassB { [ InvisibleFlag ( Color.red ) ] // I want something like that public Color Color { get ; set ; } } | Is there a way for hiding some enum values for specific property of class ? |
C_sharp : I tried disassembling a C # created executable , but I could n't come to a conclusion . What I 'd like to know is that if for the CLR c # 's delegates are really special entities or just a compiler sugar ? I ask this because I 'm implementing a language that compiles to C # , and it would be much more interesting for me to compile anonymous functions as classes than as delegates . But I do n't want to use a design that later I will regret , as they might be heavier on memory ( I think of Java 's PermGen to base my questioning on . Even though I know there is no such thing for the CLR ) .Thank you ! -- editto be a little more clear , I 'd like to know if there is ( and what are ) the differences between : and , for example -- editI think that there might be a great difference between : andI read somewhere , though , that the syntax Func < int , int , int > add = Program.add ; is only a sugar for Func < int , int , int > add = delegate ( int a , int b ) { return Program.add ; } ; . But I really do n't know if that 's really true.I could also see that the C # compiler already caches all those instances so they are constructed only once . I could do the same with my compiler , though . <code> void Main ( ) { Func < int , int , int > add = delegate ( int a , int b ) { return a + b ; } ; } class AnonFuncion__1219023 : Fun3 { public override int invoke ( int a , int b ) { return a + b ; } } class Program { static int add ( int a , int b ) { return a + b ; } static void Main ( ) { Func < int , int , int > add = Program.add ; } } class Function__432892 : Fun3 { public override int invoke ( int a , int b ) { return Program.add ( a , b ) ; } } | Are Delegates more lightweight than classes ? |
C_sharp : I was recently going through a garbage collection article and decided to play along and attempt to gain a greater understanding . I coded the following , playing around with the using statement , but was surprised with the results ... I expected e.Parent.Name outside of the using block to go ka-blooey.What exactly is going on here ? <code> static void Main ( string [ ] args ) { Employee e = new Employee ( ) ; using ( Parent p = new Parent ( ) ) { p.Name = `` Betsy '' ; e.Parent = p ; Console.WriteLine ( e.Parent.Name ) ; } Console.WriteLine ( e.Parent.Name ) ; Console.ReadLine ( ) ; } public class Employee { public Parent Parent ; } public class Parent : IDisposable { public string Name ; public void Dispose ( ) { Console.WriteLine ( `` Disposing Parent '' ) ; } } | C # Memory allocation/de-allocation question regarding scope |
C_sharp : I have a tray icon that needs to display two icons : If there is network connectivity , display a green circle with a check markIf there is n't network connectivity , display a red circle with an XSo what I have is : So I 'm thinking of starting a new thread or using the background worker progress because the tray icon is a NotifyIcon which is a component so I ca n't use : to update the icon property of the NotifyIcon class.My big concern is the polling process : I could write some logic that does : but I 've seen a couple of articles that tell me to stay away from Sleep ( 1000 ) . I ca n't seem to find those articles since I did n't bookmark them . I 'm just curious to know why that is n't a good idea for polling in a thread . <code> using System.Net.NetworkInformation ; bool isConnected = NetworkInterface.GetIsNetworkAvailable ( ) Form.Invoke ( delegate , object [ ] ) while ( true ) { System.Threading.Thread.Sleep ( 1000 ) ; isConnected = NetworkInterface.GetIsNetworkAvailable ( ) ; if ( isConnected ) notifyIcon.Icon = `` ConnectedIcon.ico '' ; else notifyIcon.Icon = `` DisconnectedIcon.ico '' ; } | C # threading and polling |
C_sharp : I want to create a list of methods to execute . Each method has the same signature.I thought about putting delegates in a generic collection , but I keep getting this error : 'method ' is a 'variable ' but is used like a 'method'In theory , here is what I would like to do : Any ideas on how to accomplish this ? Thanks ! <code> List < object > methodsToExecute ; int Add ( int x , int y ) { return x+y ; } int Subtract ( int x , int y ) { return x-y ; } delegate int BinaryOp ( int x , int y ) ; methodsToExecute.add ( new BinaryOp ( add ) ) ; methodsToExecute.add ( new BinaryOp ( subtract ) ) ; foreach ( object method in methodsToExecute ) { method ( 1,2 ) ; } | Can I use a List < T > as a collection of method pointers ? ( C # ) |
C_sharp : If I have : And then : Would 12 get boxed ? I ca n't imagine it would , I 'd just like to ask the experts . <code> void Foo ( dynamic X ) { } Foo ( 12 ) ; | C # - Are Dynamic Parameters Boxed |
C_sharp : I 've seen several references to WebServiceHost2Factory as the class to use to effectively handle errors in WCF Rest services . Apparently with that class , I just had to throw a WebProtocolException and the body of the response would contain pertinent information . That class seems to have fallen out of favor now . Is there a replacement somewhere in the .NET 4 stack ? I 'm trying to figure out how to return error text in the body of a response to a POST operation , if something went wrong . The key question is below next to all the *'sExample : <code> [ Description ( `` Performs a full enroll and activation of the member into the Loyalty program '' ) ] [ OperationContract ] [ WebInvoke ( Method = `` POST '' , UriTemplate = `` /fullenroll/ { clientDeviceId } '' , BodyStyle = WebMessageBodyStyle.Bare , RequestFormat = WebMessageFormat.Json , ResponseFormat = WebMessageFormat.Json ) ] public MemberInfo FullEnroll ( string clientDeviceId , FullEnrollmentRequest request ) { Log.DebugFormat ( `` FullEnroll . ClientDeviceId : { 0 } , Request : { 1 } '' , clientDeviceId , request ) ; MemberInfo ret = null ; try { //Do stuff } catch ( FaultException < LoyaltyException > fex ) { Log.ErrorFormat ( `` [ loyalty full enroll ] Caught faultexception attempting to full enroll . Message : { 0 } , Reason : { 1 } , Data : { 2 } '' , fex.Message , fex.Reason , fex.Detail.ExceptionMessage ) ; HandleException ( `` FullEnroll '' , fex , fex.Detail.ExceptionMessage ) ; } catch ( Exception e ) { Log.ErrorFormat ( `` [ loyalty full enroll ] Caught exception attempting to full enroll . Exception : { 0 } '' , e ) ; HandleException ( `` FullEnroll '' , e ) ; } return ret ; } /// < summary > /// Deals w/ the response when Exceptions are thrown/// < /summary > private static Exception HandleException ( string function , Exception e , string statusMessage = null ) { // Set the return context , handle the error if ( WebOperationContext.Current ! = null ) { var response = WebOperationContext.Current.OutgoingResponse ; // Set the error code based on the Exception var errorNum = 500 ; if ( e is HttpException ) errorNum = ( ( HttpException ) e ) .ErrorCode ; response.StatusCode = ( HttpStatusCode ) Enum.Parse ( typeof ( HttpStatusCode ) , errorNum.ToString ( ) ) ; response.StatusDescription = statusMessage ; // **************************************************** // How can I return this as the body of the Web Method ? // **************************************************** WebOperationContext.Current.CreateTextResponse ( statusMessage ) ; } return ( e is HttpException ) ? e : new HttpException ( 500 , string.Format ( `` { 0 } caught an exception '' , function ) ) ; } | Now that WebServiceHost2Factory is dead , how do I return error text from a WCF rest service ? |
C_sharp : I use var whenever I can since it 's easier not to have to explicitly define the variable.But when a variable is defined within an if or switch statement , I have to explicitly define it . Is there a way to use var even if the variable is defined inside an if or switch construct ? <code> string message ; //var message ; < -- - gives errorif ( error ) { message = `` there was an error '' ; } else { message = `` no error '' ; } Console.WriteLine ( message ) ; | Is there a way to use var when variable is defined in an if/else statement ? |
C_sharp : Consider this code : I want write this code with switch case : But we ca n't write this in C # .What is the clear way for write the above code , knowing that results is a long [ ] ? <code> if ( results.Contains ( 14 ) ) { //anything } else if ( results.Contains ( 15 ) ) { //anything } else if ( results.Contains ( 16 ) ) { //anything } switch ( results ) { case results.Contains ( 14 ) : } | Clear way to write if statement |
C_sharp : I get a file loader exception ( first chance ) at the InitializeComponent-method or the debugger breaks at the x : Class attribute of the xaml-root of multiple WPF user controls . Everything works fine despite the fact that the exceptions slow down navigation by a lot.This is the exception message : Could not load file or assembly 'Company.Solution.UserInterface , Version=0.1.5568.25577 , Culture=neutral , PublicKeyToken=45069ab0c15881ce ' or one of its dependencies . The located assembly 's manifest definition does not match the assembly reference . ( Exception from HRESULT : 0x80131040 ) This is the Fusion log : My project structure has a root project that references a module project ( in which the exception occurs ) . The module project itself references the project that is the target of the above mentioned probing `` Company.Product.UserInterface.dll '' which contains some resources / controls / styles / primitives / converters and so on.How can I get rid of the FileLoadExceptions ? Another more complete Fusion-log : At the moment the exception occurs the version of the assembly in the SolutionExplorer referenced is 0.1.5577.18123 ( in all solutions that reference the ..UserInterface.dll . I have no idea who looks up 0.1.5577.18122 , this version did never exist ) If I run a new rebuild all I get the same error , Fusion looks for ( I never had this version number ) : the version found is : Visual Studio Version is 2013 Ultimate , and the project is build on .net4.5 and the assembly versions are auto generated in the build process.I uploaded the build log to tinyupload as it was too big.The full Fusion-log can be found here at pastebin . <code> Assembly manager loaded from : C : \Windows\Microsoft.NET\Framework\v4.0.30319\clr.dllRunning under executable D : \Development\Product\Main\src\Company.Product \bin\Debug\Product.vshost.exe -- - A detailed error log follows . === Pre-bind state information ===LOG : DisplayName = Company.Product .UserInterface , Version=0.1.5568.25577 , Culture=neutral , PublicKeyToken=45069ab0c15881ce ( Fully-specified ) LOG : Appbase = file : ///D : /Development/Product/Main/src/Company.Product/bin/Debug/LOG : Initial PrivatePath = NULLCalling assembly : PresentationFramework , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 . LOG : This bind starts in default load context.LOG : Using application configuration file : D : \Development\Product \Main\src\Company.Product \bin\Debug\Product .vshost.exe.ConfigLOG : Using host configuration file : LOG : Using machine configuration file from C : \Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.LOG : Post-policy reference : Company.Product .UserInterface , Version=0.1.5568.25577 , Culture=neutral , PublicKeyToken=45069ab0c15881ceLOG : Attempting download of new URL file : ///D : /Development/Product/Main/src/Company.Product/bin/Debug/Company.Product.UserInterface.DLL.WRN : Comparing the assembly name resulted in the mismatch : Revision NumberERR : Failed to complete setup of assembly ( hr = 0x80131040 ) . Probing terminated . === Pre-bind state information ===LOG : DisplayName = Company.Product.UserInterface , Version=0.1.5577.18122 , Culture=neutral , PublicKeyToken=45069ab0c15881ce ( Fully-specified ) LOG : Appbase = file : ///D : /Development/Product/Main/src/Company.Product/bin/Debug/LOG : Initial PrivatePath = NULLLOG : Dynamic Base = NULLLOG : Cache Base = NULLLOG : AppName = Product.vshost.exeCalling assembly : PresentationFramework , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=31bf3856ad364e35.LOG : This bind starts in default load context.LOG : Using application configuration file : D : \Development\Product\Main\src\Company.Product\bin\Debug\Product.vshost.exe.ConfigLOG : Using host configuration file : LOG : Using machine configuration file from C : \Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.LOG : Post-policy reference : Company.Product.UserInterface , Version=0.1.5577.18122 , Culture=neutral , PublicKeyToken=45069ab0c15881ceLOG : GAC Lookup was unsuccessful.LOG : Attempting download of new URL file : ///D : /Development/Product/Main/src/Company.Product/bin/Debug/Company.Product.UserInterface.DLL.LOG : Assembly download was successful . Attempting setup of file : D : \Development\Product\Main\src\Company.Product\bin\Debug\Company.Product.UserInterface.dllLOG : Entering run-from-source setup phase.LOG : Assembly Name is : Company.Product.UserInterface , Version=0.1.5577.18123 , Culture=neutral , PublicKeyToken=45069ab0c15881ceWRN : Comparing the assembly name resulted in the mismatch : Revision NumberERR : The assembly reference did not match the assembly definition found.ERR : Run-from-source setup phase failed with hr = 0x80131040.ERR : Failed to complete setup of assembly ( hr = 0x80131040 ) . Probing terminated . LOG : Post-policy reference : Company.Product.UserInterface , Version=0.1.5577.18465 , Culture=neutral , PublicKeyToken=45069ab0c15881ce LOG : Assembly Name is : Company.Product.UserInterface , Version=0.1.5577.18466 , Culture=neutral , PublicKeyToken=45069ab0c15881ce | FileLoadException At InitializeComponent or x : Class= |
C_sharp : According to below link when you do a 'Response.Redirect ' during any posts inside update panel , it would send a HTTPResponseCode of 200 and Ajax javascripty libraries will take over from there to redirect the user to a page.https : //connect.microsoft.com/VisualStudio/feedback/details/542238/redirecting-during-ajax-request-returns-wrong-status-codeHowever , I 'm writing a module in which I 'm intercepting all redirects and changing the URLs to contain a value . I 'm doing this during PreSendRequestContent event . Below is my codeIs there any way for me to do the same during aforementioned redirects ? I 'm okay to do this both on client side using onEndRequest or similar events and some other module event on server side <code> HttpApplication app = ( HttpApplication ) sender ; if ( app.Response.StatusCode == 302 & & ! app.Response.RedirectLocation.Contains ( `` MyValue '' ) ) { // Add MyValue to URL } | Intercept redirects from UpdatePanel Posts |
C_sharp : I realize this is partially subjective , but I 'm generally curious as to community opinion and have not been able to successfully find an existing question that tackles this issue.I am in a somewhat religious debate with a fellow coworker about a particular Select statement in a L2EF query.Caveats : This is Linq-to-EntitiesThis is after the work in the DB as been performed and returnedThe input parameter r is anonymousPersonally , I 'm of the opinion that ( a ) the select clause should not be altering values , it should merely project . His counter argument is that he 's not altering anything , he 's just making sure everything is properly initialized as a result of the DB query . Secondly , I think once he starts getting into full code blocks and return statements , it 's time to define a method or even a Func < T , U > and not do all of this inline . The complicator here is , again , the input is anonymous , so a type would need to be defined . But nevertheless , we are still debating the general point if not the specific.So , when does a lambda expression do too much ? Where do you draw the fuzzy line in the sand ? <code> .Select ( r = > { r.foo.Bar = r.bar ; r.foo.Bar.BarType = r.Alpha ; if ( r.barAddress ! = null ) { r.foo.Bar.Address = r.barAddress ; r.foo.Bar.Address.State = r.BarState ; } if ( r.baz ! = null ) { r.foo.Bar.Baz = r.baz ; if ( r.bazAddress ! = null ) { r.foo.Bar.Baz.Address = r.bazAddress ; r.foo.Bar.Baz.Address.State = r.BazState ; } } return r.foo ; } ) | When does a lambda in an extension method do too much ? |
C_sharp : First off , I 'm new to LINQ , so I do n't really know the ins and outs of it . I 'm attempting to use it in some code at the minute , and according to my diagnostics it appears to be about as fast as using a for loop in the same way . However , I 'm not sure how well this would scale as the lists which I am working with could increase quite dramatically.I 'm using LINQ as part of a collision detection function ( which is still in the works ) and I 'm using it to cull the list to only the ones that are relevant for the checks.Here is the LINQ version : This is my previous method : At the minute , either run in almost no time ( but run numerous times a second ) , but as the project builds and gets more intricate , this will be dealing with far more objects at once and the code to check for collisions will be more detailed . <code> partial class Actor { public virtual bool checkActorsForCollision ( Vector2 toCheck ) { Vector2 floored=new Vector2 ( ( int ) toCheck.X , ( int ) toCheck.Y ) ; if ( ! causingCollision ) // skip if this actor does n't collide return false ; foreach ( Actor actor in from a in GamePlay.actors where a.causingCollision==true & & a.isAlive select a ) if ( // ignore offscreen collisions , we do n't care about them ( actor.location.X > GamePlay.onScreenMinimum.X ) & & ( actor.location.Y > GamePlay.onScreenMinimum.Y ) & & ( actor.location.X < GamePlay.onScreenMaximum.X ) & & ( actor.location.Y < GamePlay.onScreenMaximum.Y ) ) if ( actor ! =this ) { // ignore collisions with self Vector2 actorfloor=new Vector2 ( ( int ) actor.location.X , ( int ) actor.location.Y ) ; if ( ( floored.X==actorfloor.X ) & & ( floored.Y==actorfloor.Y ) ) return true ; } return false ; } } partial class Actor { public virtual bool checkActorsForCollision ( Vector2 toCheck ) { Vector2 floored=new Vector2 ( ( int ) toCheck.X , ( int ) toCheck.Y ) ; if ( ! causingCollision ) // skip if this actor does n't collide return false ; for ( int i=0 ; i < GamePlay.actors.Count ; i++ ) if ( // ignore offscreen collisions , we do n't care about them ( GamePlay.actors [ i ] .location.X > GamePlay.onScreenMinimum.X ) & & ( GamePlay.actors [ i ] .location.Y > GamePlay.onScreenMinimum.Y ) & & ( GamePlay.actors [ i ] .location.X < GamePlay.onScreenMaximum.X ) & & ( GamePlay.actors [ i ] .location.Y < GamePlay.onScreenMaximum.Y ) ) if ( // ignore collisions with self ( GamePlay.actors [ i ] .isAlive ) & & ( GamePlay.actors [ i ] ! =this ) & & ( GamePlay.actors [ i ] .causingCollision ) ) { Vector2 actorfloor= new Vector2 ( ( int ) GamePlay.actors [ i ] .location.X , ( int ) GamePlay.actors [ i ] .location.Y ) ; if ( ( floored.X==actorfloor.X ) & & ( floored.Y==actorfloor.Y ) ) return true ; } return false ; } } | New to LINQ : Is this the right place to use LINQ ? |
C_sharp : I am running Ubuntu 64bit linux.andI create a folder named `` test '' .I cd into test.I then run : The console returns : I am not sure what to do to remedy this . <code> No LSB modules are available.Distributor ID : UbuntuDescription : Pop ! _OS 18.10Release : 18.10Codename : cosmic dotnet version : 3.0.100 dotnet new consoledotnet run *** stack smashing detected *** : < unknown > terminated | dotnet run gives me `` *** stack smashing detected *** : < unknown > terminated '' |
C_sharp : We have a Grid that 's bound to a List < T > of items . Whenever the user hits `` Refresh '' , changes are obtained from the database , and the bound list is updated . I 'm running into a problem where duplicate items are being added to the grid , and I can not figure out why.The database call returns two values : a List < int > of the Record Ids that have changed , and a List < MyClass > of updated data for the records that have changed . The existing code code I 'm debugging which finds out what needs to be updated looks something like this : The result of calling FindUpdates ( ) is I get a Dictionary < Id , Data > of existing records , a Dictionary < Id , Data > of the updated records to replace them with , and a List < int > of Ids for which items should be Added , Removed , or Updated from the data source.On occasion , a record gets added to the grid twice and I can not for the life of me figure out where this code is going wrong.I pulled the log file from one of these instances , and can clearly see the following sequence of events : Item # 2 added to the List of data20 minutes later , Item # 2 is added to the List of data againWriteToLog ( ) from the 2nd add tells me that updatedIds contains values 1 , 2 , and 3adds contains 1 and 2updates contains 3Based on other log entries , I can clearly see that item # 2 was added previously , and never removed , so it should be in the existingRecords variable have shown up in the updates variable , not in the adds . In addition , item # 2 was successfully updated a few times between the first add and the second one , so the code in theory should work . I also have a screenshot of the UI as well showing both copies of item # 2 in the grid of data.Notes ... IsDisposed is only set to true in the overridden .Dispose ( ) method on the item . I do n't think this would have occurred.Edit : I 've added a log statement since then , and can verify that IsDisposed is not set to true when this happens.This has happened a few times now to a few different users , so it 's not just a one-time thing . I am unable to reproduce the problem on-demand though.The Grid of records can be fairly large , averaging a few thousand items.I have n't ruled out the idea of the DB call returning invalid values , or lists which do n't have the same items , however I do n't see how that could affect the outcomeThe one time I was able to see this bug in action , we were running some tests and other users were modifying record # 2 fairly frequentlyThis all runs in a background threadBased on the log , this was only running once at the time . It ran previously a minute before , and next 2 minutes later.From the log file , I can see that item # 2 has been updated a few times correctly before being incorrectly added a second time , so this code did work with the existing data set a few times before.Is there anything at all in the code shown above that could cause this to happen ? Or perhaps a rare known issue in C # where this could happen that I 'm not aware of ? <code> public void FindUpdates ( IList < MyClass > existingRecords , IList < MyClass > updatedRecords , List < int > updatedIds , out IDictionary < int , int > existing , out IDictionary < int , int > updated , out List < int > updates , out List < int > removes , out List < int > adds ) { updates = new List < int > ( ) ; removes = new List < int > ( ) ; adds = new List < int > ( ) ; existing = FindUpdated ( existingRecords , updatedIds ) ; updated = FindUpdated ( updatedRecords , updatedIds ) ; if ( updatedIds ! = null ) { // split add/update and remove foreach ( int id in updatedIds ) { if ( ! existing.ContainsKey ( id ) ) adds.Add ( id ) ; else if ( updated.ContainsKey ( id ) ) updates.Add ( id ) ; else removes.Add ( id ) ; } WriteToLog ( updatedIds , adds , updates , removes ) ; } } private IDictionary < int , int > FindUpdated ( IList < MyClass > records , List < int > updatedIds ) { IDictionary < int , int > foundItems = new Dictionary < int , int > ( ) ; if ( records ! = null & & updatedIds ! = null ) { for ( int i = 0 ; i < records.Count ; i++ ) { IMyClass r = records [ i ] as IMyClass ; if ( r ! = null & & ! r.IsDisposed ) { if ( updatedIds.Contains ( r.Id ) ) { foundItems.Add ( r.Id , i ) ; } } } } return foundItems ; } | Is there any reason an existing item would not be found in List < T > in this code block ? |
C_sharp : I need to programmatically open the android contacts app using an intent with Xamarin Forms/Android . When the Add New Contact activity/screen comes up , I would like to pre-populate it with the following fields : Name ( this is populating ) Phone ( this is populating ) Street ( Not populating ) City ( Not populating ) State ( Not populating ) Country ( Not seeing a field for this , not populating ) As stated above , some screens are populating , but the address fields are not . This is the Xamarin C # Android code/service being used to trigger the activity for opening up Android 's 'Add Contact ' screen : The activity does open the 'add new contact ' screen in the contacts app , but only the name and the phone number fields are populated . See screenshots below : I found a link that may translate into Xamarin.Android but I have been struggling with the implementation Java Samples . <code> public void AddContact ( string name , string [ ] phoneNumbers , string streetAddress , string city , string state , string postalCode , CountryValues countrycode ) { // get current activity var activity = CrossCurrentActivity.Current.Activity ; // create add contact intent var intent = new Intent ( Intent.ActionInsert ) ; intent.SetType ( ContactsContract.Contacts.ContentType ) ; // add field for contact name intent.PutExtra ( ContactsContract.Intents.Insert.Name , name ) ; // Adding more than on phone number if available foreach ( string numbers in phoneNumbers ) { intent.PutExtra ( ContactsContract.Intents.Insert.Phone , numbers ) ; } // pre-populate address fields intent.PutExtra ( ContactsContract.CommonDataKinds.StructuredPostal.Street , streetAddress ) ; intent.PutExtra ( ContactsContract.CommonDataKinds.StructuredPostal.City , city ) ; intent.PutExtra ( ContactsContract.CommonDataKinds.StructuredPostal.Region , state ) ; intent.PutExtra ( ContactsContract.CommonDataKinds.StructuredPostal.Postcode , postalCode ) ; intent.PutExtra ( ContactsContract.CommonDataKinds.StructuredPostal.Country , countrycode.ToString ( ) ) ; //start activity activity.StartActivity ( intent ) ; } | How to insert contacts with city , street , postal code , country in Xamarin Android using intent and activity ? |
C_sharp : I noticed this strange behavior yesterday when putting together a demo application for WP . Usually I never pass in plain items , and never the ‘ same ’ - but this time I did.When bound to an observablecollection of type int or string , if the value is the same , the control will add first one item , then two , then three , then four . Instead of adding one each time . Basically it does this : Items.Count ++If I however change the item , say string , to something unique ( a GUID.ToString for example ) it has the expected behavior.This is regardless of how the DataContext is set , or if I add LayoutMode= '' List '' IsGroupingEnabled= '' False '' to the control.Why does it do this ? And is this expected behavior ? I spent hours searching for an answer , so please don ’ t just paste random links about the control : ) Code for the view : Code behind : <code> < phone : PhoneApplicationPagex : Class= '' Bug.MainPage '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : phone= '' clr-namespace : Microsoft.Phone.Controls ; assembly=Microsoft.Phone '' xmlns : shell= '' clr-namespace : Microsoft.Phone.Shell ; assembly=Microsoft.Phone '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' mc : Ignorable= '' d '' FontFamily= '' { StaticResource PhoneFontFamilyNormal } '' FontSize= '' { StaticResource PhoneFontSizeNormal } '' Foreground= '' { StaticResource PhoneForegroundBrush } '' SupportedOrientations= '' Portrait '' Orientation= '' Portrait '' shell : SystemTray.IsVisible= '' True '' DataContext= '' { Binding RelativeSource= { RelativeSource Self } } '' > < StackPanel > < Button Click= '' Button_Click '' > Add < /Button > < phone : LongListSelector Width= '' 300 '' Height= '' 600 '' ItemsSource= '' { Binding Items } '' / > < /StackPanel > < /phone : PhoneApplicationPage > using System.Collections.ObjectModel ; using System.Windows ; namespace Bug { public partial class MainPage { // Constructor public MainPage ( ) { InitializeComponent ( ) ; Items = new ObservableCollection < string > ( ) ; //DataContext = this ; } public ObservableCollection < string > Items { get ; set ; } private void Button_Click ( object sender , RoutedEventArgs e ) { Items.Add ( `` A '' ) ; // This works as expected //Items.Add ( Guid.NewGuid ( ) .ToString ( ) ) ; } } } | Why does the LongListSelector add extra items if the collection values are identical ? |
C_sharp : I 'm trying to use Autofac to find the most greedy constructor in a referenced dll.It 's not finding it and only finds the one parameterless constructor.These are the two ctors : Now this is how I register the stuff with autofac : nothing too complex.But this is the only weird thing I can think of.typeof ( MvcApplication ) is the same project where this code exists in , in global.asaxtypeof ( MvcApplication ) is found in a -seperate- dll , which I manually added via AddReferences.Anyone see what I 've done wrong ? <code> public SimpleAuthenticationController ( ) { .. } public SimpleAuthenticationController ( IAuthenticationCallbackProvider callbackProvider ) : this ( ) var builder = new ContainerBuilder ( ) ; builder.RegisterType < SampleMvcAutoAuthenticationCallbackProvider > ( ) .As < IAuthenticationCallbackProvider > ( ) ; builder.RegisterControllers ( typeof ( MvcApplication ) .Assembly ) ; builder.RegisterControllers ( typeof ( SimpleAuthenticationController ) .Assembly ) ; var container = builder.Build ( ) ; DependencyResolver.SetResolver ( new AutofacDependencyResolver ( container ) ) ; | Autofac not finding the most greedy constructor |
C_sharp : I have a method which can be written pretty neatly through method chaining : However I 'd like to be able to do some checks at each point as I wish to provide helpful diagnostics information if any of the chained methods returns unexpected results.To achieve this , I need to break up all my chaining and follow each call with an if block . It makes the code a lot less readable.Ideally I 'd like to be able to weave in some chained method calls which would allow me to handle unexpected outcomes at each point ( e.g . throw a meaningful exception such as new ConventionException ( `` The report contains no parameter '' ) if the first method returns an empty collection ) . Can anyone suggest a simple way to achieve such a thing ? Edit : This is the result of using @ JeffreyZhao 's answer : <code> return viewer.ServerReport.GetParameters ( ) .Single ( p = > p.Name == Convention.Ssrs.RegionParamName ) .ValidValues .Select ( v = > v.Value ) ; return viewer.ServerReport.GetParameters ( ) .Assert ( result = > result.Any ( ) , `` The report contains no parameter '' ) .SingleOrDefault ( p = > p.Name == Convention.Ssrs.RegionParamName ) .Assert ( result = > result ! = null , `` The report does not contain a region parameter '' ) .ValidValues .Select ( v = > v.Value ) .Assert ( result = > result.Any ( ) , `` The region parameter in the report does not contain any valid value '' ) ; | LINQ method chaining and granular error handling |
C_sharp : in my application I 've got three interfaces ICapture < T > , IDecoder < T , K > , and IBroadcaster < K > .Now I implement for example a VideoCapture class inheriting from Capture < IntPtr > ( IntPtr is the raw data produced by the class ) . When data is generated by an object of VideoCapture , I firstly want to decode it from T to K , and then broadcast it.What I want to know is : how would you chain this ? Simply by writing a method likeOr are there any design patterns , that I could use ? I know of the chain of responsibility pattern . I could imagine writing classes like CaptureHandler , DecoderHandler , and BroadcastHandler inheriting from HandlerBase . HandlerBase would provide mechanisms to hand over objects to the next handler.But I dunno if this is the best approach for my situation . <code> var data = videoCapture.GetData ( ) ; var decoded = decoder.Decode ( data ) ; broadcaster.Broadcast ( decoded ) ; var handler1 = new CaptureHandler ( ) ; var handler2 = new DecodeHandler ( ) ; handler1.SetNext ( handler2 ) ; handler1.Handle ( object ) ; | Object manipulation chaining |
C_sharp : This is the code I have but it 's to slow , any way to do it faster..the number range I 'm hitting is 123456789 but I ca n't get it below 15 seconds , and I need it to get below 5 seconds..sum = ( n ( n+1 ) ) /2 is not giving me the results I need , not calculating properly..For N = 12 the sum is 1+2+3+4+5+6+7+8+9+ ( 1+0 ) + ( 1+1 ) + ( 1+2 ) = 51.I need to do this with a formula instead of a loop..I 've got about 15 tests to run through each under 6 seconds..with parallel I got one test from 15seconds to 4-8 seconds..Just to show you the test I 'm doing this is the hard one..On my computer I can run all the tests under 5 seconds..Look at the photo..With DineMartine Answer I got these results : <code> long num = 0 ; for ( long i = 0 ; i < = n ; i++ ) { num = num + GetSumOfDigits ( i ) ; } static long GetSumOfDigits ( long n ) { long num2 = 0 ; long num3 = n ; long r = 0 ; while ( num3 ! = 0 ) { r = num3 % 10 ; num3 = num3 / 10 ; num2 = num2 + r ; } return num2 ; } [ Test ] public void When123456789_Then4366712385 ( ) { Assert.AreEqual ( 4366712385 , TwistedSum.Solution ( 123456789 ) ) ; } | Get sum of each digit below n as long |
C_sharp : I am looking for a way to hold big 3d sparse array structure into memory without waste a lot of memory . Here I 've done an experiment with arrays of longs : If you want to test it set the COMPlus_gcAllowVeryLargeObjects environment variable ( Project Properties - > Debug ) to 1 or change the JMAX . And this is the output : When I see the memory consumption in the Task Manager is like this in Process.WorkingSet64 . What is the real number ? Why is memory allocated on assignment ? Is an array actually a continuous allocated memory ? Is an array an array ? Do aliens exist ? ( dramatic background music ) Episode 2 : We make a small change : and nothing change ( in the output ) . Where is the difference between existent and nonexistent ? ( more dramatic background music ) Now we are waiting for answer from one of the mysterious people ( They have some number and a small ' k ' under their names ) .Episode 3 : Another change : The output : PMS64 for one array ( 15369-8 ) /4 = 3840MBThis is not sparse array , but partially filled array ; ) .I am using full this 168MB.Answer to some question `` Why do you not use the exact size ? '' . Because I do n't know it ? The data can come from several user defined SQLs . `` Why do you not resize it ? '' . Resize make a new array and copies the values . This is time to copy , memory and on the end the evil GC comes and eat you.Did I waste memory . ( I do n't remember . The aliens ? ! ) And when yes , how much ? 0 , ( 3840-168 ) MB or ( 15369-8-168 ) MB ? Epilogue : Is a comment a comment or an answer ? is contiguous memory actually contiguous memory ? Do answers give answers ? Mysterious . ( more music ) ( Scully : Mulder , toads just fell from the sky ! Mulder : I guess their parachutes did n't open . ) Thank you all ! <code> using System ; using System.Diagnostics ; using System.Runtime ; namespace ConsoleApp4 { public class Program { static Process proc = Process.GetCurrentProcess ( ) ; const int MB = 1024 * 1024 ; const int IMAX = 5 ; const int JMAX = 100000000 ; public static void ShowTextWithMemAlloc ( string text ) { proc.Refresh ( ) ; Console.WriteLine ( $ '' { text , -30 } WS64 : { proc.WorkingSet64/MB,5 } MB PMS64 : { proc.PrivateMemorySize64/MB,5 } MB '' ) ; Console.ReadKey ( ) ; } public static void Main ( string [ ] args ) { Console.Write ( `` `` ) ; ShowTextWithMemAlloc ( `` Start . `` ) ; long [ ] lArray = new long [ IMAX * JMAX ] ; long [ ] l1Array = new long [ IMAX * JMAX ] ; long [ ] l2Array = new long [ IMAX * JMAX ] ; long [ ] l3Array = new long [ IMAX * JMAX ] ; ShowTextWithMemAlloc ( `` Arrays created . `` ) ; lArray [ IMAX * JMAX - 1 ] = 5000 ; l1Array [ IMAX * JMAX - 1 ] = 5000 ; l2Array [ IMAX * JMAX - 1 ] = 5000 ; l3Array [ IMAX * JMAX - 1 ] = 5000 ; ShowTextWithMemAlloc ( `` Last elements accessed . `` ) ; for ( var i=IMAX-1 ; i > = 0 ; i -- ) { for ( var j=0 ; j < JMAX ; j++ ) { lArray [ i * JMAX + j ] = i * JMAX + j ; } ShowTextWithMemAlloc ( $ '' Value for row { i } assigned . `` ) ; } //lArray = new long [ 5 ] ; //l1Array = null ; //l2Array = null ; //l3Array = null ; //GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce ; //GC.Collect ( ) ; //ShowTextWithMemAlloc ( $ '' GC.Collect done . `` ) ; ShowTextWithMemAlloc ( `` Stop . `` ) ; } } } Start . WS64 : 14MB PMS64 : 8MB Arrays created . WS64 : 15MB PMS64:15360MB Last elements accessed . WS64 : 15MB PMS64:15360MB Value for row 4 assigned . WS64 : 779MB PMS64:15360MB Value for row 3 assigned . WS64 : 1542MB PMS64:15360MB Value for row 2 assigned . WS64 : 2305MB PMS64:15361MB Value for row 1 assigned . WS64 : 3069MB PMS64:15361MB Value for row 0 assigned . WS64 : 3832MB PMS64:15362MB Stop . WS64 : 3844MB PMS64:15325MB //lArray [ i * JMAX + j ] = i * JMAX + j ; var x= lArray [ i * JMAX + j ] ; //lArray [ IMAX * JMAX - 1 ] = 5000 ; //l1Array [ IMAX * JMAX - 1 ] = 5000 ; //l2Array [ IMAX * JMAX - 1 ] = 5000 ; //l3Array [ IMAX * JMAX - 1 ] = 5000 ; //ShowTextWithMemAlloc ( `` Last elements accessed . `` ) ; long newIMAX = IMAX-3 ; long newJMAX = JMAX / 10 ; for ( var i=0 ; i < newIMAX ; i++ ) { for ( var j=0 ; j < newJMAX ; j++ ) { lArray [ i * newJMAX + j ] = i * newJMAX + j ; //var x= lArray [ i * JMAX + j ] ; } //ShowTextWithMemAlloc ( $ '' Value for row { i } assigned . `` ) ; } ShowTextWithMemAlloc ( $ '' { newIMAX*newJMAX } values assigned . `` ) ; Start . WS64 : 14MB PMS64 : 8MB Arrays created . WS64 : 15MB PMS64:15369MB 20000000 values assigned . WS64 : 168MB PMS64:15369MB Stop . WS64 : 168MB PMS64:15369MB | How a big array allocates memory ? |
C_sharp : I have 9 GB of data , and I want only 10 rows . When I do : I get an OutOfMemoryException . I would like to use an OrderByAndTake method , optimized for lower memory consumption . It 's easy to write , but I guess someone already did . Where can I find it.Edit : It 's Linq-to-objects . The data comes from a file . Each row can be discarded if its value for Column1 is smaller than the current list of 10 biggest values . <code> data.OrderBy ( datum = > datum.Column1 ) .Take ( 10 ) .ToArray ( ) ; | Memory optimized OrderBy and Take ? |
C_sharp : I had very simple code which worked fine for me : I 've updated OAuth 's NuGet packages and rewrite the code this way : but PrepareRequestUserAuthorizationAsync throws exception `` Attempt by method 'DotNetOpenAuth.OAuth2.WebServerClient+d__3.MoveNext ( ) ' to access method 'System.Collections.Generic.List ` 1..ctor ( ) ' failed . '' <code> var url = System.Web.HttpContext.Current.Request.Url ; Uri callbackUrl = new System.Uri ( url , `` oAuth2CallBack '' ) ; var ub = new UriBuilder ( callbackUrl ) ; // decodes urlencoded pairs from uri.Query to varvar httpValueCollection = HttpUtility.ParseQueryString ( callbackUrl.Query ) ; httpValueCollection.Add ( UrlArguments.Param , null ) ; // urlencodes the whole HttpValueCollectionub.Query = httpValueCollection.ToString ( ) ; var authorizationRequest = OAuthClient.PrepareRequestUserAuthorization ( new [ ] { `` somedata '' } , ub.Uri ) ; authorizationRequest.Send ( ) ; var url = System.Web.HttpContext.Current.Request.Url ; Uri callbackUrl = new System.Uri ( url , `` oAuth2CallBack '' ) ; var ub = new UriBuilder ( callbackUrl ) ; // decodes urlencoded pairs from uri.Query to varvar httpValueCollection = HttpUtility.ParseQueryString ( callbackUrl.Query ) ; httpValueCollection.Add ( UrlArguments.Param , null ) ; // urlencodes the whole HttpValueCollectionub.Query = httpValueCollection.ToString ( ) ; var client = new WebServerClient ( new AuthorizationServerDescription { TokenEndpoint = Configuration.OAuth2.TokenEndpoint , AuthorizationEndpoint = Configuration.OAuth2.AuthorizationEndpoint , } , clientIdentifier : Configuration.OAuth2.ClientIdentifier , clientCredentialApplicator : ClientCredentialApplicator.PostParameter ( Configuration.OAuth2.ClientSecret ) ) ; var authorizationRequest = await client.PrepareRequestUserAuthorizationAsync ( new [ ] { `` somedata '' } , ub.Uri ) ; await authorizationRequest.SendAsync ( ) ; | PrepareRequestUserAuthorizationAsync fails |
C_sharp : I 'm working on a regex for validating urls in C # . Right now , the regex I need must not match other http : // but the first one inside the url . This was my first try : But this regex does not work ( even removing ( ? ! https ? : \/\/ ) ) . Take for example this input string : Here is my first doubt : why does not the capturing group ( .+ ? ) match notwork.http : //test ? The lazy quantifier should match as few times as possible but why not until the end ? In this case I was certainly missing something ( Firstly I thought it could be related to backtracking but I do n't think this is the case ) , so I read this and found a solution , even if I 'm not sure is the best one since it says that This technique presents no advantage over the lazy dot-starAnyway , that solution is the tempered dot . This is my next try : Now : this regex is working but not in the way I would like . I need a match only when the url is valid . By the way , I think I have n't fully understood what the new regex is doing : why the negative lookahead stays before the . and not after it ? So I tried moving it after the . and it seems that it matches the url until it finds the second-to-last character before the second http . Returning to the corrected regex , my hypothesis is that the negative lookahead is actually trying to check what 's after the . already read by the regex , is this right ? Other solutions are well-accepted , but I 'd firstly prefer to understand this one . Thank you . <code> ( https ? : \/\/.+ ? ) \/ ( .+ ? ) ( ? ! https ? : \/\/ ) http : //test.test/notwork.http : //test ( https ? : \/\/.+ ? ) \/ ( ( ? : ( ? ! https ? : \/\/ ) . ) * ) | Lazy quantifier and lookahead |
C_sharp : In C # how can I create an IEnumerable < T > class with different types of objectsFor example : I want to do some thing like : <code> Public class Animals { Public class dog { } Public class cat { } Public class sheep { } } Foreach ( var animal in Animals ) { Print animal.nameType } | In C # how can I create an IEnumerable < T > class with different types of objects > |
C_sharp : I came about something rather baffling in C # just recently . In our code base , we have a TreeNode class . When changing some code , I found that it was impossible to assign a variable to the Nodes property . On closer inspection it became clear that the property is read-only and this behavior is to be expected . What is strange is that our code base had until then always relied on assignment of some anonymous type to the Nodes property and compiled and worked perfectly.To summarize : why did the assignment in AddSomeNodes work in the first place ? <code> using System.Collections.Generic ; namespace ReadOnlyProperty { public class TreeNode { private readonly IList < TreeNode > _nodes = new List < TreeNode > ( ) ; public IList < TreeNode > Nodes { get { return _nodes ; } } } public class TreeBuilder { public IEnumerable < TreeNode > AddSomeNodes ( ) { yield return new TreeNode { Nodes = { new TreeNode ( ) } } ; } public IEnumerable < TreeNode > AddSomeOtherNodes ( ) { var someNodes = new List < TreeNode > ( ) ; yield return new TreeNode { Nodes = someNodes } ; } } } | Setting a read-only property with anonymous type |
C_sharp : Before you answer , look at this post.Getting an answer for that first may resolve the issue below.This is a problem that just started with Windows 10 ( Universal Apps ) . In Windows 8.1 , and every other XAML technology , this technique worked flawlessly . Here 's the setup in a blank universal app project:1 . Static class with Attached Property Create a class that houses an attached property of type Brush . Put this anywhere in the project.2 . Add a control to your MainPage.xaml using attached propertyIn the main page , add a ContentControl with a custom template that has a Grid with its background color set to the accent brush . The accent brush is set in a style.If you run the app now , it will show up with a green background . Everything works . However , if you set the value as { x : Null } , it throws an exception.Would anyone like to take a shot at this ? <code> public static class MySettings { public static Brush GetAccentBrush ( DependencyObject d ) { return ( Brush ) d.GetValue ( AccentBrushProperty ) ; } public static void SetAccentBrush ( DependencyObject d , Brush value ) { d.SetValue ( AccentBrushProperty , value ) ; } public static readonly DependencyProperty AccentBrushProperty = DependencyProperty.RegisterAttached ( `` AccentBrush '' , typeof ( Brush ) , typeof ( MySettings ) , null ) ; } < Page x : Class= '' UniversalTest.MainPage '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' xmlns : local= '' using : UniversalTest '' mc : Ignorable= '' d '' > < Page.Resources > < Style x : Key= '' MyControl '' TargetType= '' ContentControl '' > < Setter Property= '' local : MySettings.AccentBrush '' Value= '' Green '' / > < ! -- Setting value here -- > < /Style > < /Page.Resources > < Grid Background= '' { ThemeResource ApplicationPageBackgroundThemeBrush } '' > < ContentControl Style= '' { StaticResource MyControl } '' > < ContentControl.Template > < ControlTemplate TargetType= '' ContentControl '' > < Grid Background= '' { TemplateBinding local : MySettings.AccentBrush } '' > < ! -- Using value here -- > < TextBlock Text= '' Howdy World ! '' / > < /Grid > < /ControlTemplate > < /ContentControl.Template > < /ContentControl > < /Grid > < /Page > < Page.Resources > < Style x : Key= '' MyControl '' TargetType= '' ContentControl '' > < Setter Property= '' local : MySettings.AccentBrush '' Value= '' { x : Null } '' / > < ! -- Null value here -- > < /Style > < /Page.Resources > | How can I bind to a null value inside a template in a Universal Windows App ? |
C_sharp : Can anyone explain , why we can do such thing and why we need thisWhy we need public inner whatever : struct , class , enum or static class ? I think that if it is inner then it must be only private or protected . <code> public class OuterClass { public class InnerClass { } } | public inner classes |
C_sharp : I have a game ( based on MonoGame / XNA ) with an update method like so : I would like to convert this to the Reactive pattern . My current solution is : I am new to Rx so I am still learning the best way of doing things . I read that Subject should be avoided and Observable.Create should be used instead . Is Subject appropriate here ? How could I use Observable.Create in this case ? <code> public void Update ( GameTime gameTime ) { component.Update ( gameTime ) ; } public void Initialize ( ) { updateSubject = new Subject < GameTime > ( ) ; component = new Component ( ) ; updateSubject.Subscribe ( ( gameTime ) = > component.Update ( gameTime ) ) ; } public void Update ( GameTime gameTime ) { updateSubject.OnNext ( gameTime ) ; } | How do I turn a polling system into an Rx.Net IObservable ? |
C_sharp : There are some C style functions in an Objective C library I 'm binding to that I need access to in my application . Is it possible to add these into the bindings in any way so I can access them in my C # application ? EXAMPLE from Cocos2d : EDITLink to header with functions I 'm trying to import : http : //www.cocos2d-iphone.org/api-ref/2.0.0/cc_g_l_state_cache_8h_source.htmlI tried this in my Extras.csUnfortunately , I get an entry point not found error . I guess my first thought is maybe the function is mangled but I thought since the 'extern C ' is there that should n't be happening ? Can anyone help me ? <code> void ccGLActiveTexture ( GLenum textureEnum ) { # if CC_ENABLE_GL_STATE_CACHE NSCAssert1 ( ( textureEnum - GL_TEXTURE0 ) < kCCMaxActiveTexture , @ '' cocos2d ERROR : Increase kCCMaxActiveTexture to % d ! `` , ( textureEnum-GL_TEXTURE0 ) ) ; if ( ( textureEnum - GL_TEXTURE0 ) ! = _ccCurrentActiveTexture ) { _ccCurrentActiveTexture = ( textureEnum - GL_TEXTURE0 ) ; glActiveTexture ( textureEnum ) ; } # else glActiveTexture ( textureEnum ) ; # endif } public partial class CCGLProgram { [ DllImport ( `` __Internal '' ) ] public static extern void ccGLUseProgram ( uint program ) ; public static void CCGLUseProgram ( uint test ) { ccGLUseProgram ( test ) ; } } | Is it possible to add C references to an objective c binding ? |
C_sharp : We 're trying to figure out when exactly an Entity Framework Database Initializer runs . MSDN says initializion happens the `` first time '' we access the database . When is `` first time '' ? MSDN contradicts itself , stating that initialization runs the first time an instance of a DbContext is used but also the first time a type of a DbContext is used . Which is it ? Further , MSDN does n't define `` first time '' ? Is this first time since publish ? first time since Application_Start ? first time for a given request , for a given method ? What if we restart the application by changing the web.config ? Here are some quotes from MSDN , saying database initializer runs ... when an instance of a DBContext derived class is used for the first timehttp : //msdn.microsoft.com/en-us/library/gg696323 % 28v=vs.113 % 29.aspx when the given DbContext type is used to access a database for the first timehttp : //msdn.microsoft.com/en-us/library/gg679461 % 28v=vs.113 % 29.aspxFor example , we have a controller action , in which we instantiate a DbContext and run an insert operation . If we call this action twice ( or 10,000 times ) , will the DbInitializer run that many times ? If we 're using the DropDatabaseCreateAlways initializer , and we call this action twice , will the Db have two Event rows , or will the initializer delete the Db between inserts , thereby leaving one Event row ? <code> public HttpResponseMessage PostEvent ( EventDTO eventDTO ) { var ev = new Event ( ) { Id = eventDTO.Id , Name = eventDTO.Name } ; using ( AttendanceContext db = new AttendanceContext ( ) ) { db.Events.Add ( ev ) ; db.SaveChanges ( ) ; } return Ok ( ) ; } | When exactly is the `` first time '' a DbContext accesses the database ? |
C_sharp : Here is what i have so far : it works on my LocalHost Database , and I can load my Data from it.however , I have a server , installed sqlserver with my database on that , basicaly when i change my sqlcommands connecting string this work but in some part of my program I used entity framework and have no idea how to change it connecting string , with some posts in stackoverflow I change that tobut it still read datas from my localhost and not connect to my server.I do n't know how when i change this connecting string to my server it still read data from my localhost database.what is the best way to change connecting string from App.Config ? <code> < add name= '' gymEntities1 '' connectionString= '' metadata=res : //*/DateModel.csdl|res : //*/DateModel.ssdl|res : //*/DateModel.msl ; provider=System.Data.SqlClient ; provider connection string= & quot ; data source= . ; initial catalog=gym ; user id=sa ; password=xxxx ; MultipleActiveResultSets=True ; App=EntityFramework & quot ; '' providerName= '' System.Data.EntityClient '' / > < add name= '' gymEntities2 '' connectionString= '' metadata=res : //*/DataModel.csdl|res : //*/DataModel.ssdl|res : //*/DataModel.msl ; provider=System.Data.SqlClient ; provider connection string= & quot ; data source=tcp:46.105.124.144 ; initial catalog = gym ; User ID=sa ; Password=xxxx & quot ; '' providerName= '' System.Data.EntityClient '' / > | Change Entity Framework Connecting String To Server |
C_sharp : I am building a simple Guard API to protect against illegal parameters being passed to functions and so on.I have the following code : At the moment the code can be used in a similar way to ( note this is just a dumb example ) : This all works fine . What I want to be able to do now is extend the API to include child properties in the checks in the following way : Obviously the new .Property method needs to return the parent GuardArgument in order to chain . Furthermore the child property needs to be able to use the existing check methods ( IsNotNull ( ) etc ) to avoid code duplication.I can not work out how to construct the lambda/Property function parameters or where the .Property method should be located - i.e . should it be a property on the GuardArgument or somewhere else , or even if there is a better structure to the API . <code> public static class Guard { public static GuardArgument < T > Ensure < T > ( T value , string argumentName ) { return new GuardArgument < T > ( value , argumentName ) ; } } public class GuardArgument < T > { public GuardArgument ( T value , string argumentName ) { Value = value ; Name = Name ; } public T Value { get ; private set ; } public string Name { get ; private set ; } } // Example extension for validity checkspublic static GuardArgument < T > IsNotNull < T > ( this GuardArgument < T > guardArgument , string errorMessage ) { if ( guardArgument.Value == null ) { throw new ArgumentNullException ( guardArgument.Name , errorMessage ) ; } return guardArgument ; } void DummyMethod ( int ? someObject ) { Guard.Ensure ( someObject , `` someObject '' ) .IsNotNull ( ) .IsGreaterThan ( 0 ) .IsLessThan ( 10 ) ; } Guard.Ensure ( someObject , `` someObject '' ) .IsNotNull ( ) .Property ( ( x = > x.ChildProp1 , `` childProp1 '' ) .IsNotNull ( ) .IsGreaterThan ( 10 ) ) .Property ( ( x = > x.ChildProp2 , `` childProp2 '' ) .IsNotNull ( ) .IsLessThan ( 10 ) ) ; | How to build a Fluent Nested Guard API |
C_sharp : Im trying to see how the fence is applied.I have this code ( which Blocks indefinitely ) : Writing volatile bool _complete ; solve the issue .Acquire fence : An acquire-fence prevents other reads/writes from being moved before the fence ; But if I illustrate it using an arrow ↓ ( Think of the arrowhead as pushing everything away . ) so now - the code can look like : I do n't understand how the illustrated drawing represent a solution for solving this issue.I do know that while ( ! complete ) now reads the real value . but how is it related to complete = true ; location to the fence ? <code> static void Main ( ) { bool complete = false ; var t = new Thread ( ( ) = > { bool toggle = false ; while ( ! complete ) toggle = ! toggle ; } ) ; t.Start ( ) ; Thread.Sleep ( 1000 ) ; complete = true ; t.Join ( ) ; // Blocks indefinitely } var t = new Thread ( ( ) = > { bool toggle = false ; while ( ! complete ) ↓↓↓↓↓↓↓ // instructions ca n't go up before this fence . { toggle = ! toggle ; } } ) ; | Volatile fence demo ? |
C_sharp : I have the following domain model : I implemented IUserType so I can map each name to a single database column with the full name.Queries like this work : But I ca n't query like this : Can I make NHibernate work with this ? <code> public class Name { private readonly string fullName ; public Name ( string fullName ) { this.fullName = fullName } public string FullName { get { return fullName ; } } public string FirstName { get { /* ... */ } } public string MiddleNames { get { /* ... */ } } public string LastName { get { /* ... */ } } public static implicit operator Name ( string name ) { /* ... */ } } public class Person { public Name BirthName { get ; set ; } public Name Pseudonym { get ; set ; } } var people = session.QueryOver < Person > ( ) .Where ( p = > p.Name == `` John Doe '' ) .List ( ) ; var people = session.QueryOver < Person > ( ) .Where ( p = > p.Name.LastName == `` Doe '' ) .List ( ) ; | Can I query a UserType with several properties mapped to a single column ? |
C_sharp : If an object has a Single Responsibility , can the following be acceptable : i.e . using a supplied collaborator ( which also helps to stop the domain model being anemic ) .Or should it be : <code> public class Person { public string Name ; public DateTime DateOfBirth ; private IStorageService _storageService ; public Person ( IStorageService storageService ) { _storageService = storageService } public void Save ( ) { _storageService.Persist ( this ) ; } } public class Person { public string Name ; public DateTime DateOfBirth ; public Person ( ) { } } public class StorageService { public void Persist ( Person p ) { } } | Single Responsibility and dependencies |
C_sharp : Is there any chance that this statement would return truecan a very fast machine return true for this statement , I tried on several machines and its always false ? <code> DateTime.Now == DateTime.Now | DateTime.Now retrieval speed |
C_sharp : I am having a problem understanding how polymorphism works when using generics . As an example , I have defined the following program : I can then do this , which works just fine : I have many classes that implement MyInterface . I would like to write a method that can accept all MyContainer objects : Now , I 'd like to call this method.That did n't work . Surely , because MyClass implements IMyInterface , I should be able to just cast it ? That did n't work either . I can definitely cast a normal MyClass to IMyInterface : So , at least I have n't completely misunderstood that . I am unsure exactly how I am to write a method that accepts a generic collection of classes that conform to the same interface.I have a plan to completely hack around this problem if need be , but I would really prefer to do it properly.Thank you in advance . <code> public interface IMyInterface { void MyMethod ( ) ; } public class MyClass : IMyInterface { public void MyMethod ( ) { } } public class MyContainer < T > where T : IMyInterface { public IList < T > Contents ; } MyContainer < MyClass > container = new MyContainer < MyClass > ( ) ; container.Contents.Add ( new MyClass ( ) ) ; public void CallAllMethodsInContainer ( MyContainer < IMyInterface > container ) { foreach ( IMyInterface myClass in container.Contents ) { myClass.MyMethod ( ) ; } } MyContainer < MyClass > container = new MyContainer < MyClass > ( ) ; container.Contents.Add ( new MyClass ( ) ) ; this.CallAllMethodsInContainer ( container ) ; MyContainer < IMyInterface > newContainer = ( MyContainer < IMyInterface > ) container ; MyClass newClass = new MyClass ( ) ; IMyInterface myInterface = ( IMyInterface ) newClass ; | Please help me understand polymorphism when using generics in c # |
C_sharp : i see this Question best-way-to-clear-contents-of-nets-stringbuilder/the answerers set the length to zero and also worries about capacity ? does it really matter to set capacity ? f we dis-assemble .net 4.5 Library , navigate to System.Text.StringBuilderis it really matters to set capacity when we already set its length to zero ... or ms does n't care that ? <code> /// < summary > /// Removes all characters from the current < see cref= '' T : System.Text.StringBuilder '' / > instance . /// < /summary > /// /// < returns > /// An object whose < see cref= '' P : System.Text.StringBuilder.Length '' / > /// is 0 ( zero ) . /// < /returns > [ __DynamicallyInvokable ] public StringBuilder Clear ( ) { this.Length = 0 ; return this ; } | is Capacity property of Stringbuilder really matters when we set its length to zero ? |
C_sharp : When creating webservices , in c # , I have found it very useful to pass back jagged arrays , i.e . string [ ] [ ] I also found a neat trick to build these in a simple way in my code , which was to create a List and convert it by doing a ToArray ( ) call.e.g.I would like to be able to employ a similar solution , but I ca n't think how to do something similar with a 3 level jagged array or string [ ] [ ] [ ] , without resorting to loops and such . RegardsMartin <code> public string [ ] [ ] myws ( ) { List < string [ ] > output = new List < string [ ] > ( ) ; return output.ToArray ( ) ; } | converting List < List < string [ ] > > into string [ ] [ ] [ ] in c # |
C_sharp : It is very unpredictable result of code for me.I did not expect this code to produce such a result.So , I read Jeffrey Richter 's book ( clr ia c # ) and there is a example with this code.And , as some of you can suggest we can see in console four names.So , my question is : How do we get our names , if they are going to get in Students and respectively in _students , that were not assigned because of nonexistence of Students setter.__________EDIT_1_______________I read your answers , and thank you for those.But , you know , it is kind of misunderstanding ... I really ca n't figure it out.When I Initialize Students , I initialize _students ? And what not less important , when I take variable from IEnumerable ( some ) , I am take variable from Students ? I think not.I ca n't understand , WHERE exactly I assign variables ( INITALIZE ) _students collections ? Thank you for help me to figure it out ! <code> internal class ClassRoom { private List < String > _students = new List < string > ( ) ; public List < String > Students { get { return _students ; } } } ClassRoom classRoom = new ClassRoom { Students = { `` Mike '' , `` Johny '' , `` Vlad '' , `` Stas '' } } ; foreach ( var some in classRoom.Students ) { Console.WriteLine ( some ) ; } | Why does collection initializer work with getter-only property ? |
C_sharp : I develop a system with plugins , which loads assemblies at runtime . I have a common interface library , which i share between server and its plugins . But , when i perform LoadFrom for plugin folder and try to find all types , which implement common interface IServerModule i get runtime exception : The type 'ServerCore.IServerModule ' exists in both 'ServerCore.dll ' and 'ServerCore.dll ' I load plugins like this : How can i deal with this trouble ? I 'll be gratefull for any help <code> foreach ( var dll in dlls ) { var assembly = Assembly.LoadFrom ( dll ) ; var modules = assembly.GetExportedTypes ( ) .Where ( type = > ( typeof ( IServerModule ) ) .IsAssignableFrom ( type ) & & ! type.IsAbstract & & ! type.IsGenericTypeDefinition ) .Select ( type = > ( IServerModule ) Activator.CreateInstance ( type ) ) ; result.AddRange ( modules ) ; } | How to load assembly correctly |
C_sharp : I am using asp.net web api 2 and Entity Framework 6.Original pseudo codeModified codeBefore my change everything ran synchronously.After my change the call to a remote service which is calling again a database is done the async-await way.Then I do a sync call to a rendering library which offers only sync methods . The calculation takes 1,5 seconds.Is there still a benefit that I did the remote database_service call the async-await way but the 2nd call not ? And is there anything I could still improve ? NoteThe reason why I ask this is because : '' With async controllers when a process is waiting for I/O to complete , its thread is freed up for the server to use for processing other requests . `` So when the first remote database_service call is processing and awaiting for that 1 second the thread is returned to IIS ? ? ! ! But what about the 2nd label calculation taking 1,5 seconds that will block the current thread again for 1,5 seconds ? So I release and block the thread , that does not make sense or what do you think ? <code> public IHttpActionResult GetProductLabel ( int productId ) { var productDetails = repository.GetProductDetails ( productId ) ; var label = labelCalculator.Render ( productDetails ) ; return Ok ( label ) ; } public async Task < IHttpActionResult > GetProductLabel ( int productId ) { var productDetails = await repository.GetProductDetailsAsync ( productId ) ; // 1 long second as this call goes into sub services var label = labelCalculator.Render ( productDetails ) ; // 1.5 seconds synchrounous code return Ok ( label ) ; } | async await calling long running sync AND async methods |
C_sharp : My entity `` Progetto '' map a view with name VW_AMY_PRG_WCS_LookupProgetto has five navigations property : ClienteDiFatturazione , ClienteDiLavorazione , PercentualeSuccesso , Agente having multiplicity 0..1 and DocumentiWcs having mupltiplicity *When I run this simple statement in LINQPadthe sql generated isI wonder why the generated SQL query involves so many left outer join ; i would expect a simple select on VW_AMY_PRG_WCS_Lookup . What is the purpose of this behavior ? Being the entity mapped to a View multiple joins have a heavy impact on query performance . Any workaround ? UPDATEBeing VW_AMY_PRG_WCS_Lookup a view I had to manually add all the associations and navigation properties ( no fk defined at database level so no associations generated when model has been created from database ) IdAnagrafica_Fatturazione refers to ClienteDIfatturazione , IdAnagrafica_Lavorazione refers to ClienteDiLavorazione , IdPercentuale_Successo refers to PercentualeSuccesso and IdAgente to Agente , I just renamed the field in the model so their name are a little differente from the fields in the view . This is the code of Progetto classHere the DefiningQuery for the view VW_AMY_PRG_WCS_Lookup <code> var prj = Progetti.AsQueryable ( ) ; prj.ToList ( ) ; SELECT [ Extent1 ] . [ IdProgetto ] AS [ IdProgetto ] , [ Extent1 ] . [ IdSerie_Progetto ] AS [ IdSerie_Progetto ] , [ Extent1 ] . [ Importo ] AS [ Importo ] , [ Extent1 ] . [ Data_Prevista_Chiusura ] AS [ Data_Prevista_Chiusura ] , [ Extent1 ] . [ IdStato ] AS [ IdStato ] , [ Extent1 ] . [ Oggetto ] AS [ Oggetto ] , [ Extent1 ] . [ IdMezzo_Pervenuto ] AS [ IdMezzo_Pervenuto ] , [ Extent1 ] . [ IdAgente ] AS [ IdAgente ] , [ Extent1 ] . [ Fido_Residuo ] AS [ Fido_Residuo ] , [ Extent2 ] . [ IdAnagrafica_Fatturazione ] AS [ IdAnagrafica_Fatturazione ] , [ Extent3 ] . [ IdAnagrafica_Lavorazione ] AS [ IdAnagrafica_Lavorazione ] , [ Extent4 ] . [ IdPercentuale_Successo ] AS [ IdPercentuale_Successo ] FROM ( SELECT [ VW_AMY_PRG_WCS_Lookup ] . [ IdProgetto ] AS [ IdProgetto ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdSerie_Progetto ] AS [ IdSerie_Progetto ] , [ VW_AMY_PRG_WCS_Lookup ] . [ Importo ] AS [ Importo ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdPercentuale_Successo ] AS [ IdPercentuale_Successo ] , [ VW_AMY_PRG_WCS_Lookup ] . [ Data_Prevista_Chiusura ] AS [ Data_Prevista_Chiusura ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdAnagrafica_Lavorazione ] AS [ IdAnagrafica_Lavorazione ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdAnagrafica_Fatturazione ] AS [ IdAnagrafica_Fatturazione ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdMezzo_Pervenuto ] AS [ IdMezzo_Pervenuto ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdStato ] AS [ IdStato ] , [ VW_AMY_PRG_WCS_Lookup ] . [ Oggetto ] AS [ Oggetto ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdAgente ] AS [ IdAgente ] , [ VW_AMY_PRG_WCS_Lookup ] . [ Fido_Residuo ] AS [ Fido_Residuo ] FROM [ dbo ] . [ VW_AMY_PRG_WCS_Lookup ] AS [ VW_AMY_PRG_WCS_Lookup ] ) AS [ Extent1 ] LEFT OUTER JOIN ( SELECT [ VW_AMY_PRG_WCS_Lookup ] . [ IdProgetto ] AS [ IdProgetto ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdSerie_Progetto ] AS [ IdSerie_Progetto ] , [ VW_AMY_PRG_WCS_Lookup ] . [ Importo ] AS [ Importo ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdPercentuale_Successo ] AS [ IdPercentuale_Successo ] , [ VW_AMY_PRG_WCS_Lookup ] . [ Data_Prevista_Chiusura ] AS [ Data_Prevista_Chiusura ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdAnagrafica_Lavorazione ] AS [ IdAnagrafica_Lavorazione ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdAnagrafica_Fatturazione ] AS [ IdAnagrafica_Fatturazione ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdMezzo_Pervenuto ] AS [ IdMezzo_Pervenuto ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdStato ] AS [ IdStato ] , [ VW_AMY_PRG_WCS_Lookup ] . [ Oggetto ] AS [ Oggetto ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdAgente ] AS [ IdAgente ] , [ VW_AMY_PRG_WCS_Lookup ] . [ Fido_Residuo ] AS [ Fido_Residuo ] FROM [ dbo ] . [ VW_AMY_PRG_WCS_Lookup ] AS [ VW_AMY_PRG_WCS_Lookup ] ) AS [ Extent2 ] ON ( [ Extent2 ] . [ IdAnagrafica_Fatturazione ] IS NOT NULL ) AND ( [ Extent1 ] . [ IdProgetto ] = [ Extent2 ] . [ IdProgetto ] ) AND ( [ Extent1 ] . [ IdSerie_Progetto ] = [ Extent2 ] . [ IdSerie_Progetto ] ) LEFT OUTER JOIN ( SELECT [ VW_AMY_PRG_WCS_Lookup ] . [ IdProgetto ] AS [ IdProgetto ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdSerie_Progetto ] AS [ IdSerie_Progetto ] , [ VW_AMY_PRG_WCS_Lookup ] . [ Importo ] AS [ Importo ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdPercentuale_Successo ] AS [ IdPercentuale_Successo ] , [ VW_AMY_PRG_WCS_Lookup ] . [ Data_Prevista_Chiusura ] AS [ Data_Prevista_Chiusura ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdAnagrafica_Lavorazione ] AS [ IdAnagrafica_Lavorazione ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdAnagrafica_Fatturazione ] AS [ IdAnagrafica_Fatturazione ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdMezzo_Pervenuto ] AS [ IdMezzo_Pervenuto ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdStato ] AS [ IdStato ] , [ VW_AMY_PRG_WCS_Lookup ] . [ Oggetto ] AS [ Oggetto ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdAgente ] AS [ IdAgente ] , [ VW_AMY_PRG_WCS_Lookup ] . [ Fido_Residuo ] AS [ Fido_Residuo ] FROM [ dbo ] . [ VW_AMY_PRG_WCS_Lookup ] AS [ VW_AMY_PRG_WCS_Lookup ] ) AS [ Extent3 ] ON ( [ Extent3 ] . [ IdAnagrafica_Lavorazione ] IS NOT NULL ) AND ( [ Extent1 ] . [ IdProgetto ] = [ Extent3 ] . [ IdProgetto ] ) AND ( [ Extent1 ] . [ IdSerie_Progetto ] = [ Extent3 ] . [ IdSerie_Progetto ] ) LEFT OUTER JOIN ( SELECT [ VW_AMY_PRG_WCS_Lookup ] . [ IdProgetto ] AS [ IdProgetto ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdSerie_Progetto ] AS [ IdSerie_Progetto ] , [ VW_AMY_PRG_WCS_Lookup ] . [ Importo ] AS [ Importo ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdPercentuale_Successo ] AS [ IdPercentuale_Successo ] , [ VW_AMY_PRG_WCS_Lookup ] . [ Data_Prevista_Chiusura ] AS [ Data_Prevista_Chiusura ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdAnagrafica_Lavorazione ] AS [ IdAnagrafica_Lavorazione ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdAnagrafica_Fatturazione ] AS [ IdAnagrafica_Fatturazione ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdMezzo_Pervenuto ] AS [ IdMezzo_Pervenuto ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdStato ] AS [ IdStato ] , [ VW_AMY_PRG_WCS_Lookup ] . [ Oggetto ] AS [ Oggetto ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdAgente ] AS [ IdAgente ] , [ VW_AMY_PRG_WCS_Lookup ] . [ Fido_Residuo ] AS [ Fido_Residuo ] FROM [ dbo ] . [ VW_AMY_PRG_WCS_Lookup ] AS [ VW_AMY_PRG_WCS_Lookup ] ) AS [ Extent4 ] ON ( [ Extent4 ] . [ IdPercentuale_Successo ] IS NOT NULL ) AND ( [ Extent1 ] . [ IdProgetto ] = [ Extent4 ] . [ IdProgetto ] ) AND ( [ Extent1 ] . [ IdSerie_Progetto ] = [ Extent4 ] . [ IdSerie_Progetto ] ) // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- // < auto-generated > // This code was generated from a template.//// Manual changes to this file may cause unexpected behavior in your application.// Manual changes to this file will be overwritten if the code is regenerated.// < /auto-generated > // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- namespace EntityModel { using System ; using System.Collections.Generic ; public partial class Progetto { [ System.Diagnostics.CodeAnalysis.SuppressMessage ( `` Microsoft.Usage '' , `` CA2214 : DoNotCallOverridableMethodsInConstructors '' ) ] public Progetto ( ) { this.DocumentiWcs = new HashSet < DocumentoWcsProgetto > ( ) ; } public int Codice { get ; set ; } public int Serie { get ; set ; } public Nullable < decimal > Importo { get ; set ; } public Nullable < System.DateTime > DataPrevistaChiusura { get ; set ; } public Nullable < int > IdStato { get ; set ; } public string Oggetto { get ; set ; } public Nullable < int > IdMezzoPervenuto { get ; set ; } public Nullable < int > IdAgente { get ; set ; } public Nullable < decimal > FidoResiduo { get ; set ; } public virtual Cliente ClienteDiFatturazione { get ; set ; } public virtual Cliente ClienteDiLavorazione { get ; set ; } public virtual PercentualeSuccesso PercentualeSuccesso { get ; set ; } [ System.Diagnostics.CodeAnalysis.SuppressMessage ( `` Microsoft.Usage '' , `` CA2227 : CollectionPropertiesShouldBeReadOnly '' ) ] public virtual ICollection < DocumentoWcsProgetto > DocumentiWcs { get ; set ; } public virtual Agente Agente { get ; set ; } } } < EntitySet Name= '' VW_AMY_PRG_WCS_Lookup '' EntityType= '' Self.VW_AMY_PRG_WCS_Lookup '' store : Type= '' Views '' store : Schema= '' dbo '' > < DefiningQuery > SELECT [ VW_AMY_PRG_WCS_Lookup ] . [ IdProgetto ] AS [ IdProgetto ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdSerie_Progetto ] AS [ IdSerie_Progetto ] , [ VW_AMY_PRG_WCS_Lookup ] . [ Importo ] AS [ Importo ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdPercentuale_Successo ] AS [ IdPercentuale_Successo ] , [ VW_AMY_PRG_WCS_Lookup ] . [ Data_Prevista_Chiusura ] AS [ Data_Prevista_Chiusura ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdAnagrafica_Lavorazione ] AS [ IdAnagrafica_Lavorazione ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdAnagrafica_Fatturazione ] AS [ IdAnagrafica_Fatturazione ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdMezzo_Pervenuto ] AS [ IdMezzo_Pervenuto ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdStato ] AS [ IdStato ] , [ VW_AMY_PRG_WCS_Lookup ] . [ Oggetto ] AS [ Oggetto ] , [ VW_AMY_PRG_WCS_Lookup ] . [ IdAgente ] AS [ IdAgente ] , [ VW_AMY_PRG_WCS_Lookup ] . [ Fido_Residuo ] AS [ Fido_Residuo ] FROM [ dbo ] . [ VW_AMY_PRG_WCS_Lookup ] AS [ VW_AMY_PRG_WCS_Lookup ] < /DefiningQuery > < /EntitySet > | EF Linq to Entities calling ToList ( ) on entity set generates SQL command containing multiple left outer join |
C_sharp : Since I have another method where the only difference is the expression in the return statement , how to pass Expression.OrElse as a parameter to the method ( my other method uses AndAlso ) ? Since the methods are close to identical I would like one common method with the expression passed as a parameter.I 've tried passing a BinaryExpression without success . <code> public static Expression < Func < T , bool > > OrElse < T > ( this Expression < Func < T , bool > > expr1 , Expression < Func < T , bool > > expr2 ) { ParameterExpression parameter = Expression.Parameter ( typeof ( T ) ) ; ReplaceExpressionVisitor leftVisitor = new ReplaceExpressionVisitor ( expr1.Parameters [ 0 ] , parameter ) ; Expression left = leftVisitor.Visit ( expr1.Body ) ; ReplaceExpressionVisitor rightVisitor = new ReplaceExpressionVisitor ( expr2.Parameters [ 0 ] , parameter ) ; Expression right = rightVisitor.Visit ( expr2.Body ) ; return Expression.Lambda < Func < T , bool > > ( Expression.OrElse ( left , right ) , parameter ) ; } | Passing a BinaryExpression as parameter |
C_sharp : I 'm programming an apartment & house rental site . Since there are never more than 10'000 properties for rent , it 's no problem to load em all into memory . Now , when a users want to search for a specific one , he can define very much filters for price , room , escalator etc.Every property has a very different set of attributes . One property may have an attribute that another property does not have . So , creating a Class in C # that has all the attributes , while only a few of them are used is not a good idea to me . I decided to use a Dictionary instead.A few benchmarks later , I found out , that the Dictionary is about 40 times slower in accessing attributes as a Class . I also did a benchmark for node.js , which just used objects as dictionarys . This was absolutely interesting because the exact same program in node.js performed even better than the C # example with a native class.In fact I got the following results : C # Dictionary : ~820msC # Class : ~26msNode.js Object : ~24msEach benchmark searched 1'000'000 objects by the same criterias.I know that the Node.js version is that fast because of the V8 engine by Google . Do you know if there is a C # class that uses similar techniques as the V8 engine and gets almost the same performance ? C # Dictionary BenchmarkC # Class BenchmarkNode.js Benchmark <code> namespace Test { class Program { static void Main ( string [ ] args ) { PropertyList p = new PropertyList ( ) ; long startTime = DateTime.Now.Ticks ; for ( int i = 0 ; i < 100 ; i++ ) { p.Search ( ) ; } Console.WriteLine ( ( DateTime.Now.Ticks - startTime ) / 10000 ) ; } } class PropertyList { List < Property > properties = new List < Property > ( ) ; public PropertyList ( ) { for ( int i = 0 ; i < 10000 ; i++ ) { Property p = new Property ( ) ; p [ `` Strasse '' ] = `` Oberdorfstrasse '' ; p [ `` StrassenNr '' ] = 6 ; p [ `` Plz '' ] = 6277 ; p [ `` Ort '' ] = `` Lieli '' ; p [ `` Preis '' ] = 600 ; p [ `` Fläche '' ] = 70 ; p [ `` Zimmer '' ] = 2 ; p [ `` Lift '' ] = true ; p [ `` Verfügbarkeit '' ] = 7 ; p [ `` Keller '' ] = false ; p [ `` Neubau '' ] = true ; p [ `` ÖV '' ] = false ; properties.Add ( p ) ; } } public void Search ( ) { int found = 0 ; for ( int i = 0 ; i < properties.Count ; i++ ) { Property p = properties [ i ] ; if ( ( string ) p [ `` Strasse '' ] == `` Oberdorfstrasse '' & & ( int ) p [ `` StrassenNr '' ] == 6 & & ( int ) p [ `` Plz '' ] == 6277 & & ( string ) p [ `` Ort '' ] == `` Lieli '' & & ( int ) p [ `` Preis '' ] > = 500 & & ( int ) p [ `` Preis '' ] < = 1000 & & ( int ) p [ `` Fläche '' ] > = 10 & & ( int ) p [ `` Fläche '' ] < = 200 & & ( int ) p [ `` Zimmer '' ] == 2 & & ( bool ) p [ `` Lift '' ] == true & & ( int ) p [ `` Verfügbarkeit '' ] > = 2 & & ( int ) p [ `` Verfügbarkeit '' ] < = 8 & & ( bool ) p [ `` Keller '' ] == false & & ( bool ) p [ `` Neubau '' ] == true & & ( bool ) p [ `` ÖV '' ] == true ) { found++ ; } } } } class Property { private Dictionary < string , object > values = new Dictionary < string , object > ( ) ; public object this [ string key ] { get { return values [ key ] ; } set { values [ key ] = value ; } } } } namespace Test { class Program { static void Main ( string [ ] args ) { SpecificPropertyList p2 = new SpecificPropertyList ( ) ; long startTime2 = DateTime.Now.Ticks ; for ( int i = 0 ; i < 100 ; i++ ) { p2.Search ( ) ; } Console.WriteLine ( ( DateTime.Now.Ticks - startTime2 ) / 10000 ) ; } } class SpecificPropertyList { List < SpecificProperty > properties = new List < SpecificProperty > ( ) ; public SpecificPropertyList ( ) { for ( int i = 0 ; i < 10000 ; i++ ) { SpecificProperty p = new SpecificProperty ( ) ; p.Strasse = `` Oberdorfstrasse '' ; p.StrassenNr = 6 ; p.Plz = 6277 ; p.Ort = `` Lieli '' ; p.Preis = 600 ; p.Fläche = 70 ; p.Zimmer = 2 ; p.Lift = true ; p.Verfügbarkeit = 7 ; p.Keller = false ; p.Neubau = true ; p.ÖV = false ; properties.Add ( p ) ; } } public void Search ( ) { int found = 0 ; for ( int i = 0 ; i < properties.Count ; i++ ) { SpecificProperty p = properties [ i ] ; if ( p.Strasse == `` Oberdorfstrasse '' & & p.StrassenNr == 6 & & p.Plz == 6277 & & p.Ort == `` Lieli '' & & p.Preis > = 500 & & p.Preis < = 1000 & & p.Fläche > = 10 & & p.Fläche < = 200 & & p.Zimmer == 2 & & p.Lift == true & & p.Verfügbarkeit > = 2 & & p.Verfügbarkeit < = 8 & & p.Keller == false & & p.Neubau == true & & p.ÖV == true ) { found++ ; } } } } class SpecificProperty { public string Strasse ; public int StrassenNr ; public int Plz ; public string Ort ; public int Preis ; public int Fläche ; public int Zimmer ; public bool Lift ; public int Verfügbarkeit ; public bool Keller ; public bool Neubau ; public bool ÖV ; } } var properties = [ ] ; for ( var i = 0 ; i < 10000 ; i++ ) { var p = { Strasse : '' Oberdorfstrasse '' , StrassenNr:6 , Plz:6277 , Ort : '' Lieli '' , Preis:600 , Fläche:70 , Zimmer:2 , Lift : true , Verfügbarkeit:7 , Keller : false , Neubau : true , ÖV : false } ; properties.push ( p ) ; } function search ( ) { var found = 0 ; for ( var i = 0 ; i < properties.length ; i++ ) { var p = properties [ i ] ; if ( p.Strasse == `` Oberdorfstrasse '' & & p.StrassenNr == 6 & & p.Plz == 6277 & & p.Ort == `` Lieli '' & & p.Preis > = 500 & & p.Preis < = 1000 & & p.Fläche > = 10 & & p.Fläche < = 100 & & p.Zimmer == 2 & & p.Verfügbarkeit > = 2 & & p.Verfügbarkeit < = 8 & & p.Keller == false & & p.Neubau == true & & p.ÖV == false ) { found++ ; } } } var startTime = new Date ( ) .getTime ( ) ; for ( var i = 0 ; i < 100 ; i++ ) { search ( ) ; } console.log ( new Date ( ) .getTime ( ) -startTime ) ; | V8-like Hashtable for C # ? |
C_sharp : I 've written the following LINQ query : The objective is to retrieve a list of the countries represented by the competitors found in the system . 'countries ' is an array of ISOCountry objects explicitly created and returned as an IQueryable < ISOCountry > ( ISOCountry is an object of just two strings , isoCountryCode and Name ) . Competitors is an IQueryable < Competitor > which is bound to a database table through LINQ to SQL though I created the objects from scratch and used the LINQ data mapping decorators.For some reason , this query causes a stack overflow when the system tries to execute it . I 've no idea why , I 've tried trimming the Distinct , returning an anonymous type of the two strings , using 'select c ' , but all result in the overflow . The e.CountryID value is populated from a dropdown that was in itself populated from the IQueryable < ISOCountry > , so I know the values are appropriate but even if not , I would n't expect a stack overflow.Why is the overflow is occurring or why might it be happening ? As requested , code for ISOCountry : It 's initialised from a static utility class thus : How I finally got it to work , see below ... I am still curious as to what specifically is wrong with the original query , I 'm sure I 've done similar things before . <code> IQueryable < ISOCountry > entries = ( from e in competitorRepository.Competitors join c in countries on e.countryID equals c.isoCountryCode where ! e.Deleted orderby c.isoCountryCode select new ISOCountry ( ) { isoCountryCode = e.countryID , Name = c.Name } ) .Distinct ( ) ; public class ISOCountry { public string isoCountryCode { get ; set ; } public string Name { get ; set ; } } public static IQueryable < ISOCountry > GetCountryCodes ( ) { // ISO 3166-1 country names and codes from http : //opencountrycodes.appspot.com/javascript ISOCountry [ ] countries = new ISOCountry [ ] { new ISOCountry { isoCountryCode= `` AF '' , Name= `` Afghanistan '' } , new ISOCountry { isoCountryCode= `` AX '' , Name= `` Aland Islands '' } , new ISOCountry { isoCountryCode= `` AL '' , Name= `` Albania '' } , new ISOCountry { isoCountryCode= `` DZ '' , Name= `` Algeria '' } , new ISOCountry { isoCountryCode= `` AS '' , Name= `` American Samoa '' } , ... new ISOCountry { isoCountryCode= `` YE '' , Name= `` Yemen '' } , new ISOCountry { isoCountryCode= `` ZM '' , Name= `` Zambia '' } , new ISOCountry { isoCountryCode = `` ZW '' , Name = `` Zimbabwe '' } } ; return countries.AsQueryable ( ) ; } IList < string > entries = competitorRepository.Competitors.Select ( c= > c.CountryID ) .Distinct ( ) .ToList ( ) ; IList < ISOCountry > countries = Address.GetCountryCodes ( ) .Where ( a = > entries.Contains ( a.isoCountryCode ) ) .ToList ( ) ; | Tracking down a stack overflow error in my LINQ query |
C_sharp : I 'd like to implement a sort of Factory Pattern for XAML . I created an app for WinRT where I defined two xaml style files . Basically , what I 'd like to achieve ( if possible ) is to load one of the the two xaml file when the application starts.in the solution explorer I have this : CustomStyles foder contains the style files . So , based on an enumerator in my App.xaml.cs fileif I choose Style_1 I 'd like to load the xaml file Style_1.xaml else Style_2.xaml at run-time.Both the style files , have the same definition of Button style , TextBlock style , etc with different property values . Here an example : Style_1.xamlStyle_2.xamlThere is a way to achieve what I want to do ? Thank you in advance . <code> public enum Style { Style_1 , Style_2 } < Style x : Key= '' Attribute_Label '' TargetType= '' TextBlock '' > < Setter Property= '' FontFamily '' Value= '' Segoe UI '' / > < Setter Property= '' Foreground '' Value= '' # 78CAB3 '' / > < Setter Property= '' FontSize '' Value= '' 15 '' / > < Setter Property= '' FontWeight '' Value= '' Normal '' / > < /Style > < Style x : Key= '' Attribute_Label '' TargetType= '' TextBlock '' > < Setter Property= '' FontFamily '' Value= '' Arial '' / > < Setter Property= '' Foreground '' Value= '' # 606060 '' / > < Setter Property= '' FontSize '' Value= '' 30 '' / > < Setter Property= '' FontWeight '' Value= '' Normal '' / > < /Style > | XAML WinRT - Factory Pattern for Custom Styles |
C_sharp : I 'm working on some test cases at the moment , and I 'm regularly finding that I 'm ending up with multiple asserts in each case . For example ( over-simplified and comments stripped for brevity ) : This looks acceptable in principle , but the point of the test is to verify that when the the class is instantiated with a given name , the Name property is set correctly , but it fails if anything goes wrong on instantiation , before it even gets to the assertion.I refactored it like this : but of course , now I 'm actually testing three things here ; In this test , I 'm not interested in testing whether or not the instance of MyClass was successfully instantiated , or that the Name property was read successfully , these are tested in another case . But how can I test the last assertion without asserting the other two first , given that it 's not possible to even do the test if the first two fail ? <code> [ Test ] public void TestNamePropertyCorrectlySetOnInstantiation ( ) { MyClass myInstance = new MyClass ( `` Test name '' ) ; Assert.AreEqual ( `` Test Name '' , myInstance.Name ) ; } [ Test ] public void TestNamePropertyCorrectlySetOnInstantiation ( ) { MyClass myInstance ; string namePropertyValue ; Assert.DoesNotThrow ( ( ) = > myInstance = new MyClass ( `` Test name '' ) ) ; Assert.DoesNotThrow ( ( ) = > namePropertyValue = myInstance.Name ) ; Assert.AreEqual ( `` Test Name '' , namePropertyValue ) ; } | How to prevent 'over-testing ' in a test case ? ( C # /nUnit ) |
C_sharp : I have following DbContext and I want to migrate it using Entity FramworkI ran the statement in the Package Manager Console to generate the configuration.But the generation has compilation errors because following namespaces/classes ca n't be found : .Any solutions on how the configuration could compile so I can add the migration ? <code> public class TestDbContext : DbContext { public DbSet < State > States { get ; set ; } public DbSet < StateType > StateTypes { get ; set ; } public DbSet < Measure > Measures { get ; set ; } public DbSet < Priority > Priorities { get ; set ; } public DbSet < Task > Tasks { get ; set ; } public DbSet < TaskType > TaskTypes { get ; set ; } public DbSet < Document > Documents { get ; set ; } protected override void OnConfiguring ( DbContextOptionsBuilder optionsBuilder ) { string databaseFilePath = `` test.db '' ; try { databaseFilePath = Path.Combine ( ApplicationData.Current.LocalFolder.Path , databaseFilePath ) ; } catch ( InvalidOperationException ) { } optionsBuilder.UseSqlite ( $ '' Data source= { databaseFilePath } '' ) ; } protected override void OnModelCreating ( ModelBuilder modelBuilder ) { } enable-migrations -ContextTypeName TestData.TestDbContext using System.Data.Entity ; using System.Data.Entity.Migrations ; DbMigrationsConfiguration namespace TestData.Migrations { using System ; using System.Data.Entity ; using System.Data.Entity.Migrations ; using System.Linq ; internal sealed class Configuration : DbMigrationsConfiguration < TestDatas.TestDbContext > { public Configuration ( ) { AutomaticMigrationsEnabled = false ; } protected override void Seed ( TestDatas.TestDbContext context ) { // This method will be called after migrating to the latest version . // You can use the DbSet < T > .AddOrUpdate ( ) helper extension method // to avoid creating duplicate seed data . E.g . // // context.People.AddOrUpdate ( // p = > p.FullName , // new Person { FullName = `` Andrew Peters '' } , // new Person { FullName = `` Brice Lambson '' } , // new Person { FullName = `` Rowan Miller '' } // ) ; // } } } | EF Migration for Universal Windows Platform |
C_sharp : Whilst browsing through some legacy code , I was surprised to encounter an abstract override of a member that was abstract by itself . Basically , something like this : Is n't the distinction between a virtual or abstract member always available to the compiler ? Why does C # support this ? ( This question is not a duplicate of What is the use of 'abstract override ' in C # ? because the DoStuff-method in class A is not virtual but abstract as well . ) <code> public abstract class A { public abstract void DoStuff ( ) ; } public abstract class B : A { public override abstract void DoStuff ( ) ; // < -- - Why is this supported ? } public abstract class C : B { public override void DoStuff ( ) = > Console.WriteLine ( `` ! `` ) ; } | Why does C # support abstract overrides of abstract members ? |
C_sharp : I have a requirement to create some objects that implement a given interface , where the type of concrete implementation being created is based on an Enum value.I run into trouble when the different concrete implementations require different parameters at runtime.This example ( C # ) is fine : However , what happens if the concrete implementations have different constructor arguments ? I ca n't pass in all the values to the SerialNumberValidatorFactory.CreateValidator ( ) method , so how do I proceed ? I 've heard the Abstract Factory pattern is supposed to solve this , but I 'm not sure how to implement it properly . <code> public enum ProductCategory { Modem , Keyboard , Monitor } public class SerialNumberValidatorFactory ( ) { public ISerialNumberValidator CreateValidator ( ProductCategory productCategory ) { switch ( productCategory ) { case ProductCategory.Modem : return new ModemSerialNumberValidator ( ) ; case ProductCategory.Keyboard : return new KeyboardSerialNumberValidator ( ) ; case ProductCategory.Monitor : return new MonitorSerialNumberValidator ( ) ; default : throw new ArgumentException ( `` productType '' , string.Format ( `` Product category not supported for serial number validation : { 0 } '' , productCategory ) ) } } } | Will the Factory Pattern solve my problem ? |
C_sharp : I have two download file methods , so I wanted to extract part which actually hits the disk to some helper/service class , but I struggle with returning that file to controller and then to userHow can I return from class that does not derives from Controller a file with that easy-to-work method from Mvc.ControllerBase.File ? The error is An object reference is required for the non-static field , method , or property 'ControllerBase.File ( Stream , string , string ) 'for this line : Is there any possibility to achieve that ? <code> public ( bool Success , string ErrorMessage , IActionResult File ) TryDownloadFile ( string FilePath , string FriendlyName ) { try { var bytes = File.ReadAllBytes ( FilePath ) ; if ( FilePath.EndsWith ( `` .pdf '' ) ) { return ( true , `` '' , new FileContentResult ( bytes , `` application/pdf '' ) ) ; } else { return ( true , `` '' , ControllerBase.File ( bytes , `` application/octet-stream '' , FriendlyName ) ) ; } } catch ( Exception ex ) { return ( false , ex.Message , null ) ; } } return ( true , `` '' , ControllerBase.File ( bytes , `` application/octet-stream '' , FriendlyName ) ) ; | How to return ActionResult ( file ) from class that does not derive from Controller ? |
C_sharp : I am trying to pass multiple paths as arguments to a console application but am getting an `` Illegal characters in path '' error . It appears that something is mistaking the last two characters of the argument `` C : \test\ '' for an escaped double-quote.For example , if I create a new empty console application in C # like so : and , under Project Properties - > Debug I add a command line argument like so : then my output looks like this : If the value is being evaluated/un-escaped , why does \t not become a tab ? If the value is NOT being evaluated/un-escaped , why does \ '' become a double-quote ? ( Note : I know I can work around this by , for example , trimming trailing backslashes etc . I 'm asking for help understanding why the arguments appear to be partially evaluated ) <code> static void Main ( string [ ] args ) { Console.WriteLine ( args [ 0 ] ) ; Console.ReadLine ( ) ; } | Why does C # appear to partially un-escape command line arguments ? |
C_sharp : I 'm confused is it possible to create a sdk-style .net framework project in Visual Studio ( to be more specific I use the latest VS2019 ) . Or it still requires manual manipulations ? I 'm interested in creating a new project not in migrating existed project from old .csproj file style to the new .csproj sdk-style.I 've already edited .csproj files manually many times but it 's super inconvenient . <code> < Project Sdk= '' Microsoft.NET.Sdk '' > | How to create a sdk-style .net framework project in VS ? |
C_sharp : I have noticed a new tendency in .NET 4.0 , specifically in potentially multi-threaded scenarios , which is avoiding events , and providing subscriber methods instead.For example , System.Threading.Tasks.Task and Task < TResult > have ContinueWith ( ) methods instead of a Completed or Finished event . Another example is System.Threading.CancellationToken : it has a Register ( ) method instead of a CancellationRequested event.While Task.ContinueWith ( ) is logical because it allows for easy task chaining ( would not be so elegant with events ) , and that it also allows Task < TResult > to inherit from Task ( because this way , Task < TResult > can provide appropriate overloads , which would not be possible for an event : if you have an event EventHandler Finished in Task , all you can do is create another event , say , event EventHandler < TaskResultEventArgs > Finished in Task < TResult > , which is not very nice ) , but I can not find the same explanation for CancellationToken.Register ( ) .So , what are the disadvantages of events in similar scenarios ? Should I also follow this pattern ? To clarify , which one of the below should I choose ? When should I prefer one against the other ? Thank you very much ! <code> public event EventHandler Finished ; // orpublic IDisposable OnFinished ( Action continuation ) | Subscriber method vs event |
C_sharp : Possible Duplicate : using statement with multiple variables I have several disposable object to manage . The CA2000 rule ask me to dispose all my object before exiting the scope . I do n't like to use the .Dispose ( ) method if I can use the using clause . In my specific method I should write many using in using : Is it possible to write this on another way like : <code> using ( Person person = new Person ( ) ) { using ( Adress address = new Address ( ) ) { // my code } } using ( Person person = new Person ( ) ; Adress address = new Address ( ) ) | How write several using instructions ? |
C_sharp : Apparently , Constrained Execution Region guarantees do not apply to iterators ( probably because of how they are implemented and all ) , but is this a bug or by design ? [ See the example below. ] i.e . What are the rules on CERs being used with iterators ? ( Code mostly stolen from here . ) <code> using System.Runtime.CompilerServices ; using System.Runtime.ConstrainedExecution ; class Program { static bool cerWorked ; static void Main ( string [ ] args ) { try { cerWorked = true ; foreach ( var v in Iterate ( ) ) { } } catch { System.Console.WriteLine ( cerWorked ) ; } System.Console.ReadKey ( ) ; } [ ReliabilityContract ( Consistency.WillNotCorruptState , Cer.Success ) ] unsafe static void StackOverflow ( ) { Big big ; big.Bytes [ int.MaxValue - 1 ] = 1 ; } static System.Collections.Generic.IEnumerable < int > Iterate ( ) { RuntimeHelpers.PrepareConstrainedRegions ( ) ; try { cerWorked = false ; yield return 5 ; } finally { StackOverflow ( ) ; } } unsafe struct Big { public fixed byte Bytes [ int.MaxValue ] ; } } | Do C # try-finally CERs break in iterators ? |
C_sharp : I 'm using Entity Framework 6.1 , and I have a code like this : And this generates : Find method returns a single result but it generates a TOP ( 2 ) query instead of 1 . Why ? Note : I 'm sure I 'm passing correct Id to the method , and yes , Id is the primary key . <code> Brand b ; using ( var ctx = new KokosEntities ( ) ) { try { b = ctx.Brands.Find ( _brands [ brandName ] .Id ) ; return b ; } catch ( Exception ex ) { _logger.Log ( LogLevel.Error , ex ) ; } } N'SELECT TOP ( 2 ) [ Extent1 ] . [ Id ] AS [ Id ] , [ Extent1 ] . [ Name ] AS [ Name ] , [ Extent1 ] . [ OpenCartId ] AS [ OpenCartId ] FROM [ dbo ] . [ Brands ] AS [ Extent1 ] WHERE [ Extent1 ] . [ Id ] = @ p0 ' , N ' @ p0 int ' | Why Find method generates a TOP ( 2 ) query ? |
C_sharp : I want a single Regex expression to match 2 groups of lowercase , uppercase , numbers or special characters . Length needs to also be grater than 7.I currently have this expressionIt , however , forces the string to have lowercase and uppercase and digit or special character.I currently have this implemented using 4 different regex expressions that I interrogate with some C # code.I plan to reuse the same expression in JavaScript.This is sample console app that shows the difference between 2 approaches . <code> ^ ( ? =.* [ ^a-zA-Z ] ) ( ? =.* [ a-z ] ) ( ? =.* [ A-Z ] ) . { 8 , } $ class Program { private static readonly Regex [ ] Regexs = new [ ] { new Regex ( `` [ a-z ] '' , RegexOptions.Compiled ) , //Lowercase Letter new Regex ( `` [ A-Z ] '' , RegexOptions.Compiled ) , // Uppercase Letter new Regex ( @ '' \d '' , RegexOptions.Compiled ) , // Numeric new Regex ( @ '' [ ^a-zA-Z\d\s : ] '' , RegexOptions.Compiled ) // Non AlphaNumeric } ; static void Main ( string [ ] args ) { Regex expression = new Regex ( @ '' ^ ( ? =.* [ ^a-zA-Z ] ) ( ? =.* [ a-z ] ) ( ? =.* [ A-Z ] ) . { 8 , } $ '' , RegexOptions.ECMAScript & RegexOptions.Compiled ) ; string [ ] testCases = new [ ] { `` P @ ssword '' , `` Password '' , `` P2ssword '' , `` xpo123 '' , `` xpo123 ! `` , `` xpo123 ! 123 @ @ '' , `` Myxpo123 ! 123 @ @ '' , `` Something_Really_Complex123 ! # 43 @ 2*333 '' } ; Console.WriteLine ( `` { 0 } \t { 1 } \t '' , `` Single '' , `` C # Hack '' ) ; Console.WriteLine ( `` '' ) ; foreach ( var testCase in testCases ) { Console.WriteLine ( `` { 0 } \t { 2 } \t : { 1 } '' , expression.IsMatch ( testCase ) , testCase , ( testCase.Length > = 8 & & Regexs.Count ( x = > x.IsMatch ( testCase ) ) > = 2 ) ) ; } Console.ReadKey ( ) ; } } Result Proper Test String -- -- -- - -- -- -- - -- -- -- -- -- -- True True : P @ sswordFalse True : PasswordTrue True : P2sswordFalse False : xpo123False False : xpo123 ! False True : xpo123 ! 123 @ @ True True : Myxpo123 ! 123 @ @ True True : Something_Really_Complex123 ! # 43 @ 2*333 | Regex match 2 out of 4 groups |
C_sharp : I have a class that initializes a collection to a default state . When I load the object from some saved JSON it appends the values rather than overwriting the collection . Is there a way to have the JSON.Net replace the collection when deserializing rather than append the values ? <code> void Main ( ) { string probMatrix = `` { \ '' Threshold\ '' :0.0276 , \ '' Matrix\ '' : [ [ -8.9,23.1,4.5 ] , [ 7.9,2.4,4.5 ] , [ 9.4,1.4,6.3 ] ] } '' ; var probabiltyMatrix = JsonConvert.DeserializeObject < ProbabiltyMatrix > ( probMatrix ) ; probabiltyMatrix.Dump ( ) ; } // Define other methods and classes herepublic class ProbabiltyMatrix { public ProbabiltyMatrix ( ) { // Initialize the probabilty matrix Matrix = new List < double [ ] > ( ) ; var matrixSize = 3 ; for ( var i = 0 ; i < matrixSize ; i++ ) { var probArray = new double [ matrixSize ] ; for ( var j = 0 ; j < matrixSize ; j++ ) { probArray [ j ] = 0.0 ; } Matrix.Add ( probArray ) ; } } public double Threshold ; public List < double [ ] > Matrix ; } | JSON.Net Collection initialized in default constructor not overwritten from deserialized JSON |
C_sharp : I am trying to use the new C # 7 pattern matching feature in this line of codeBut for some reason Resharper/Visual Studio 2017 is giving me a warning under is Customer with the following message The source expression is always of pattern 's type , matches on all non-null valuesBut customer can also be null right ? Can anyone please explain to me why it 's given this warning ? <code> if ( Customers.SingleOrDefault ( x = > x.Type == CustomerType.Company ) is Customer customer ) { ... } | Getting warning `` The source expression is always of pattern 's type , matches on all non-null values '' |
C_sharp : I 'm moving a object over a bunch of Buttons , and when this object is over a button I change the color of the border . This is no problem , I can do this through bindings , storyboards or style setters/Visual state . When I run this on my emulator it works nice and smooth , but when I run it on my windows phone , there is a small lag when the Border of the country changes . Is there a way to avoid this ? 1 . CODE Exampleand activationExtraOne difference which comes to mind between emulator and an actual device is the accuracy of the touch point . In the emulator you use a mouse which has much higher resolution . On a device where you 're using your finger the accuracy is much lower , i.e . millimeters vs pixels.I just tested this with a simple counter and a break point in the manipulation_completed_event . But the count is the same in both cases . And it only tried to run the storyboard once.Extra2To clarify the lag I see : I am dragging an element that follows the finger smoothly , when I cross into a new buttton , the element I am dragging stops a short while . The color of the button is changed and the element moves again.When I move back after the button has changed the color . The element moves smoothly with my finger when I move between the buttons.Therefore there is a lag when the storyboard is activated and it is seen in that the element I drag can not follow the finger.I am therefore trying to find alternativ ways to change the color that might have better performance , on the Phone . Beacuse it works fine on the emulator . I have tested on two different lumia 920s and one lumia 5202 . Code ExampleUsing Visual State Manager with help from Shawn Kendrot , from another question : Using Dependency object for color animation WP8 replicated below : Notice it has a MouseOver VisualState . Then assign the style and subscribe to the event handlersAnd in the event handler change the visual state.Still with lag , Anyone else have a solution that could be tested ? ExtraSince the issue might be low fps , i.e . a render problem when I want to change the color , could the dispatcher be used ? So in the first code example where I start a storyboard , I could instead call a function in the view to utilize the dispatcher ? Anyone has an idea for doing this and or if it is a good idea ? appreciating all the help , since I can not understand why I can move objects smooth around on the screen but when I want to change the color of the border I can see it lagging : / <code> < Button x : Name= '' Button1 '' BorderThickness= '' 0 '' BorderBrush= '' Transparent '' > < Button.Template > < ControlTemplate x : Name= '' Control '' > < Path x : Name= '' CountryUser '' Style= '' { StaticResource style_ColorButton } '' Data= '' { Binding UserView.buttonData } '' Fill= '' { StaticResource ButtonBackground } '' > < Path.Resources > < Storyboard x : Name= '' StoryBoard1 '' > < ColorAnimation Storyboard.TargetName= '' User '' Storyboard.TargetProperty= '' ( Stroke ) . ( SolidColorBrush.Color ) '' To= '' Blue '' Duration= '' 0 '' / > < /Storyboard > < /Path.Resources > < /Path > < /ControlTemplate > < /Button.Template > foreach ( UIElement x in ElementsAtPoint ) { f = x as FrameworkElement ; if ( f is Path ) { try { h = f as Path ; Storyboard sb = h.Resources [ `` StoryBoard1 '' ] as Storyboard ; sb.Begin ( ) ; } catch { } break ; } } < Style x : Key= '' ButtonStyle '' TargetType= '' Button '' > < Setter Property= '' Background '' Value= '' Transparent '' / > < Setter Property= '' BorderBrush '' Value= '' { StaticResource PhoneForegroundBrush } '' / > < Setter Property= '' Foreground '' Value= '' { StaticResource PhoneForegroundBrush } '' / > < Setter Property= '' BorderThickness '' Value= '' { StaticResource PhoneBorderThickness } '' / > < Setter Property= '' FontFamily '' Value= '' { StaticResource PhoneFontFamilySemiBold } '' / > < Setter Property= '' FontSize '' Value= '' { StaticResource PhoneFontSizeMedium } '' / > < Setter Property= '' Padding '' Value= '' 10,5,10,6 '' / > < Setter Property= '' Template '' > < Setter.Value > < ControlTemplate TargetType= '' Button '' > < Grid Background= '' Transparent '' > < VisualStateManager.VisualStateGroups > < VisualStateGroup x : Name= '' CommonStates '' > < VisualState x : Name= '' Normal '' / > < VisualState x : Name= '' MouseOver '' > < Storyboard > < ObjectAnimationUsingKeyFrames Storyboard.TargetProperty= '' Foreground '' Storyboard.TargetName= '' ContentContainer '' > < DiscreteObjectKeyFrame KeyTime= '' 0 '' Value= '' White '' / > < /ObjectAnimationUsingKeyFrames > < ObjectAnimationUsingKeyFrames Storyboard.TargetProperty= '' Background '' Storyboard.TargetName= '' ButtonBackground '' > < DiscreteObjectKeyFrame KeyTime= '' 0 '' Value= '' Orange '' / > < /ObjectAnimationUsingKeyFrames > < /Storyboard > < /VisualState > < VisualState x : Name= '' Pressed '' > < Storyboard > < ObjectAnimationUsingKeyFrames Storyboard.TargetProperty= '' Foreground '' Storyboard.TargetName= '' ContentContainer '' > < DiscreteObjectKeyFrame KeyTime= '' 0 '' Value= '' { StaticResource PhoneButtonBasePressedForegroundBrush } '' / > < /ObjectAnimationUsingKeyFrames > < ObjectAnimationUsingKeyFrames Storyboard.TargetProperty= '' Background '' Storyboard.TargetName= '' ButtonBackground '' > < DiscreteObjectKeyFrame KeyTime= '' 0 '' Value= '' { StaticResource PhoneAccentBrush } '' / > < /ObjectAnimationUsingKeyFrames > < /Storyboard > < /VisualState > < VisualState x : Name= '' Disabled '' > < Storyboard > < ObjectAnimationUsingKeyFrames Storyboard.TargetProperty= '' Foreground '' Storyboard.TargetName= '' ContentContainer '' > < DiscreteObjectKeyFrame KeyTime= '' 0 '' Value= '' { StaticResource PhoneDisabledBrush } '' / > < /ObjectAnimationUsingKeyFrames > < ObjectAnimationUsingKeyFrames Storyboard.TargetProperty= '' BorderBrush '' Storyboard.TargetName= '' ButtonBackground '' > < DiscreteObjectKeyFrame KeyTime= '' 0 '' Value= '' { StaticResource PhoneDisabledBrush } '' / > < /ObjectAnimationUsingKeyFrames > < ObjectAnimationUsingKeyFrames Storyboard.TargetProperty= '' Background '' Storyboard.TargetName= '' ButtonBackground '' > < DiscreteObjectKeyFrame KeyTime= '' 0 '' Value= '' Transparent '' / > < /ObjectAnimationUsingKeyFrames > < /Storyboard > < /VisualState > < /VisualStateGroup > < /VisualStateManager.VisualStateGroups > < Border x : Name= '' ButtonBackground '' BorderBrush= '' { TemplateBinding BorderBrush } '' BorderThickness= '' { TemplateBinding BorderThickness } '' Background= '' { TemplateBinding Background } '' CornerRadius= '' 0 '' Margin= '' { StaticResource PhoneTouchTargetOverhang } '' > < ContentControl x : Name= '' ContentContainer '' ContentTemplate= '' { TemplateBinding ContentTemplate } '' Content= '' { TemplateBinding Content } '' Foreground= '' { TemplateBinding Foreground } '' HorizontalContentAlignment= '' { TemplateBinding HorizontalContentAlignment } '' Padding= '' { TemplateBinding Padding } '' VerticalContentAlignment= '' { TemplateBinding VerticalContentAlignment } '' / > < /Border > < /Grid > < /ControlTemplate > < /Setter.Value > < /Setter > < /Style > < Button Content= '' Drag over me '' Style= '' { StaticResource ButtonStyle } '' MouseEnter= '' OnButtonMouseEnter '' MouseLeave= '' OnButtonMouseLeave '' / > private void OnButtonMouseEnter ( object sender , MouseEventArgs e ) { VisualStateManager.GoToState ( ( Control ) sender , `` MouseOver '' , true ) ; } private void OnButtonMouseLeave ( object sender , MouseEventArgs e ) { VisualStateManager.GoToState ( ( Control ) sender , `` Normal '' , true ) ; } | Lag when changing color of button border on WP8 |
C_sharp : I 'm currently looking at a copy-on-write set implementation and want to confirm it 's thread safe . I 'm fairly sure the only way it might not be is if the compiler is allowed to reorder statements within certain methods . For example , the Remove method looks like : Where hashSet is defined asSo my question is , given that hashSet is volatile does it mean that the Remove on the new set happens before the write to the member variable ? If not , then other threads may see the set before the remove has occurred.I have n't actually seen any issues with this in production , but I just want to confirm it is guaranteed to be safe.UPDATETo be more specific , there 's another method to get an IEnumerator : So the more specific question is : is there a guarantee that the returned IEnumerator will never throw a ConcurrentModificationException from a remove ? UPDATE 2Sorry , the answers are all addressing the thread safety from multiple writers . Good points are raised , but that 's not what I 'm trying to find out here . I 'd like to know if the compiler is allowed to re-order the operations in Remove to something like this : If this was possible , it would mean that a thread could call GetEnumerator after hashSet had been assigned , but before item was removed , which could lead to the collection being modified during enumeration.Joe Duffy has a blog article that states : Volatile on loads means ACQUIRE , no more , no less . ( There are additional compiler optimization restrictions , of course , like not allowing hoisting outside of loops , but let ’ s focus on the MM aspects for now . ) The standard definition of ACQUIRE is that subsequent memory operations may not move before the ACQUIRE instruction ; e.g . given { ld.acq X , ld Y } , the ld Y can not occur before ld.acq X . However , previous memory operations can certainly move after it ; e.g . given { ld X , ld.acq Y } , the ld.acq Y can indeed occur before the ld X . The only processor Microsoft .NET code currently runs on for which this actually occurs is IA64 , but this is a notable area where CLR ’ s MM is weaker than most machines . Next , all stores on .NET are RELEASE ( regardless of volatile , i.e . volatile is a no-op in terms of jitted code ) . The standard definition of RELEASE is that previous memory operations may not move after a RELEASE operation ; e.g . given { st X , st.rel Y } , the st.rel Y can not occur before st X . However , subsequent memory operations can indeed move before it ; e.g . given { st.rel X , ld Y } , the ld Y can move before st.rel X.The way I read this is that the call to newHashSet.Remove requires a ld newHashSet and the write to hashSet requires a st.rel newHashSet . From the above definition of RELEASE no loads can move after the store RELEASE , so the statements can not be reordered ! Could someone confirm please confirm my interpretation is correct ? <code> public bool Remove ( T item ) { var newHashSet = new HashSet < T > ( hashSet ) ; var removed = newHashSet.Remove ( item ) ; hashSet = newHashSet ; return removed ; } private volatile HashSet < T > hashSet ; public IEnumerator < T > GetEnumerator ( ) { return hashSet.GetEnumerator ( ) ; } var newHashSet = new HashSet < T > ( hashSet ) ; hashSet = newHashSet ; // swapped var removed = newHashSet.Remove ( item ) ; // swapped return removed ; | Reordering of operations around volatile |
C_sharp : This is a little spooky.I 'm thinking there must be a setting somewhere that explains why this is happening.In our solution there are about 50 different projects . For the most part , the libraries start with the namespace OurCompany.We have OurComany.This.That and OurCompany.Foo.Bar ... etc.There is a namespace/class clash between an external library with the namespaceAnd a class that is qualified like so..The error goes like this : Even Resharper gives me a `` Qualifier is redundant '' message when I fully qualify anything under the `` OurCompany '' namespace.. i.e.I can not figure out what on earth is doing this . The solution is pretty huge , so ripping things apart to try and reverse engineer the problem is not a great solution for me.I should state that if I use ... ... the Resharper message goes away . <code> OurCompany.Foo.Bar OurCompany.Some.Location.Foo Error 75 The type or namespace name 'MethodName ' does not exist in thenamespace 'OurCompany.Foo ' ( are you missing an assembly reference ? ) OurCompany.Some.Location.Foo.MethodName ( ) ; //OurCompany is redundant Some.Location.Foo.MethodName ( ) ; //Leaving out OurCompany | C # : Why is First namespace redundant ? |
C_sharp : I am trying to get logging up and running in my C # console app based on .NET Core 2.1.I added the following code to my DI declaration : I am trying to inject the service by using the Interface Microsoft.Extensions.Logging.ILogger in the constructor of the services , but I am getting the following error : Unhandled Exception : System.InvalidOperationException : Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger ' while attempting to activate 'MyService'.Did I misunderstand something here ? Should n't the AddLogging method be enough to expose the Service in the DI Container ? <code> var sc = new ServiceCollection ( ) ; sc.AddLogging ( builder = > { builder.AddFilter ( `` Microsoft '' , LogLevel.Warning ) ; builder.AddFilter ( `` System '' , LogLevel.Warning ) ; builder.AddFilter ( `` Program '' , LogLevel.Warning ) ; builder.AddConsole ( ) ; builder.AddEventLog ( ) ; } ) ; at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites ( Type serviceType , Type implementationType , CallSiteChain callSiteChain , ParameterInfo [ ] parameters , Boolean throwIfCallSiteNotFound ) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite ( ResultCache lifetime , Type serviceType , Type implementationType , CallSiteChain callSiteChain ) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact ( ServiceDescriptor descriptor , Type serviceType , CallSiteChain callSiteChain , Int32 slot ) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact ( Type serviceType , CallSiteChain callSiteChain ) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite ( Type serviceType , CallSiteChain callSiteChain ) at System.Collections.Concurrent.ConcurrentDictionary ` 2.GetOrAdd ( TKey key , Func ` 2 valueFactory ) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites ( Type serviceType , Type implementationType , CallSiteChain callSiteChain , ParameterInfo [ ] parameters , Boolean throwIfCallSiteNotFound ) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite ( ResultCache lifetime , Type serviceType , Type implementationType , CallSiteChain callSiteChain ) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact ( ServiceDescriptor descriptor , Type serviceType , CallSiteChain callSiteChain , Int32 slot ) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateEnumerable ( Type serviceType , CallSiteChain callSiteChain ) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite ( Type serviceType , CallSiteChain callSiteChain ) at System.Collections.Concurrent.ConcurrentDictionary ` 2.GetOrAdd ( TKey key , Func ` 2 valueFactory ) at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.CreateServiceAccessor ( Type serviceType ) at System.Collections.Concurrent.ConcurrentDictionary ` 2.GetOrAdd ( TKey key , Func ` 2 valueFactory ) at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService ( Type serviceType , ServiceProviderEngineScope serviceProviderEngineScope ) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService ( IServiceProvider provider , Type serviceType ) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService [ T ] ( IServiceProvider provider ) at Program.Main ( String [ ] args ) in Program.cs : line 27 | Why does .NET Core DI container not inject ILogger ? |
C_sharp : There are many different ways to create objects in Powershell . I am posting this as a challenge to create objects purely in Powerhell . I am looking for a way to create objects using Add-Type that pass these requirements : Strongly-Typed object propertiesInstantiated , using : New-Object , [ My.Object ] : :New ( ) , [ My.Object ] @ { 'Property'='Value ' } Part of a custom Namespace ( i.e [ My.Object ] ) Can be type-checked . Example : $ myVar -is [ My.Object ] I know dll 's can be created in Visual Studio that would accomplish this , but I am looking for a purely Powershell way to create objects.Here is the closest example I have that satisfy the rules above : With that said , are there other ( Possibly better ) ways to create objects that look , feel , and act like native Powershell objects ? Examples that do not satisfy all rulesWeakly-Typed object properties : Objects without namespaces : <code> PS C : \ > $ memberDef = @ '' public String myString { get ; set ; } public int myInt { get ; set ; } '' @ PS C : \ > Add-Type -Namespace `` My.Namespace '' -Name `` Object '' -MemberDefinition $ memberDefPS C : \ > $ myObj = [ My.Namespace.Object ] @ { 'myString'='Foo ' ; 'myInt'=42 } PS C : \ > $ myObjmyString myInt -- -- -- -- -- -- -Foo 42 PS C : \ > $ myObj = `` '' | Select-Object -Property myString , myIntPS C : \ > $ myObj = New-Object -TypeName PSObject -Property @ { 'myString'='foo ' ; 'myInt'=42 } PS C : \ > $ myObj = @ { } ; $ myObj.myString = 'foo ' ; $ myObj.myInt = 42PS C : \ > $ myObj.myInt = `` This should result in an error . '' PS C : \ > $ typeDef = @ '' public class myObject { public string myString { get ; set ; } public int myInt { get ; set ; } } '' @ PS C : \ > Add-Type -TypeDefinition $ typeDefPS C : \ > $ myObj = [ myObject ] : :new ( ) PS C : \ > $ myObj = New-Object -TypeName PSObject -Property @ { 'myString'='foo ' ; 'myInt'=42 } PS C : \ > $ myObj.PSObject.TypeNames.Insert ( 0 , `` myObject '' ) | Defining Custom Powershell Objects |
C_sharp : After reading `` Odd query expressions '' by Jon Skeet , I tried the code below.I expected the LINQ query at the end to translate to int query = proxy.Where ( x = > x ) .Select ( x = > x ) ; which does not compile because Where returns an int . The code compiled and prints `` Where ( x = > x ) '' to the screen and query is set to 2 . Select is never called , but it needs to be there for the code to compile . What is happening ? <code> using System ; using System.Linq.Expressions ; public class LinqProxy { public Func < Expression < Func < string , string > > , int > Select { get ; set ; } public Func < Expression < Func < string , string > > , int > Where { get ; set ; } } class Test { static void Main ( ) { LinqProxy proxy = new LinqProxy ( ) ; proxy.Select = exp = > { Console.WriteLine ( `` Select ( { 0 } ) '' , exp ) ; return 1 ; } ; proxy.Where = exp = > { Console.WriteLine ( `` Where ( { 0 } ) '' , exp ) ; return 2 ; } ; int query = from x in proxy where x select x ; } } | Why does this LINQ query compile ? |
C_sharp : I 've been scratching my head for a while with this . On my MainWindow I have an an Image who 's ToolTip should pop up the image at it 's actual size ( or with a height no larger than the MainWindow itself ) : ( MainWindow 's x : name is 'MW ' ) In another class elsewhere I am loading a BitmapImage into this image control : And the GetBitMapImageFromDisk method : The image ToolTip pops up on mouse over but the problem is that the size of the image appears to be dependent on the DPI of the image itself . So if for some reason it targets an image who 's DPI is say '762 ' the ToolTip image is really tiny when it is displayed.Can anyone suggest a way of mitigating this with my current code ? The images that are loaded at runtime can be pretty much any size , DPI and aspect ratio . <code> < Image x : Name= '' ss1 '' Grid.Column= '' 0 '' Grid.Row= '' 0 '' Margin= '' 0 '' > < Image.ToolTip > < ToolTip DataContext= '' { Binding PlacementTarget , RelativeSource= { RelativeSource Self } } '' > < Border BorderBrush= '' Black '' BorderThickness= '' 1 '' Margin= '' 5,7,5,5 '' > < Image Source= '' { Binding Source } '' MaxHeight= '' { Binding ElementName=MW , Path=Height } '' Stretch= '' Uniform '' ToolTipService.Placement= '' Top '' / > < /Border > < /ToolTip > < /Image.ToolTip > < /Image > Image img = ( Image ) mw.FindName ( `` ss1 '' ) ; img.Source = GetBitmapImageFromDisk ( path , UriKind.Absolute ) ; public static BitmapImage GetBitmapImageFromDisk ( string path , UriKind urikind ) { if ( ! File.Exists ( path ) ) return null ; try { BitmapImage b = new BitmapImage ( new Uri ( path , urikind ) ) ; return b ; } catch ( System.NotSupportedException ex ) { BitmapImage c = new BitmapImage ( ) ; return c ; } } | WPF Image as ToolTip - DPI issue |
C_sharp : I have a string that has special characters like this example : 12345678912\rJ\u0011 because I need to have access to this special chars to configure my application . I want to display this string exactly like this in a TextBox field so everything I have tried so far results in a string where the character \u0011 tries to render with an empty character at the end : `` 7896104866061\rJ '' .I made this but it does n't work.What need I do ? Thanks in advance . <code> string result = Regex.Replace ( ToLiteral ( this.Buffer ) , `` [ ^\x00-\x7Fd ] '' , c = > string.Format ( `` \\u { 0 : x4 } '' , ( int ) c.Value [ 0 ] ) ) .Replace ( @ '' \ '' , @ '' \\ '' ) ; public static string ToLiteral ( string input ) { using ( var writer = new StringWriter ( ) ) { using ( var provider = CodeDomProvider.CreateProvider ( `` CSharp '' ) ) { provider.GenerateCodeFromExpression ( new CodePrimitiveExpression ( input ) , writer , null ) ; return writer.ToString ( ) ; } } } | Render special character C # |
C_sharp : Case 1 : can be simplified asCase 2 : can not be simplified asQuestion : For the second case , why can not we just use [ ] [ ] instead of int [ ] [ ] ? <code> int [ ] data1 = new int [ ] { 1 , 2 , 3 } ; int [ ] data2 = new [ ] { 1 , 2 , 3 } ; int [ ] [ ] table1 = new int [ ] [ ] { new int [ ] { } , new int [ ] { 1 , 2 } } ; int [ ] [ ] table2 = new [ ] [ ] { new int [ ] { } , new int [ ] { 1 , 2 } } ; | Why can not we just use [ ] [ ] instead of int [ ] [ ] ? |
C_sharp : I have an issue with a navigation property in an entity framework project . Here is the class MobileUser : The relevant part is this navigation property : This is the class MobileDeviceInfo : As you can see , it implements IEquatable < MobileDeviceInfo > and overrides also Equals and GetHashCode from System.Object.I have following test , i 've expected that Contains would call my Equals but it does not . It seems to use Object.ReferenceEquals instead , so wo n't find my device because it 's a different reference : The second approach with LINQ 's Enumerable.Any returns the expected true.If i do n't use user.DeviceInfos.Contains ( device ) but user.DeviceInfos.ToList ( ) .Contains ( device ) it also works as expected since List < > .Contains uses my Equals.The actual type of the ICollection < > seems to be a System.Collections.Generic.HashSet < MobileDeviceInfo > but if i use following code that uses also a HashSet < > it again works as expected : So why are only references compared and my custom Equals is ignored ? Update : even more confusing is the result is false even if i cast it to the HashSet < MobileDeviceInfo > : Update 2 : : the reason for this really seems to be that both HashSets use different comparers . The entity-framework-HashSet uses a : and the standard HashSet < > uses a : That explains the issue , although i do n't understand why entity framework uses an implementation that ignores custom Equals implementations under certain circumstances . That 's a nasty trap , is n't it ? Conclusion : never use Contains if you do n't know what comparer will be used or use Enumerable.Contains with the overload that takes a custom comparer : <code> [ DataContract ] [ Table ( `` MobileUser '' ) ] public class MobileUser : IEquatable < MobileUser > { // constructors omitted ... . /// < summary > /// The primary-key of MobileUser . /// This is not the VwdId which is stored in a separate column /// < /summary > [ DataMember , Key , Required , DatabaseGenerated ( DatabaseGeneratedOption.Identity ) ] public int UserId { get ; set ; } [ DataMember , Required , Index ( IsUnique = true ) , MinLength ( VwdIdMinLength ) , MaxLength ( VwdIdMaxLength ) ] public string VwdId { get ; set ; } // other properties omitted ... [ DataMember ] public virtual ICollection < MobileDeviceInfo > DeviceInfos { get ; private set ; } public bool Equals ( MobileUser other ) { return this.UserId == other ? .UserId || this.VwdId == other ? .VwdId ; } public override bool Equals ( object obj ) { if ( object.ReferenceEquals ( this , obj ) ) return true ; MobileUser other = obj as MobileUser ; if ( other == null ) return false ; return this.Equals ( other ) ; } public override int GetHashCode ( ) { // ReSharper disable once NonReadonlyMemberInGetHashCode return VwdId.GetHashCode ( ) ; } public override string ToString ( ) { return `` foo '' ; // omitted actual implementation } # region constants // irrelevant # endregion } public virtual ICollection < MobileDeviceInfo > DeviceInfos { get ; private set ; } [ DataContract ] [ Table ( `` MobileDeviceInfo '' ) ] public class MobileDeviceInfo : IEquatable < MobileDeviceInfo > { [ DataContract ] public enum MobilePlatform { [ EnumMember ] // ReSharper disable once InconsistentNaming because correct spelling is iOS iOS = 1 , [ EnumMember ] Android = 2 , [ EnumMember ] WindowsPhone = 3 , [ EnumMember ] Blackberry = 4 } // constructors omitted ... [ DataMember , Key , DatabaseGenerated ( DatabaseGeneratedOption.Identity ) ] public int DeviceInfoId { get ; private set ; } [ DataMember , Required , Index ( IsUnique = true ) , MinLength ( DeviceTokenMinLength ) , MaxLength ( DeviceTokenMaxLength ) ] public string DeviceToken { get ; set ; } [ DataMember , Required , MinLength ( DeviceNameMinLength ) , MaxLength ( DeviceNameMaxLength ) ] public string DeviceName { get ; set ; } [ DataMember , Required ] public MobilePlatform Platform { get ; set ; } // other properties ... [ DataMember ] public virtual MobileUser MobileUser { get ; private set ; } /// < summary > /// The foreign-key to the MobileUser . /// This is not the VwdId which is stored in MobileUser /// < /summary > [ DataMember , ForeignKey ( `` MobileUser '' ) ] public int UserId { get ; set ; } public bool Equals ( MobileDeviceInfo other ) { if ( other == null ) return false ; return DeviceToken == other.DeviceToken ; } public override string ToString ( ) { return `` Bah '' ; // implementation omitted public override bool Equals ( object obj ) { if ( ReferenceEquals ( this , obj ) ) return true ; MobileDeviceInfo other = obj as MobileDeviceInfo ; if ( other == null ) return false ; return Equals ( other ) ; } public override int GetHashCode ( ) { // ReSharper disable once NonReadonlyMemberInGetHashCode return DeviceToken.GetHashCode ( ) ; } # region constants // irrelevant # endregion } var userRepo = new MobileUserRepository ( ( ILog ) null ) ; var deviceRepo = new MobileDeviceRepository ( ( ILog ) null ) ; IReadOnlyList < MobileUser > allUser = userRepo.GetAllMobileUsersWithDevices ( ) ; MobileUser user = allUser.First ( ) ; IReadOnlyList < MobileDeviceInfo > allDevices = deviceRepo.GetMobileDeviceInfos ( user.VwdId , true ) ; MobileDeviceInfo device = allDevices.First ( ) ; bool contains = user.DeviceInfos.Contains ( device ) ; bool anyEqual = user.DeviceInfos.Any ( x = > x.DeviceToken == device.DeviceToken ) ; Assert.IsTrue ( contains ) ; // no , it 's false bool contains = new HashSet < MobileDeviceInfo > ( user.DeviceInfos ) .Contains ( device ) ; // true // still falsebool contains2 = ( ( HashSet < MobileDeviceInfo > ) user.DeviceInfos ) .Contains ( device ) ; // but this is true as already mentionedbool contains3 = new HashSet < MobileDeviceInfo > ( user.DeviceInfos ) .Contains ( device ) ; System.Data.Entity.Infrastructure.ObjectReferenceEqualityComparer GenericEqualityComparer < T > bool contains = user.DeviceInfos.Contains ( device , EqualityComparer < MobileDeviceInfo > .Default ) ; // true | Why ICollection < > .Contains ignores my overridden Equals and the IEquatable < > interface ? |
C_sharp : I am currently trying to run some code when the debugger detaches from a process . It is easy to find out if a debugger is attached : My question is if there is a way ( preferable one that works for .NET , Windows Phone , WinRT ) to get an event when the debugger gets detached ( mostly when the application is killed ) .Worst case I can find the debugger Process in .NET and subscribe to the Exit event , but that wo n't work in Windows Phone and WinRT . <code> System.Diagnostics.Debugger.IsAttached ; | Running code when C # debugger detaches from process |
C_sharp : DTC is disabled on my machine . It is my understanding that this code should fail , because it uses two data contexts in the same transaction . So , why does it work ? ( Note : I tried this using .NET 3.5 and .NET 4.0 . ) Here are the DAL methods that get called : <code> using ( TransactionScope transactionScope = new TransactionScope ( ) ) { UpdateEta ( ) ; UpdateBin ( ) ; transactionScope.Complete ( ) ; } public static void UpdateBin ( Bin updatedBin ) { using ( DevProdDataDataContext dataContext = new DevProdDataDataContext ( ConnectionString ) ) { BinRecord binRecord = ( from bin in dataContext.BinRecords where bin.BinID == updatedBin.BinId select bin ) .FirstOrDefault ( ) ; binRecord.BinID = updatedBin.BinId ; binRecord.BinName = updatedBin.BinName ; dataContext.SubmitChanges ( ) ; } } public static void UpdateEta ( Eta updatedEta ) { using ( DevProdDataDataContext dataContext = new DevProdDataDataContext ( ConnectionString ) ) { EtaRecord etaRecord = ( from eta in dataContext.EtaRecords where eta.ID == updatedEta.ID select eta ) .FirstOrDefault ( ) ; etaRecord.ID = updatedEta.ID ; etaRecord.Title = updatedEta.Title ; dataContext.SubmitChanges ( ) ; } } | Why is n't my transaction escalating to DTC ? |
C_sharp : I 'm creating a Code Fix which turns the access modifier of detected methods public . The implementation is straightforward : remove all existing access modifiers and add public at the front . Afterwards I replace the node and return the solution . This however results in a modifier list that looks like this : publicvirtual void Method ( ) . On top of the modifiers being pasted against eachother , that line of code is wrongly indented . It looks like this : So as a solution I format the code instead . Using I can format the modifiers but they are still wrongly indented : I assume this is because of trivia but prepending the formatted method with the original method 's leading trivia does not make a difference . I want to avoid formatting the entire document because , well , this is n't an action to format the entire document.The entire relevant implementation of this Code Fix : <code> [ TestClass ] public class MyClass { [ TestMethod ] publicvirtual void Method ( ) { } } var formattedMethod = Formatter.Format ( newMethod , newMethod.Modifiers.Span , document.Project.Solution.Workspace , document.Project.Solution.Workspace.Options ) ; [ TestClass ] public class MyClass { [ TestMethod ] public virtual void Method ( ) { } } private Task < Solution > MakePublicAsync ( Document document , SyntaxNode root , MethodDeclarationSyntax method ) { var removableModifiers = new [ ] { SyntaxFactory.Token ( SyntaxKind.InternalKeyword ) , SyntaxFactory.Token ( SyntaxKind.ProtectedKeyword ) , SyntaxFactory.Token ( SyntaxKind.PrivateKeyword ) } ; var modifierList = new SyntaxTokenList ( ) .Add ( SyntaxFactory.Token ( SyntaxKind.PublicKeyword ) ) .AddRange ( method.Modifiers.Where ( x = > ! removableModifiers.Select ( y = > y.RawKind ) .Contains ( x.RawKind ) ) ) ; var newMethod = method.WithModifiers ( modifierList ) ; var formattedMethod = Formatter.Format ( newMethod , newMethod.Modifiers.Span , document.Project.Solution.Workspace , document.Project.Solution.Workspace.Options ) ; var newRoot = root.ReplaceNode ( method , formattedMethod.WithLeadingTrivia ( method.GetLeadingTrivia ( ) ) ) ; var newDocument = document.WithSyntaxRoot ( newRoot ) ; return Task.FromResult ( newDocument.Project.Solution ) ; } | Formatting a method signature loses indentation |
C_sharp : Well I am not sure if this questions asked before but I have no idea how the search for it . Well this is not an Entity Framework specified question but I am gon na give example using it.So in EF we need to use .Include ( `` Related Object '' ) to include related data . However what I want to is that write a method that takes a List of strings and returns the entity or entity list with the related objects.In exampleObviously above example wo n't work since I already called out the Entites when I declared the list . But I think it demonstrates the point . <code> public List < Entity > GetAll ( List < string > includes > ) { List < Entity > entites = context.Entites ; foreach ( string s in includes ) { entites.Include ( s ) ; } return entites ; } | How to dynamically generate Includes in entity framework |
C_sharp : I 've got the following class : I 've searched for a while and it appears that an argument passed with the ref keyword ca n't be stored . Trying to add the source argument to a list or to assign it to a field variable does n't allow it to keep a reference to the actual delegate 's original reference ; so my questions are : Is there a way to unsubscribe from all the sources without passing their references again ? If not , how can the class be changed in order to support it , but still maintain the subscription by passing a delegate through a method ? Is it possible to achieve it without using Reflection ? Is it possible to achieve it without wrapping the delegate/event in a class and then passing the class as a parameter for the subscription ? Thank you.EDIT : It appears that without using a Wrapper or Reflection , there 's no solution to the given problem . My intention was to make the class as much portable as possible , without having to wrap delegates in helper classes . Thanks everyone for the contributions . <code> public class Terminal : IDisposable { readonly List < IListener > _listeners ; public Terminal ( IEnumerable < IListener > listeners ) { _listeners = new List < IListener > ( listeners ) ; } public void Subscribe ( ref Action < string > source ) { source += Broadcast ; //Store the reference somehow ? } void Broadcast ( string message ) { foreach ( var listener in _listeners ) listener.Listen ( message ) ; } public void Dispose ( ) { //Unsubscribe from all the stored sources ? } } | Unsubscribe from delegate passed through ref keyword to the subscription method ? |
C_sharp : so in my program I have parts where I use try catch blocks like thisOf course I probably could do checks to see if the string is valid path ( regex ) , then I would check if directory exists , then I could catch various exceptions to see why my routine failed and give more info ... But in my program it 's not really necessary . Now I just really need to know if this is acceptable , and what would a pro say/think about that . Thanks a lot for attention . <code> try { DirectoryInfo dirInfo = new DirectoryInfo ( someString ) ; //I do n't know if that directory exists //I do n't know if that string is valid path string ... it could be anything //Some operations here } catch ( Exception iDontCareWhyItFailed ) { //Did n't work ? great ... we will say : somethings wrong , try again/next one } | Is it bad programming style to have a single , maybe common , generic exception ? |
C_sharp : I want to convert a binary file to a string which could be then converted back to the binary file.I tried this : but it 's too slow , it takes about 20 seconds to convert 5KB on i5 CPU.I noticed that notepad does the same in much less time.Any ideas on how to do it ? Thanks <code> byte [ ] byteArray = File.ReadAllBytes ( @ '' D : \pic.png '' ) ; for ( int i = 0 ; i < byteArray.Length ; i++ ) { textBox1.Text += ( char ) byteArray [ i ] ; } | converting bytes to a string C # |
C_sharp : I have the problem where I need to do dynamic dispatch based on an object type . The types based on which I need to dispatch are known at compile time - in my example they are 17.My initial guess was to use a Dictionary < Type , Action < Object > > for the dispatching and to use obj.GetType ( ) to find out the appropriate action . But then I decided to use BenchmarkDotNet to see if I can do better and exactly how expensive the dispatch lookup would be . Bellow is the code I used for the benchmark.In my example I ran the test with a boxed Guid which is the worst case in the handcrafted Switch function . The results were surprising to say the least : The switch function 2 times faster for it 's worst case . If I reorder the ifs so most common types are first then on average I expect it to run 3-5 times faster.My question is how come 18 checks are so much faster than a single dictionary lookup ? Am I missing something obvious ? EDIT : The original test was x86 ( Prefer 32bit ) mode on x64 machine . I ran the tests in 64 release build as well : <code> public class Program { private static readonly Object Value = Guid.NewGuid ( ) ; private static readonly Dictionary < Type , Action < Object > > Dictionary = new Dictionary < Type , Action < Object > > ( ) { [ typeof ( Byte ) ] = x = > Empty ( ( Byte ) x ) , [ typeof ( Byte [ ] ) ] = x = > Empty ( ( Byte [ ] ) x ) , [ typeof ( SByte ) ] = x = > Empty ( ( SByte ) x ) , [ typeof ( Int16 ) ] = x = > Empty ( ( Int16 ) x ) , [ typeof ( UInt16 ) ] = x = > Empty ( ( UInt16 ) x ) , [ typeof ( Int32 ) ] = x = > Empty ( ( Int32 ) x ) , [ typeof ( UInt32 ) ] = x = > Empty ( ( UInt32 ) x ) , [ typeof ( Int64 ) ] = x = > Empty ( ( Int64 ) x ) , [ typeof ( UInt64 ) ] = x = > Empty ( ( UInt64 ) x ) , [ typeof ( Decimal ) ] = x = > Empty ( ( Decimal ) x ) , [ typeof ( Single ) ] = x = > Empty ( ( Single ) x ) , [ typeof ( Double ) ] = x = > Empty ( ( Double ) x ) , [ typeof ( String ) ] = x = > Empty ( ( String ) x ) , [ typeof ( DateTime ) ] = x = > Empty ( ( DateTime ) x ) , [ typeof ( TimeSpan ) ] = x = > Empty ( ( TimeSpan ) x ) , [ typeof ( Guid ) ] = x = > Empty ( ( Guid ) x ) , [ typeof ( Char ) ] = x = > Empty ( ( Char ) x ) , } ; [ Benchmark ] public void Switch ( ) = > Switch ( Value ) ; [ Benchmark ] public void Lookup ( ) = > Lookup ( Value ) ; private static void Switch ( Object value ) { if ( value is Byte ) goto L_Byte ; if ( value is SByte ) goto L_SByte ; if ( value is Int16 ) goto L_Int16 ; if ( value is UInt16 ) goto L_UInt16 ; if ( value is Int32 ) goto L_Int32 ; if ( value is UInt32 ) goto L_UInt32 ; if ( value is Int64 ) goto L_Int64 ; if ( value is UInt64 ) goto L_UInt64 ; if ( value is Decimal ) goto L_Decimal ; if ( value is Single ) goto L_Single ; if ( value is Double ) goto L_Double ; if ( value is DateTime ) goto L_DateTime ; if ( value is TimeSpan ) goto L_TimeSpan ; if ( value is DateTimeOffset ) goto L_DateTimeOffset ; if ( value is String ) goto L_String ; if ( value is Byte [ ] ) goto L_ByteArray ; if ( value is Char ) goto L_Char ; if ( value is Guid ) goto L_Guid ; return ; L_Byte : Empty ( ( Byte ) value ) ; return ; L_SByte : Empty ( ( SByte ) value ) ; return ; L_Int16 : Empty ( ( Int16 ) value ) ; return ; L_UInt16 : Empty ( ( UInt16 ) value ) ; return ; L_Int32 : Empty ( ( Int32 ) value ) ; return ; L_UInt32 : Empty ( ( UInt32 ) value ) ; return ; L_Int64 : Empty ( ( Int64 ) value ) ; return ; L_UInt64 : Empty ( ( UInt64 ) value ) ; return ; L_Decimal : Empty ( ( Decimal ) value ) ; return ; L_Single : Empty ( ( Single ) value ) ; return ; L_Double : Empty ( ( Double ) value ) ; return ; L_DateTime : Empty ( ( DateTime ) value ) ; return ; L_DateTimeOffset : Empty ( ( DateTimeOffset ) value ) ; return ; L_TimeSpan : Empty ( ( TimeSpan ) value ) ; return ; L_String : Empty ( ( String ) value ) ; return ; L_ByteArray : Empty ( ( Byte [ ] ) value ) ; return ; L_Char : Empty ( ( Char ) value ) ; return ; L_Guid : Empty ( ( Guid ) value ) ; return ; } private static void Lookup ( Object value ) { if ( Dictionary.TryGetValue ( value.GetType ( ) , out var action ) ) { action ( value ) ; } } [ MethodImpl ( MethodImplOptions.NoInlining ) ] private static void Empty < T > ( T value ) { } static void Main ( string [ ] args ) { BenchmarkRunner.Run ( typeof ( Program ) ) ; Console.ReadLine ( ) ; } } BenchmarkDotNet=v0.10.11 , OS=Windows 10 Redstone 3 [ 1709 , Fall Creators Update ] ( 10.0.16299.125 ) Processor=Intel Core i7-4790K CPU 4.00GHz ( Haswell ) , ProcessorCount=8 Frequency=3903988 Hz , Resolution=256.1483 ns , Timer=TSC [ Host ] : .NET Framework 4.7 ( CLR 4.0.30319.42000 ) , 32bit LegacyJIT-v4.7.2600.0 DefaultJob : .NET Framework 4.7 ( CLR 4.0.30319.42000 ) , 32bit LegacyJIT-v4.7.2600.0 Method | Mean | Error | StdDev | -- -- -- - | -- -- -- -- - : | -- -- -- -- -- : | -- -- -- -- -- : | Switch | 13.21 ns | 0.1057 ns | 0.0989 ns | Lookup | 28.22 ns | 0.1082 ns | 0.1012 ns | Method | Mean | Error | StdDev | -- -- -- -- -- | -- -- -- -- -- : | -- -- -- -- -- : | -- -- -- -- -- : | Switch | 12.451 ns | 0.0600 ns | 0.0561 ns | Lookup | 22.552 ns | 0.1108 ns | 0.1037 ns | | Unexpected performance results when comparing dictionary lookup vs multiple is operators in .NET 4.7 |
C_sharp : I 'm trying to ditch Windows Forms , and learn to use WPF professionally from now on . Pictured above is a form done in Windows Forms that I 'd like to recreate in WPF.Here is the XAML I have so far : Is this even the right approach , I mean using a Rectangle . In my Windows Forms example , I used a Panel and gave it a .BackColor property.What 's the WPF way to achieve this ? Thank you . <code> < Window x : Class= '' PizzaSoftware.UI.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' Title= '' MainWindow '' Height= '' 297 '' Width= '' 466 '' > < Grid ShowGridLines= '' True '' > < Grid.ColumnDefinitions > < ColumnDefinition Width= '' .20* '' / > < ColumnDefinition / > < ColumnDefinition Width= '' .20* '' / > < /Grid.ColumnDefinitions > < Rectangle Grid.Column= '' 0 '' > < Backcolor ? < /Rectangle > < /Grid > < /Window > | New to WPF , how would I create these colored bars in my form ? |
C_sharp : I want to test for object references held improperly and wrote a test that always failed . I simplified the test to the following behaviour : This test however , which does the same without using , passes : The used stub class is simple enough : Can someone please explain me that behaviour or - even better - has an idea how to make sure that the object gets garbage collected ? PS : Bear with me if a similar question was asked before . I only examined those questions that have using in the title . <code> [ Test ] public void ScopesAreNotLeaking ( ) { WeakReference weakRef ; Stub scope = null ; using ( scope = new Stub ( ) ) { weakRef = new WeakReference ( scope ) ; } scope = null ; GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ; Assert.That ( weakRef.Target , Is.Null ) ; } [ Test ] public void ScopesAreNotLeaking ( ) { WeakReference weakRef ; Stub scope = new Stub ( ) ; weakRef = new WeakReference ( scope ) ; scope = null ; GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ; Assert.That ( weakRef.Target , Is.Null ) ; } class Stub : IDisposable { public void Dispose ( ) { } } | Garbage collector wo n't collect an object created with using |
C_sharp : I 've recently been developing an RTF Editor which is only a simple UserControl that has a RichTextBox with a couple Events like PreviewTextInput and PreviewMouseUp.I noticed something slightly annoying though.The Performance of the RichTextBox is absolutely terrible whenever the UI is being resized and the RichTextBox has a lot of Text to cause its Wrapping Algorithm to fire.This gives the Application a really sloppy feel , as if it is poorly optimized ( even though it is n't ) .At first I noticed this performance hit while selecting Text , so instead of using the SelectionChanged event , I decided to use the PreviewMouseUp event and then fetch the Selection.Then after further testing I found out that the resize also caused huge loads.And I 'm talking about loads ranging between 5 % - > 30 % with a Quad-Core CPU running at 3.8GHz ! To further test it out , I decided to comment out my RichTextBox and only include a new RichTextBox with no defined PropertyInserting this into a Window , filling with Text , and then resizing the Window to cause the Wrapping Algorithm did the same again , up to 30 % usage ! I tried to research about this matter , and most people ended up recommending setting the PageWidth to high values in order to prevent Wrapping : Which I do not want , since the previous Version of the Editor I wrote was made with WinForms and could do Wrapping effortlessly , and I also want it in the new WPF Version.Did anyone else ever face this issue ? If yes , could you please point me into the right direction to remove this huge strain on the hardware ? I 'm a bit sad because I love WPF , but I did find one or the other Object that is really unoptimized and/or not practical in comparison to the WinForms counterpart , the RichTextBox seems to be another one of those cases : ( Sorry for the huge amount of Text , but I really wanted to Document this neatly in case some other poor soul faces this issue and for you guys to see what I 've tried so far . <code> < RichTextBox/ > richTextBox1.HorizontalScrollBarVisibility = ScrollBarVisibility.Visible ; richTextBox1.Document.PageWidth = 1000 ; | RichTextBox - UI Resize causes huge CPU Load |
C_sharp : In PersonBusiness.GetQuery method , the PersonEntity is peppered all over code and there are a lot of other entity types that will implement this method similarly.I want to use generic parameters in PersonBusiness to lessen usage of specific entity type because there will be implementations like this one with other entities and i want to prevent some other type used instead of the intended entity type . But could not be successful or satisfied by generic parameter used versions.I also want to use interfaces instead of concrete classes if it is more meaningful . <code> public class Entities : DbContext { public virtual DbSet < PersonEntity > PersonSet { get ; set ; } } public class PersonEntity { public int Id { get ; set ; } public string FullName { get ; set ; } } public class BaseBusiness { public Entities Db = > new Entities ( ) ; } public abstract class BaseBusiness < T > : BaseBusiness where T : class { public IQueryable < T > GetQuery < TKey > ( Expression < Func < T , bool > > where , Expression < Func < T , TKey > > orderBy ) { IQueryable < T > query = Db.Set < T > ( ) ; if ( where ! = null ) query = query.Where ( where ) ; if ( orderBy ! = null ) query = query.OrderBy ( orderBy ) ; return query ; } public abstract IQueryable < T > ApplyDefaultOrderyBy ( IQueryable < T > query ) ; public IQueryable < T > GetQuery ( IQueryable < T > query , string orderBy , Func < IQueryable < T > , IQueryable < T > > defaultOrderBy = null ) { if ( orderBy ! = null ) query = query.OrderBy ( orderBy ) ; else query = defaultOrderBy ! = null ? defaultOrderBy ( query ) : ApplyDefaultOrderyBy ( query ) ; return query ; } } public class PersonBusiness : BaseBusiness < PersonEntity > { public IQueryable < PersonEntity > GetQuery ( string orderBy , int ? groupId ) { IQueryable < PersonEntity > query = Db.PersonSet ; Func < IQueryable < PersonEntity > , IQueryable < PersonEntity > > defaultOrderBy = null ; if ( groupId.HasValue ) { query = query.Where ( d = > d.Id == groupId ) ; } else { defaultOrderBy = q = > q.OrderBy ( d = > d.Id ) .ThenBy ( d = > d.FullName ) ; } return GetQuery ( query , orderBy , defaultOrderBy ) ; } public override IQueryable < PersonEntity > ApplyDefaultOrderyBy ( IQueryable < PersonEntity > query ) { return query.OrderBy ( q = > q.FullName ) ; } } | Using generics with entities |
C_sharp : I 'm just wondering why I get this output : OUTPUTc But in MonoOUTPUTfSo why is the output c ? not d ? How does the compiler choose c ? If I change the code like this : OUTPUTc again ! Another example : OUTPUTc <code> enum MyEnum { a=1 , b=2 , c=3 , d=3 , f=d } Console.WriteLine ( MyEnum.f.ToString ( ) ) ; enum MyEnum { a=1 , b=2 , c=3 , d=3 , k=3 } Console.WriteLine ( MyEnum.k.ToString ( ) ) ; enum MyEnum { a=3 , b=3 , c=3 , d=3 , f=d , } MessageBox.Show ( MyEnum.f.ToString ( ) ) ; | Values of Enum types |
C_sharp : Having this extension wanted it to accept IEnumerable and casting to array if needed inside the extension , but I do n't know how to use the params keyword for that.Tryed : but this generates a compile-time error : The parameter array must be a single dimensional arrayIs there any way to make the extension method support IEnumerable params ? if not , why not ? <code> public static bool In < T > ( this T t , params T [ ] values ) { return values.Contains ( t ) ; } public static bool In < T > ( this T t , params IEnumerable < T > values ) { return values.Contains ( t ) ; } | C # How can I make an extension accept IEnumerable instead of array for params |
C_sharp : I 'm dealing with a code base that makes generous use of Generics with class types . I 've been pushing to use interfaces ( for a variety of reasons ) . In my work of slowly converting things , I 've hit the following and I ca n't get past it.Put simply ( and minimally ) , the problem I 'm facing is the following : As it says in the comment , it produces a compile time error.How can I produce an object that adheres to the interface that can be returned ? In general , how can I convert or cast the `` inner '' type ? Update : My example may be misleading . My situation is not specific to a List that contains Dictionary elements . There are instances of that but it could also just as well be IList < IVehicle > vehicleList = new List < Car > ( ) ; The crux of my question is how to deal with mis-matched Generic Types . <code> private static IList < IDictionary < int , string > > exampleFunc ( ) { //The following produces a compile error of : // Can not implicitly convert type 'System.Collections.Generic.List < System.Collections.Generic.Dictionary < int , string > > ' to // 'System.Collections.Generic.IList < System.Collections.Generic.IDictionary < int , string > > ' . // An explicit conversion exists ( are you missing a cast ? ) return new List < Dictionary < int , string > > ( ) ; } | Conversion of Generic using Interfaces |
C_sharp : I 'm using C # in Visual Studio 2010 with the framework 4.0.In my project , in two different forms , there are two FileSystemWatchers with the property EnableRaisingEvent set to false . If I close Visual Studio , when I reopen it I get in both FileSystemWatcher the property EnableRaisingEvent set to true.In both my forms in the designer file there is the following code : The property EnableRaisingEvent is not set , but the default is false.Any idea why I get this strange behaviour ? editI followed the Virtlink 's suggestion , adding the following line of code : It seemed to solve my problem , but after a few days ( and some opening , closing and rebuilding of the project , but without modifying the fileSystemWatcher1 ) I found : in the designer , in the properties of the fileSystemWatcher1 , EnableRaisingEvents was set back to truein the code , the line previously added was missingI tried moving to Visual Studio 2012 ( still framework 4.0 ) and the workaround fixed the problem for some more days . Then I got the same situation as in VS10 . Any other idea ? <code> private void InitializeComponent ( ) { this.components = new System.ComponentModel.Container ( ) ; System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager ( typeof ( Form1 ) ) ; this.fileSystemWatcher1 = new System.IO.FileSystemWatcher ( ) ; ( ( System.ComponentModel.ISupportInitialize ) ( this.fileSystemWatcher1 ) ) .BeginInit ( ) ; this.SuspendLayout ( ) ; this.fileSystemWatcher1.Filter = `` my_filter '' ; this.fileSystemWatcher1.NotifyFilter = System.IO.NotifyFilters.LastWrite ; this.fileSystemWatcher1.SynchronizingObject = this ; this.fileSystemWatcher1.Changed += new System.IO.FileSystemEventHandler ( this.fileSystemWatcher1_Changed ) ; } this.fileSystemWatcher1.EnableRaisingEvents = false ; | Each time I open Visual Studio the FileSystemWatcher EnableRaisingEvent changes |
C_sharp : Consider two iterator methods with the same bodies : Is there any circumstance where calling It2 is different from calling It1.GetEnumerator ( ) ? Is there ever a good reason to define an iterator as IEnumerator < T > over IEnumerable < T > ? The only one I can think of is when you are implementing IEnumerable < T > .GetEnumerator ( ) .EDIT : By iterator methods I mean methods using yield return and yield break constructs . <code> public static IEnumerable < int > It1 ( ) { ... } public static IEnumerator < int > It2 ( ) { ... } | Is there any difference between iterator methods returning IEnumerable < T > and IEnumerator < T > ? |
C_sharp : I 've been digging through ExpressionVisitor in .NET and I found this for loop , Now is there any particular reason why is that : i = 0 , n = nodes.Count ; i < n ? Is there any performance gain from this that is not in i = 0 ; i < nodes.Count ? <code> for ( int i = 0 , n = nodes.Count ; i < n ; i++ ) { Expression node = Visit ( nodes [ i ] ) ; if ( newNodes ! = null ) { newNodes [ i ] = node ; } else if ( ! object.ReferenceEquals ( node , nodes [ i ] ) ) { newNodes = new Expression [ n ] ; for ( int j = 0 ; j < i ; j++ ) { newNodes [ j ] = nodes [ j ] ; } newNodes [ i ] = node ; } } | For loop variable declaration for the condition in .NET Source code |
C_sharp : I am developing a compiler that emits IL code . It is important that the resulting IL is JIT'ted to the fastest possible machine codes by Mono and Microsoft .NET JIT compilers . My questions are : Does it make sense to optimize patterns like : and such , or are the JIT 's smart enough to take care of these ? Is there a specification with the list of optimizations performed by Microsoft/Mono JIT compilers ? Is there any good read with practical recommendations / best practices to optimize IL so that JIT compilers can in turn generate the most optimal machine code ( performance-wise ) ? <code> 'stloc.0 ; ldloc.0 ; ret ' = > 'ret ' 'ldc.i4.0 ; conv.r8 ' = > 'ldc.r8.0 ' | IL optimization for JIT compilers |
C_sharp : There are a hundred examples in blogs , etc . on how to implement a background worker that logs or gives status to a foreground GUI element . Most of them include an approach to handle the race condition that exists between spawning the worker thread , and creating the foreground dialog with ShowDialog ( ) . However , it occured to me that a simple approach is to force the creation of the handle in the form constructor , so that the thread wo n't be able to trigger an Invoke/BeginInvoke call on the form prior to its handle creation.Consider a simple example of a Logger class that uses a background worker thread to log to the foreground.Assume , also , that we do n't want NLog or some other heavy framework to do something so simple and lightweight.My logger window is opened with ShowDialog ( ) by the foreground thread , but only after the background `` worker '' thread is started . The worker thread calls logger.Log ( ) which itself uses logForm.BeginInvoke ( ) to update the log control correctly on the foreground thread.Where logDelegate is just a simple wrapper around `` form.Log ( ) '' or some other code that may update a progress bar.The problem lies in the race condition that exists ; when the background worker thread starts logging before the foreground ShowDialog ( ) is called the form 's Handle has n't yet been created so the BeginInvoke ( ) call fails.I 'm familiar with the various approaches , including using a Form OnLoad event and a timer to create the worker task suspended until the OnLoad event generates a timer message that starts the task once the form is shown , or , as mentioned , using a queue for the messages . However , I think that simply forcing the dialog 's handle to create early ( in the constructor ) ensures there is no race condition , assuming the thread is spawned off by the same thread that creates the dialog.http : //msdn.microsoft.com/en-us/library/system.windows.forms.control.handle ( v=vs.71 ) .aspxMSDN says : `` If the handle has not yet been created , referencing this property will force the handle to be created . `` So my logger wraps a form , and its constructor does : The solution seems too simple to be correct . I 'm specifically interested in why the seemingly too simple solution is or is n't safe to use.Any comments ? Am I missing something else ? EDIT : I 'm NOT asking for alternatives . Not asking how to use NLog or Log4net , etc . if I were , I 'd write a page about all of the customer constraints on this app , etc.By the number of upvotes , there are a lot of other people that would like to know the answer too . <code> public override void Log ( string s ) { form.BeginInvoke ( logDelegate , s ) ; } public SimpleProgressDialog ( ) { var h = form.Handle ; // dereference the handle } | Need second ( and third ) opinions on my fix for this Winforms race condition |
C_sharp : Do you think that C # will support something like ? ? = operator ? Instead of this : It might be possible to write : Now , I could use ( but it seems to me not well readable ) : <code> if ( list == null ) list = new List < int > ( ) ; list ? ? = new List < int > ( ) ; list = list ? ? new List < int > ( ) ; | What do you think about ? ? = operator in C # ? |
C_sharp : I have two BlockingCollection < T > objects , collection1 and collection2 . I want to consume items from these collections giving priority to items in collection1 . That is , if both collections have items , I want to take items from collection1 first . If none of them have items , I want to wait for an item to be available.I have the following code : This code is expected to return null when CompleteAdding is called on both collections and they both are empty.My main issue with this code is that the documentation for the TakeFromAny method specifies that TakeFromAny will throw an ArgumentException if CompleteAdding was called on `` the collection '' : ArgumentExceptionThe collections argument is a 0-length array or contains a null element or CompleteAdding ( ) has been called on the collection.Does it throw if CompleteAdding was called on any collection ? or both collections ? What if CompleteAdding was called and the collection still has some items , does it throw ? I need a reliable way to do this.In this code I am trying to get from collection1 first because the documentation of TakeFromAny does not give any guarantees about the collection order from which to take the item if the two collections have items.This also means that if both collections are empty , and then they receive items at the same time later , then I might get an item from collection2 first , which is fine.EDIT : The reason I add items to two collections ( and not simply a single collection ) is that the first collection does not have an upper-bound , and the second collection does.More details for those who are interested why I need this : I am using this in an open source project called ProceduralDataflow . See here for more details https : //github.com/ymassad/ProceduralDataflowEach processing node in the dataflow system has two collections , one collection will contain items coming for the first time ( so I need to slow down the producer if needed ) , and another collection will contain items coming for the second ( or third , .. ) times ( as a result of a loop in the data flow ) .The reason why one collection does not have an upper-bound is that I do n't want to have deadlocks as a result of loops in the dataflow . <code> public static T Take < T > ( BlockingCollection < T > collection1 , BlockingCollection < T > collection2 ) where T : class { if ( collection1.TryTake ( out var item1 ) ) { return item1 ; } T item2 ; try { BlockingCollection < T > .TakeFromAny ( new [ ] { collection1 , collection2 } , out item2 ) ; } catch ( ArgumentException ) { return null ; } return item2 ; } | How to take an item from any two BlockingCollections with priority to the first collection ? |
C_sharp : Is it possible to use the ref returns feature in C # 7.0 define a generic function that can do both comparison and update of a field in two instances of an Object ? I am imagining something like this : Example intended usage : Is there any way to specify a Func type or any kind of generic type restriction that would make this valid by requiring that getter return a reference ? I tried Func < TClass , ref TField > , but it does n't appear to be valid syntax . <code> void UpdateIfChanged < TClass , TField > ( TClass c1 , TClass c2 , Func < TClass , TField > getter ) { if ( ! getter ( c1 ) .Equals ( getter ( c2 ) ) { getter ( c1 ) = getter ( c2 ) ; } } Thing thing1 = new Thing ( field1 : 0 , field2 : `` foo '' ) ; Thing thing2 = new Thing ( field1 : -5 , field2 : `` foo '' ) ; UpdateIfChanged ( thing1 , thing2 , ( Thing t ) = > ref t.field1 ) ; UpdateIfChanged ( thing1 , thing2 , ( Thing t ) = > ref t.field2 ) ; | Generic functions and ref returns in C # 7.0 |
C_sharp : I was reading about SynchronizationContext and its use with the async/await methods ( link ) . From my understanding , in a Console application where the SynchronizationContext is null , the continuation of an awaited method ( Task ) will be scheduled with the default scheduler which would be the ThreadPool.But if I run this console app , you 'll see from the output that the the continuation is run on the worker thread that I created : And here is the output : As you can see , `` After WorkerThread '' was outputted on the same thread as my workerthread , but not on the threadpool.I found a similar question but the guy was using Mono and they were saying that this was a bug . On my side , I built this code with in Visual Studio and ran it under Windows 7 and .Net 4.5.2 installed on my machine.Could someone please explain this behaviour ? <code> class Program { static void Main ( string [ ] args ) { Console.WriteLine ( `` MainThreadId= '' + Thread.CurrentThread.ManagedThreadId ) ; Method1 ( ) .ContinueWith ( t = > { Console.WriteLine ( `` After Method1 . ThreadId= '' + Thread.CurrentThread.ManagedThreadId ) ; } ) ; Console.ReadKey ( ) ; } public static async Task Method1 ( ) { Console.WriteLine ( `` Method1 = > Entered . ThreadId= '' + Thread.CurrentThread.ManagedThreadId ) ; TaskCompletionSource < bool > completionSource = new TaskCompletionSource < bool > ( ) ; Thread thread = new Thread ( ( ) = > { Console.WriteLine ( `` Method1 = > Started new thread . ThreadId= '' + Thread.CurrentThread.ManagedThreadId ) ; Thread.Sleep ( 2000 ) ; completionSource.SetResult ( true ) ; } ) ; thread.Start ( ) ; await completionSource.Task ; Console.WriteLine ( `` Method1 = > After WorkerThread . ThreadId= '' + Thread.CurrentThread.ManagedThreadId ) ; } } MainThreadId=10Method1 = > Entered . ThreadId=10Method1 = > Started new thread . ThreadId=11Method1 = > After WorkerThread . ThreadId=11After Method1 . ThreadId=12 | Task continuation was not scheduled on thread-pool thread |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.