text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
C_sharp : There probably is a question on this already , but I was n't able to come up with the search terms to find an answer..I 'm probably missing something obvious here , but why am I not allowed to do the following , which gives the error : `` Argument 1 : can not convert from System.Collections.Generic.IEnumerable < TType > to System.Collections.Generic.IEnumerable < Test.A > '' whilst making the call to DoSomething ? whilst it is , of course , OK to do this : <code> public interface A { void Foo ( ) ; } public class B : A { public void Foo ( ) { } } class Test < TType > where TType : A { public Test ( IEnumerable < TType > testTypes ) { DoSomething ( testTypes ) ; } void DoSomething ( IEnumerable < A > someAs ) { } } class Test { public Test ( IEnumerable < B > testTypes ) { DoSomething ( testTypes ) ; } void DoSomething ( IEnumerable < A > someAs ) { } } | Constraint on generic type can not be used in IEnumerable ? |
C_sharp : I 've been reading a lot about why constructors are useful and all the resources I found specify that constructors are used to initialize the instances of your classes . A key benefit of using a constructor is that it guarantees that the object will go through proper initialization before being used , often accepting parameters . It helps ensure the integrity of the object and helps make applications written with object-oriented languages much more reliable.By default in C # a default empty constructor is instantiated if no constructors are specified in a class.Most examples I 'm finding specify something like this ; Now what 's the practical point of creating the constructor when you can specify the properties ; And initialise it like this ; I can not wrap my head around the need of having the explicitly creating a constructor . I would appreciate if someone would give me a good practical example . <code> public Car ( int speedCurrent , int gearCurrent ) { speed = speedCurrent ; gear= startGear ; } Car myCar = new Car ( 0 , 0 ) ; public int speed { get ; set ; } public int gear { get ; set ; } Car myCar = new Car ( ) ; myCar.speed = 0 ; myCar.gear = 0 ; | Constructors in C # |
C_sharp : I am iterating over elements which were taken from HTML . structureElement seems to hold found element , but when I run .FindElement ( ) on it , it returns always value from first iteration . Why is that ? Here is my code : <code> IReadOnlyCollection < IWebElement > structureElements = driver.FindElements ( By.XPath ( `` .//div [ contains ( @ id , 'PSBTree_x-auto- ' ) ] '' ) ) ; //.Where ( sE = > sE.FindElement ( By.XPath ( `` //img [ @ title ] '' ) ) .GetAttribute ( `` title '' ) ! = `` Customer Item '' ) IWebElement tmp ; foreach ( IWebElement structureElement in structureElements ) { //if ( structureElement.FindElement ( By.XPath ( `` //span//img [ @ title ] '' ) ) .GetAttribute ( `` title '' ) .Contains ( `` Customer Item '' ) ) // continue ; tmp = structureElement.FindElement ( By.XPath ( `` //span [ @ class='cat-icons-tree ' ] /img '' ) ) ; ReportProgress ( progress , ref r , ct , allsteps , message + tmp.GetCssValue ( `` background '' ) ) ; Thread.Sleep ( 100 ) ; ReportProgress ( progress , ref r , ct , allsteps , message + structureElement.Text ) ; Thread.Sleep ( 300 ) ; } | FindElement doesnt iterate when iterating elements in IReadOnlyCollection |
C_sharp : How do I declare and use generic interfaces ( see namespace Sample2 ) to work in the same way as with classes in namespace Sample1 ? I know there is a workaround ( see namespace Sample2Modified ) but that is not what I 'm trying to achieve.Works with classesWhen using classes , this works fine : Does not work with interfacesHowever , with interfaces the compiler gives this warning when declaring the property in ClassSampleDoesNotWork : Code : Modified version works , but this is not really what I wantIf I modify the class to have TEnumerableOfItem instead of TItem , it works : <code> namespace Sample1 { public class ClassContainer < T1 , T2 > where T1 : T2 { } public class ClassParent { } public class ClassChild : ClassParent { } public class ClassSampleDoesWork < TItem > where TItem : ClassParent { ClassContainer < IEnumerable < TItem > , IEnumerable < ClassParent > > SomeProperty { get ; set ; } } } Error 16 The type 'System.Collections.Generic.IEnumerable < TItem > ' can not be used as type parameter 'T1 ' in the generic type or method'Sample2.IInterfaceContainer < T1 , T2 > ' . There is no implicit referenceconversion from 'System.Collections.Generic.IEnumerable < TItem > ' to'System.Collections.Generic.IEnumerable < Sample2.IInterfaceParent > ' . namespace Sample2 { public interface IInterfaceContainer < T1 , T2 > where T1 : T2 { } public interface IInterfaceParent { } public interface IInterfaceChild : IInterfaceParent { } public class ClassSampleDoesNotWork < TItem > where TItem : IInterfaceParent { IInterfaceContainer < IEnumerable < TItem > , IEnumerable < IInterfaceParent > > SomeProperty { get ; set ; } } } namespace Sample2Modified { public interface IInterfaceContainer < T1 , T2 > where T1 : T2 { } public interface IInterfaceParent { } public interface IInterfaceChild : IInterfaceParent { } public class ClassSampleModifiedDoesWork < TEnumerableOfItem > where TEnumerableOfItem : IEnumerable < IInterfaceParent > { IInterfaceContainer < TEnumerableOfItem , IEnumerable < IInterfaceParent > > SomeProperty { get ; set ; } } } | How to use a generic type parameter as type parameter for a property declared as an interface with type constraints ? |
C_sharp : I 'm a relative newbie to C # , although I am a competent programmer , and I confess that I am totally confused as to whether or not it is a good idea to write custom collection classes . So many people seem to say `` do n't '' , yet there is a whole set of base classes for it in C # .Here is my specific case . I have a timetable application . As part of that , I have a service class , and the service class contains collections of things service-y , such as route links . A route link is itself a custom class : So far I have looked at using Dictionary as the type for RouteLinks , because I need to be able to reference them . This is fine in principle . However , the process of adding a RouteLink to the RouteLinks collection involves checking to see whether it is already there , or whether it extends and existing route link , or ... And for that , I need a custom Add function.So why is is such bad practice to create custom collection classes ? Why should n't I just inherit CollectionBase or DictionaryBase ? I should perhaps add that I am transferring this code from VBA [ please do n't shoot me : ) ] and there I HAD to implement custom collections . <code> public class Service { public RouteLinks RL ; // A collection of RouteLink types ... } public class RouteLink { public string FirstStopRef ; public string LastStopRef ; public Tracks RouteTrack ; // Another collection , this time of Track types } | C # Collection classes - yes or no |
C_sharp : I am using the new JsonSerializer from NETCore 3.0 's System.Text.Json namespace to deserialize Json documents like this : Response is defined as : The fact that JsonDocument implements IDisposable makes me wonder if by keeping a reference to an element ( Bar ) that can be contained in a JsonDocument , will create memory leaks ? Be advised that in general I avoid storing data as kind of `` variant '' type like this . Unfortunately the structure of the Bar property value is unknown at compile time.My suspicion stems from System.Text.Json advertised strength 's of lazy evaluation and I 'm not sure if that involves deferred I/O . <code> var result = JsonSerializer.Deserialize < Response > ( json , options ) ; public class Response { public string Foo { get ; set ; } public JsonElement Bar { get ; set ; } } | Am I creating a leak here ? |
C_sharp : I just lifted this snippet from a website and it proved to be exactly the solution I needed for my particular problem . I have no idea what it is ( particularly the delegate and return parts ) and the source does n't explain it . Hoping SO can enlighten me . <code> myList.Sort ( delegate ( KeyValuePair < String , Int32 > x , KeyValuePair < String , Int32 > y ) { return x.Value.CompareTo ( y.Value ) ; } ) ; | ok , this worked . what is it exactly ? |
C_sharp : In C # ( .NET 4.5 ) I would like to subscribe to an event while I 'm creating an object.The following , of course , would work : But want to find out if it 's possible to do something along the lines of : Post-discussion edit : This is in order to accomplish is something like : <code> CheckBox c = new CheckBox ( ) ; c.Name = `` TheCheckBox '' ; c.Checked += c_Checked ; CheckBox c = new CheckBox ( ) { Name = `` TheCheckBox '' , Checked += c_Checked } MyUniformGrid.Add ( new CheckBox ( ) { Name = `` TheCheckBox '' , Checked += CheckHandler } ) ; | Subscribing to event while creating object in C # |
C_sharp : Given an Enumerable , I want to Take ( ) all of the elements up to and including a terminator ( throwing an exception if the terminator is not found ) . Something like : ..except not crappy . Only want to walk it once.Is this concisely possible with current operators in .NET 4 and Rx or do I need to write a new operator ? Writing the operator would take me less time than it did to write this question ( though I think half that time would be figuring out what to name this function ) , but I just do n't want to duplicate something that 's already there.UpdateOk , here 's the operator . Very exciting , I know . Anyway , possible to build it from built-in operators ? <code> list.TakeWhile ( v = > ! condition ( v ) ) .Concat ( list.Single ( condition ) ) public static IEnumerable < T > TakeThroughTerminator < T > ( [ NotNull ] this IEnumerable < T > @ this , Func < T , bool > isTerminatorTester ) { foreach ( var item in @ this ) { yield return item ; if ( isTerminatorTester ( item ) ) { yield break ; } } throw new InvalidOperationException ( `` Terminator not found in list '' ) ; } | Looking for a particular Enumerable operator sequence : TakeWhile ( ! ) + Concat Single |
C_sharp : I did this pattern to match nested divs : This works nicely , as you can see in regex101.However , when I write the code below in C # : It throws me an error : As you can see \g does n't work in c # . How can I match the first subpattern then ? <code> ( < div [ ^ > ] * > ( ? : \g < 1 > | . ) * ? < \/div > ) Regex findDivs = new Regex ( `` ( < div [ ^ > ] * > ( ? : \\g < 1 > | . ) * ? < \\/div > ) '' , RegexOptions.Singleline ) ; Additional information : parsing `` ( < div [ ^ > ] * > ( ? : \g < 1 > | . ) * ? < \/div > ) '' - Unrecognized escape sequence \g . | How can I match the first subpattern in C # ? |
C_sharp : There are type parameters for methods . Why there are no type parameters for constructors ? ExampleI think there are several ( not many ) examples where it would be usefull . My current problem was following : A Delegate is enough for my class . But to pass it as method group I need to define the parameter as a Func < T > . <code> internal class ClassA { private readonly Delegate _delegate ; public ClassA < T > ( Func < T > func ) { _delegate = func ; } } | Why are type parameters not allowed in constructors ? |
C_sharp : This question is probably language-agnostic , but I 'll focus on the specified languages.While working with some legacy code , I often saw examples of the functions , which ( to my mind , obviously ) are doing too much work inside them . I 'm talking not about 5000 LoC monsters , but about functions , which implement prerequisity checks inside them.Here is a small example : Now , when this kind of function is called , the caller does n't have to worry about all that prerequisities to be fulfilled and one can simply say : Now - how should one deal with the following problem ? Like , generally speaking - should this function only do what it is asked for and move the `` prerequisity checks '' to the caller side : Or - should it simply throw exceptions per every prerequisity mismatch ? I 'm not sure this problem can be generalized , but still I want to here your thoughts about this - probably there is something I can rethink.If you have alternative solutions , feel free to tell me about them : ) Thank you . <code> void WorriedFunction ( ... ) { // Of course , this is a bit exaggerated , but I guess this helps // to understand the idea . if ( argument1 ! = null ) return ; if ( argument2 + argument3 < 0 ) return ; if ( stateManager.currentlyDrawing ( ) ) return ; // Actual function implementation starts here . // do_what_the_function_is_used_for } // Call the function.WorriedFunction ( ... ) ; if ( argument1 ! = null & & argument2 + argument3 < 0 & & ... ) { // Now all the checks inside can be removed . NotWorriedFunction ( ) ; } if ( argument1 ! = null ) throw NullArgumentException ; | General function question ( C++ / Java / C # ) |
C_sharp : I want a regex pattern to find any integer in the string , but not float ( with decimal point as `` . '' or `` , '' . So for string : abc111.222dfg333hfg44.55it should only find:333I created regex pattern : but it fails when using in C++ STL regex . It throws exception : but it works nice in C # Regex classUPDATE : My Code : but it throws exception on the line : UPDATE 2 : Both answers are correct , but for C++ STL regex Toto one works better . <code> ( ? < ! \\d [ \\. , ] |\\d ) \\d+ ( ? ! [ \\. , ] \\d+|\\d ) Unhandled exception at at 0x76AF4598 in xxxxxx.exe : Microsoft C++ exception : std : :regex_error at memory location 0x00C1F218 . smatch intMatch ; regex e1 ( `` ( ? < ! \\d [ \\. , ] |\\d ) \\d+ ( ? ! [ \\. , ] \\d+|\\d ) '' ) ; string s ( `` 111.222dfg333hfg44.55 '' ) ; regex_search ( s , intMatch , e1 ) ; regex e1 ( `` ( ? < ! \\d [ \\. , ] |\\d ) \\d+ ( ? ! [ \\. , ] \\d+|\\d ) '' ) ; | regex : find integer but not float |
C_sharp : I am working on a multi-touch app using Monogame , where multiple users can work on a larger multi-touch screen with separate documents/images/videos simultaneously , and I was wondering if it 's possible to make gestures `` context-aware '' , i.e . two fingers pinching a document on one side of the wall should n't affect somebody panning the other side of the wall.The way Monogame works is , all input points are translated into gestures , which can be read using : Is there a way to make gestures limited to a certain point on the screen , or do I need to implement this myself ? For example , by looking at the source code , it appears that the TouchPanelState class does all the work , but unfortunately its constructors are internal . <code> if ( TouchPanel.IsGestureAvailable ) { var gesture = TouchPanel.ReadGesture ( ) ; // do stuff } | Is it possible to get `` contextual '' gestures in Monogame/XNA ? |
C_sharp : I just do n't get something in the .NET generic type casting.Can someone explain what happens in the following code snippet ? <code> void Main ( ) { IEnumerable < int > ints = new List < int > ( ) ; IEnumerable < string > strings = new List < string > ( ) ; var rez1= ( IEnumerable < object > ) ints ; //runtime error var rez2= ( IEnumerable < object > ) strings ; //works var rez3= ( List < object > ) strings ; //runtime error } | Generics type casting |
C_sharp : Can someone explain to me why the below code outputs what it does ? Why is T a String in the first one , not an Int32 , and why is it the opposite case in the next output ? This puzzle is from an interview with Eric LippertWhen I look through the code , I really have no idea if it 's going to be an Int32 or a String : <code> public class A < T > { public class B : A < int > { public void M ( ) { System.Console.WriteLine ( typeof ( T ) ) ; } public class C : B { } } } public class P { public static void Main ( ) { ( new A < string > .B ( ) ) .M ( ) ; //Outputs System.String ( new A < string > .B.C ( ) ) .M ( ) ; //Outputs System.Int32 Console.Read ( ) ; } } | Puzzle from an Interview with Eric Lippert : Inheritance and Generic Type Setting |
C_sharp : I have a List < string > myList in my class that I want to be readonly for the class users.Like this I thought I could set the myList value inside my class in my private members and make it readonly for the class users . But I realised that declaring it that way I 'm unable to set any value . <code> List < strign > myList { get ; } private void SetListValue ( ) { myList = new List < string > ( ) ; myList.Add ( `` ss '' ) ; } | How to make a readonly C # List by non declaring its set attribute |
C_sharp : I have a Flags Enum : and then a classAssuming the following values and a specific range period : How can substract from the totalSeconds the task 's totalSeconds ? So basically I want to exclude from the totalSeconds the period when the task occures which is every Monday , Tuesday , Wednesday between 00:00 and 06:00 which is 3x6hours = 18 hours which is 64800 seconds ? I need to do this by applying the mask to the time range ... <code> [ Flags ] public enum WeekDays { Monday = 1 , Tuesday = 2 , Wednesday = 4 , Thursday = 8 , Friday = 16 , Saturday = 32 , Sunday = 64 } public class Task { public Task ( ) { } public int Days { get ; set ; } public TimeSpan Start { get ; set ; } public TimeSpan End { get ; set ; } } Task task = new Task ( ) ; task.Days = 7 ; // from WeekDays enum : 7 = Monday , Tuesday , Wednesday task.Start = TimeSpan.Parse ( `` 00:00 '' ) ; //midnight task.End = TimeSpan.Parse ( `` 06:00 '' ) ; //morning 06 AM DateTime now = DateTime.Now ; DateTime start = now.AddDays ( -6 ) ; TimeSpan time = now - start ; double toatlSeconds = time.TotalSeconds ; // get total seconds between the start and now datetime range | c # DateTime range exclude specific ranges |
C_sharp : I 'm allowing users to input their own SQL statement to execute , but only if it 's a SELECT statement . Is there a way to detect if the SQL statement is anything but this , i.e . an ALTER , INSERT , DROP , etc. ? I 'll worry about other concerns such as a query locking up a table and such later , but this is more of a proof of concept right now . I can restrict the service account on the server running the app to have read-only rights on the db , but I 'm interested in seeing it handled in the app.This is my approach to it by detecting the first word of the query , but this seems vulnerable . Is there a cleaner way to do this detection ? <code> public void ExecuteQuery ( string connectionString , int id ) { //The SQL statement will be user input var sql = `` SELECT ColumnA , ColumnB , ColumnC FROM MyTable where MyTableId = @ Id '' ; var split = sql.Split ( ' ' ) ; if ( split [ 0 ] .ToUpper ( ) ! = `` SELECT '' ) Console.WriteLine ( `` Only use a SELECT statement . `` ) ; else { using ( var connection = new SqlConnection ( connectionString ) ) using ( var cmd = new SqlCommand ( sql , connection ) ) { cmd.Parameters.AddWithValue ( `` @ Id '' , SqlDbType.Int ) ; cmd.Parameters [ `` @ Id '' ] .Value = id ; connection.Open ( ) ; var reader = cmd.ExecuteReader ( ) ; try { while ( reader.Read ( ) ) { Console.WriteLine ( $ '' { reader [ `` ColumnA '' ] } , { reader [ `` ColumnB '' ] } , { reader [ `` ColumnC '' ] } '' ) ; } } finally { reader.Close ( ) ; } cmd.ExecuteNonQuery ( ) ; } } } | Prevent Non-SELECT SQL Statements |
C_sharp : Is it possible to add dates in C # ? I tried this but it does n't work . <code> ( DateTime.Today.ToLongDateString ( ) + 10 ) | Adding DateTime in C # |
C_sharp : I have a WPF program , and when I localize it , it fails . I created this XML namespace , which corresponds to the file location , in the Window element : This is how I am localizing each element : The designer works perfectly fine , and I when I choose Resources. , auto-complete pulls up the available items , but when I build my application , it crashes with this error message : Exception thrown : 'System.Windows.Markup.XamlParseException ' in PresentationFramework.dllAdditional information : 'Provide value on 'System.Windows.Markup.StaticExtension ' threw an exception . ' Line number ' 5 ' and line position ' 9'.The line number and position correspond to the first x in the namespace I have given above . I tried searching this message on the web , and I ca n't seem to find anything . <code> xmlns : properties= '' clr-namespace : ResxEditor.Properties '' < Button Content= '' { x : Static properties : Resources.FilePickerButton_AddFile } '' / > | Why ca n't I localize my WPF program ? I get `` Exception thrown : 'System.Windows.Markup.XamlParseException ' in PresentationFramework.dll '' |
C_sharp : I recently started learning c # and learned that there are 2 ways to have my code output even numbers when I write this For loop . I learned the syntax of version 2 , which is intuitive to me . However , version 1 was an exampled I found elsewhere online . I want to understand if there is a difference between the two versions.Of the two possible ways , is there any difference between the two syntaxes ? If yes , which is more efficient and why ? <code> //Version 1for ( int num = 0 ; num < 100 ; num+=2 ) { Console.WriteLine ( num ) ; } //Version 2for ( int num = 0 ; num < 100 ; num++ ) { if ( num % 2 == 0 ) { Console.WriteLine ( num ) ; } } | What is the more efficient syntax to produce an even number in my console project ? |
C_sharp : While perusing Twitter I spotted a tweet by a Game Developer I follow that just said ; @ ChevyRay 2:44 AM - 5 Jul 2016 i give you : the stupidest 8 lines of code i ’ ve ever written that is actually used by my game ’ s code Immediately I looked at it and thought to myself what does this do ? I 'm sure the post was meant as an in-joke but I just did n't get it . So with that I went and researched yield but that did n't really answer my question.I wondered if anyone here could shed some light on firstly what it 's doing and also why . <code> static IEnumerable < int > RightAndleft { get { yield return 1 ; yield return -1 ; } } | What is the purpose of Yield and how does it work ? |
C_sharp : I 'm creating a query string in a web form , and I 'm dealing with values from the parameters that might be null . There are lots of ways to check and fix these , but the most elegant one I found is the following : The only issue is ... it does n't work . When the code reaches this part , the string stops assigning values . So the string would end with & _leadCon=.I know of ways to work around this , but I do n't know why it stopped working in the first place . Any tips ? <code> string pass ; pass = `` BillabilityDetail.aspx ? _startDate= '' + _startDate.Text + `` & _endDate= '' + _endDate.Text + `` & _isContractor= '' + _isContractor.SelectedValue + `` & _busUnit= '' + _busUnit.Text + `` & _projectUnit= '' + _projectUnit.SelectedValue + `` & _leadCon= '' + _leadCon.Value ? ? -1 + `` & _acctExec= '' + _acctExec.Value ? ? -1 + `` & _isBillable= '' + _isBillable.SelectedValue + `` & _isActive= '' + _isActive.SelectedValue + `` & _include= '' + _include.SelectedValue ; `` & _leadCon= '' + _leadCon.Value ? ? -1 + `` & _acctExec= '' + _acctExec.Value ? ? -1 | Why is the null coalescing operator breaking my string assignment in c # ? |
C_sharp : What is the difference betweenandThey seem to give me the same results . <code> var q_nojoin = from o in one from t in two where o.SomeProperty == t.SomeProperty select new { o , t } ; var q_join = from o in one join t in two on o.SomeProperty equals t.SomeProperty select new { o , t } ; | What is the difference between where and join ? |
C_sharp : I 'm trying the PagedList.Mvc library from herehttps : //github.com/TroyGoode/PagedListwhich has this usage sampletypical implmentations of MyProductDataSource.FindAllProducts ( ) ; are along the lines ofwhich of course has the InvalidOperationException ( ) and DBContext is already disposed messageLooking for best practices on how to return IQueryable which can be used here without issues ? <code> var products = MyProductDataSource.FindAllProducts ( ) ; //returns IQueryable < Product > representing an unknown number of products . a thousand maybe ? var pageNumber = page ? ? 1 ; // if no page was specified in the querystring , default to the first page ( 1 ) var onePageOfProducts = products.ToPagedList ( pageNumber , 25 ) ; // will only contain 25 products max because of the pageSize public IQuerable < T > MyProductDataSource.FindAllProducts ( ) { using ( var ctx = new MyCtx ( ) ) { return ctx.MyList ( ) .Where ( ... . ) ; } } | How to return IQueryable < T > for further querying |
C_sharp : My questions as follows , I need to check conditions through the database . which means in the simple application we check if conditions like this.Suppose , Client , needs to change the condition dynamically , which means he need to add additional condition to the system like , if 31 < = age & & age < = 40 = > Range 31 - 40When doing this in the client side , sometimes wrong conditions can be added to the system like , ( 4 < = age & & age < = 15 ) this condition can not be added , because the system already have condition ( 5 < = age & & age < = 10 ) . When age is 7 , both conditions will be true . like this type situations what is the best thing to do.I need to store the conditions in my database , ( PS : database table structure can be changed according to your answer ) as the sample table structurePlease give me a solution to solve this . How can I do this with C # and oracle SQL <code> private static void Main ( string [ ] args ) { Console.WriteLine ( `` Enter your age '' ) ; var age = int.Parse ( Console.ReadLine ( ) ? ? throw new InvalidOperationException ( ) ) ; if ( 5 < = age & & age < = 10 ) { Console.WriteLine ( `` Range 5 - 10 '' ) ; } else if ( 11 < = age & & age < = 20 ) { Console.WriteLine ( `` Range 11 - 20 '' ) ; } else if ( 21 < = age & & age < = 30 ) { Console.WriteLine ( `` Range 21 - 30 '' ) ; } else { Console.WriteLine ( `` Over range '' ) ; } } ConditionID Condition Detailscon001 5 < = age & & age < = 10 Range 5 - 10con002 11 < = age & & age < = 20 Range 11 - 20con003 21 < = age & & age < = 30 Range 21 - 30 | How to check if statements dynamically |
C_sharp : Newtonsoft.Json.Linq.JObject implemented IEnumerable < T > , and not explicit implementation , but why ca n't do this : WHY ? Thanks . <code> using System.Linq ; ... var jobj = new JObject ( ) ; var xxx = jobj.Select ( x = > x ) ; //errorforeach ( var x in jobj ) { } //no error | Why ca n't use LINQ methods on JObject ? |
C_sharp : I 've got code in a button click like so : Nowhere else but in the finally block is the cursor set back to default , yet it does `` get tired '' and revert to its default state for some reason . Why would this be , and how can I assure that it will not stop `` waiting '' until the big daddy of all the processes ( GenerateReports ( ) ) has completed ? <code> try { Cursor = Cursors.WaitCursor ; GenerateReports ( ) ; } finally { Cursor = Cursors.Default ; GC.Collect ( ) ; GenPacketBtn.Enabled = true ; } | Why would the hourglass ( WaitCursor ) stop spinning ? |
C_sharp : I write simple library wich returns List of names.But , what i should returns if i can not find anything ? or example : This code can be used from another components and i do not want to corrupted it.If i return null- i think it is right way to check it . But , may be i should return empty list ? Thank you . <code> return new List < String > ( ) ; return null ; var resultColl=FindNames ( ... ) ; | What result i should return ? |
C_sharp : I have the following class : In English grammar you can ’ t have “ is something equal to something ” or “ does something greater than something ” so I don ’ t want Is.EqualTo and Does.GreaterThan to be possible . Is there any way to restrict it ? Thank you ! <code> public class Fluently { public Fluently Is ( string lhs ) { return this ; } public Fluently Does ( string lhs ) { return this ; } public Fluently EqualTo ( string rhs ) { return this ; } public Fluently LessThan ( string rhs ) { return this ; } public Fluently GreaterThan ( string rhs ) { return this ; } } var f = new Fluently ( ) ; f.Is ( `` a '' ) .GreaterThan ( `` b '' ) ; f.Is ( `` a '' ) .EqualTo ( `` b '' ) ; //grammatically incorrect in Englishf.Does ( `` a '' ) .GreaterThan ( `` b '' ) ; f.Does ( `` a '' ) .EqualTo ( `` b '' ) ; //grammatically incorrect in English | Question regarding fluent interface in C # |
C_sharp : I would like to print products in order of quantity.The product with a bigger total should be first.What am I missing here as it 's NOT printing in order or total <code> class Program { static void Main ( ) { var products=new List < Product > { new Product { Name = `` Apple '' , Total = 5 } , new Product { Name = `` Pear '' , Total = 10 } } ; var productsByGreatestQuantity = products.OrderBy ( x = > x.Total ) ; foreach ( var product in productsByGreatestQuantity ) { System.Console.WriteLine ( product.Name ) ; } System.Console.Read ( ) ; } } public class Product { public string Name { get ; set ; } public int Total { get ; set ; } } | How do you order by Greatest number in linq |
C_sharp : I am cross-posting this question from Microsoft Community because I have n't gotten any response there , and maybe someone here can shed some light on this.I have noticed an issue that is specific to Word 2013 when using VSTO to process a document.The document contains an image in the header or footer that has its Layout Options set to `` With Text Wrapping '' with either `` Behind Text '' or `` In Front of Text '' : Using VSTO , if I open the document and then attempt to process shapes , I get the following exception : I have uploaded a repro here : Word2013VstoImageFormattedInHeaderBug.zipThe relevant piece of code is in WordFieldEnumerator.cs : Here is the full exception and stacktrace : The exception is thrown regardless of whether I attempt to catch it or not , and it crashes Word 2013 : This bug does not occur on Word 2016 , and I can process shapes successfully . However , upgrading to Office 2016 is not an option . I am of the opinion that this requires a hotfix for Office 2013 in order for the bug to be fixed.Is there anything I can do to get this working on Word 2013 ? I have tried numerous supposed fixes , including multiple repairs and re-installs of Office 2013 , to no avail . <code> The remote procedure call failed . ( Exception from HRESULT : 0x800706BE ) private static bool ShapesWithinGroup ( Shape shape ) { var result = false ; try { // shape.GroupItems throws the exception if ( shape.GroupItems ! = null & & shape.GroupItems.Count > 0 ) { result = true ; } } catch ( UnauthorizedAccessException ) { // This shape is not in a group - ignore } catch ( Exception exception ) { var exceptionString = exception.BuildExceptionString ( ) ; Console.WriteLine ( exceptionString ) ; Console.WriteLine ( exception.StackTrace ) ; //throw ; } return result ; } The remote procedure call failed . ( Exception from HRESULT : 0x800706BE ) at Microsoft.Office.Interop.Word.Shape.get_GroupItems ( ) at Word2013VstoImageFormattedInHeaderBug.WordFieldEnumerator.ShapesWithinGroup ( Shape shape ) in C : \Users\QA\Desktop\Word2013VstoImageFormattedInHeaderBug\Word2013VstoImageFormattedInHeaderBug\WordFieldEnumerator.cs : line 170The RPC server is unavailable . ( Exception from HRESULT : 0x800706BA ) at Microsoft.Office.Interop.Word.Shape.get_TextFrame ( ) at Word2013VstoImageFormattedInHeaderBug.WordFieldEnumerator.ProcessShapes ( IEnumerable ` 1 shapes ) in C : \Users\QA\Desktop\Word2013VstoImageFormattedInHeaderBug\Word2013VstoImageFormattedInHeaderBug\WordFieldEnumerator.cs : line 124The RPC server is unavailable . ( Exception from HRESULT : 0x800706BA ) at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal ( Int32 errorCode , IntPtr errorInfo ) at System.Runtime.InteropServices.CustomMarshalers.EnumeratorViewOfEnumVariant.MoveNext ( ) at System.Linq.Enumerable. < CastIterator > d__aa ` 1.MoveNext ( ) at Word2013VstoImageFormattedInHeaderBug.WordFieldEnumerator.ProcessShapes ( IEnumerable ` 1 shapes ) in C : \Users\QA\Desktop\Word2013VstoImageFormattedInHeaderBug\Word2013VstoImageFormattedInHeaderBug\WordFieldEnumerator.cs : line 90 at Word2013VstoImageFormattedInHeaderBug.WordFieldEnumerator.GetAllFields ( ) in C : \Users\QA\Desktop\Word2013VstoImageFormattedInHeaderBug\Word2013VstoImageFormattedInHeaderBug\WordFieldEnumerator.cs : line 64 at Word2013VstoImageFormattedInHeaderBug.Program.LockDialogFields ( Document document ) in C : \Users\QA\Desktop\Word2013VstoImageFormattedInHeaderBug\Word2013VstoImageFormattedInHeaderBug\Program.cs : line 116 at Word2013VstoImageFormattedInHeaderBug.Program.PdfDocument ( String documentFilePath ) in C : \Users\QA\Desktop\Word2013VstoImageFormattedInHeaderBug\Word2013VstoImageFormattedInHeaderBug\Program.cs : line 60 | BUG : Word 2013 VSTO Can not Handle Image in Header Formatted Behind or In Front of Text |
C_sharp : I want to replace every occurrence of one of those magic 2-byte packages in my List < byte > with a single byte : { 0xF8 , 0x00 } - > Replace with 0xF8 { 0xF8 , 0x01 } - > Replace with 0xFB { 0xF8 , 0x02 } - > Replace with 0xFD { 0xF8 , 0x03 } - > Replace with 0xFEFor example : This is my solution so far , which works but I do n't like it because its readability is quite bad : Is there a shorter solution with improved readability ? <code> List < byte > message = new List < byte > { 0xFF , 0xFF , 0xFB , 0xF8 , 0x00 , 0xF8 , 0x01 , 0xF8 , 0x02 , 0xF8 , 0x03 , 0xFE } ; // will be converted to : List < byte > expected = new List < byte > { 0xFF , 0xFF , 0xFB , 0xF8 , 0xFB , 0xFD , 0xFE , 0xFE } ; public static void RemoveEscapeSequences ( List < byte > message ) { // skipped parameter checks for ( int index = 0 ; index < message.Count - 1 ; ++index ) { if ( message [ index ] == 0xF8 ) { // found an escaped byte , look at the following byte to determine replacement switch ( message [ index + 1 ] ) { case 0x0 : message [ index ] = 0xF8 ; message.RemoveAt ( index + 1 ) ; break ; case 0x1 : message [ index ] = 0xFB ; message.RemoveAt ( index + 1 ) ; break ; case 0x2 : message [ index ] = 0xFD ; message.RemoveAt ( index + 1 ) ; break ; case 0x3 : message [ index ] = 0xFE ; message.RemoveAt ( index + 1 ) ; break ; } } } } | Replace two bytes in a generic list |
C_sharp : I have a C # application that uses an unmanaged C++ DLL . I 've found a crash that only happens in WinXP ( not Win7 ) when the memory I 'm passing back from the C++ DLL is too big.The basic flow is that C # starts an operation in the C++ DLL by calling a start function , in which it provides a callback . The C++ DLL then performs the operation and dumps logging information into a text buffer . When the operation is completed the C++ DLL calls the callback and passes the text buffer as a parameter : C++ : C # : This works fine in Win7 , but in WinXP if the buffer gets too big it crashes . I 'm not sure of the exact size that causes this but I 've put an 8MB limit on it and the crash has disappeared.Does anyone know of a limit on the amount of memory that can be transferred between C++ and C # like this in WinXP ? Or have I completely misunderstood this problem and there 's a more logical explanation ? Update : I should have been more specific - this occurs on the same PC with WinXP and Win7 dual boot , both 32-bit OS . <code> typedef void ( CALLBACK *onfilecallbackfunc_t ) ( LPCWSTR ) ; DLL_API void NWAperture_SetOnFileCallback ( onfilecallbackfunc_t p_pCallback ) ; l_pFileCallback ( _wstringCapture.c_str ( ) ) ; public delegate void FileCallback ( [ MarshalAs ( UnmanagedType.LPWStr ) ] string buffer ) ; public static extern void SetOnFileCallback ( FileCallback fileCallback ) ; private void OnFile ( string buffer ) ; | What 's the memory limit in WinXP when getting a callback from a C++ DLL in C # ? |
C_sharp : The issue is that VS2010 Code Analysis is returning two CA2000 warnings for a particular function . I have n't been successful at reproducing the warnings with a smaller block of code , so I 've posted the original function in it 's entirety.The two CA2000 warnings pertain to the using statements containing the SqlConnection and SqlCommand.I ca n't find any issues in the code itself , but I have found that commenting out lines at random will make the errors go away . For instance , commenting out the three money fields being set to 0 in the else block will remove the warnings . Conversely , commenting out just the three lines with DBNull.Value at the end will remove the error too . I ca n't make sense of the results . <code> public int SaveTransaction ( Transaction tx , UserAccount account ) { if ( tx == null ) { throw new ArgumentNullException ( `` tx '' ) ; } if ( account == null ) { throw new ArgumentNullException ( `` account '' ) ; } bool isRefund = tx.TransactionType == LevelUpTransaction.TransactionTypes.Refund ; int pnRef = 0 ; using ( SqlConnection conn = new SqlConnection ( DatabaseConfiguration.ConnectionString ) ) { using ( SqlCommand cmd = new SqlCommand ( `` dbo.SaveTransaction '' , conn ) ) { cmd.CommandType = CommandType.StoredProcedure ; cmd.Parameters.Add ( `` @ InvoiceId '' , SqlDbType.VarChar , 100 ) .Value = tx.InvoiceNumber ; cmd.Parameters.Add ( `` @ TxStartDate '' , SqlDbType.DateTime ) .Value = tx.TransactionBeginDate ; cmd.Parameters.Add ( `` @ AuthDate '' , SqlDbType.DateTime ) .Value = tx.AuthenticationDate ; cmd.Parameters.Add ( `` @ MerchantKey '' , SqlDbType.Int ) .Value = account.MerchantKey ; cmd.Parameters.Add ( `` @ UserName '' , SqlDbType.Char , 25 ) .Value = account.UserName ; cmd.Parameters.Add ( `` @ RegisterNumber '' , SqlDbType.Char , 10 ) .Value = tx.RegisterNumber ; cmd.Parameters.Add ( `` @ ResellerKey '' , SqlDbType.Int ) .Value = account.ResellerKey ; cmd.Parameters.Add ( `` @ TxEndDate '' , SqlDbType.DateTime ) .Value = tx.TransactionEndDate ; cmd.Parameters.Add ( `` @ IpAddress '' , SqlDbType.VarChar , 15 ) .Value = account.IPAddress ; cmd.Parameters.Add ( `` @ CustomerId '' , SqlDbType.VarChar , 50 ) .Value = tx.CustomerId ; cmd.Parameters.Add ( `` @ TransactionId '' , SqlDbType.VarChar , 50 ) .Value = tx.TransactionId ; cmd.Parameters.Add ( `` @ ProcStartDate '' , SqlDbType.DateTime ) .Value = tx.ProcessorBeginDate ; cmd.Parameters.Add ( `` @ ProcEndDate '' , SqlDbType.DateTime ) .Value = tx.ProcessorEndDate ; cmd.Parameters.Add ( `` @ AuthAmount '' , SqlDbType.Money ) .Value = StringParser.ParseDecimal ( tx.OriginalAmount ) ; cmd.Parameters.Add ( `` @ ResultCode '' , SqlDbType.VarChar , 50 ) .Value = tx.ResultCode ; cmd.Parameters.Add ( `` @ ResultMessage '' , SqlDbType.VarChar , 150 ) .Value = tx.ResultMessage ; cmd.Parameters.Add ( `` @ PONumber '' , SqlDbType.VarChar , 100 ) .Value = tx.PurchaseOrderNumber ; cmd.Parameters.Add ( `` @ TaxAmount '' , SqlDbType.Money ) .Value = StringParser.ParseDecimal ( tx.TaxAmount ) ; cmd.Parameters.Add ( `` @ Refund '' , SqlDbType.Bit ) .Value = isRefund ; if ( tx.Order ! = null ) { cmd.Parameters.Add ( `` @ HostDate '' , SqlDbType.VarChar , 50 ) .Value = tx.Order.HostTime.ToString ( ) ; cmd.Parameters.Add ( `` @ ApprovalCode '' , SqlDbType.VarChar , 50 ) .Value = tx.Order.TransactionId.ToString ( CultureInfo.InvariantCulture ) ; cmd.Parameters.Add ( `` @ NameOnCard '' , SqlDbType.VarChar , 200 ) .Value = tx.Order.UserFirstName + `` `` + tx.Order.UserLastNameInitial ; cmd.Parameters.Add ( `` @ TipAmount '' , SqlDbType.Money ) .Value = StringParser.ParseDecimal ( tx.Order.Tip.FormattedAmount ) ; cmd.Parameters.Add ( `` @ TotalAmount '' , SqlDbType.Money ) .Value = StringParser.ParseDecimal ( tx.Order.TotalAmount.FormattedAmount ) ; cmd.Parameters.Add ( `` @ DiscountAmount '' , SqlDbType.Money ) .Value = StringParser.ParseDecimal ( tx.Order.CreditAmount.FormattedAmount ) ; } else { cmd.Parameters.Add ( `` @ NameOnCard '' , SqlDbType.VarChar , 200 ) .Value = DBNull.Value ; cmd.Parameters.Add ( `` @ HostDate '' , SqlDbType.VarChar , 50 ) .Value = DBNull.Value ; cmd.Parameters.Add ( `` @ ApprovalCode '' , SqlDbType.VarChar , 50 ) .Value = DBNull.Value ; cmd.Parameters.Add ( `` @ TipAmount '' , SqlDbType.Money ) .Value = 0 ; cmd.Parameters.Add ( `` @ TotalAmount '' , SqlDbType.Money ) .Value = 0 ; cmd.Parameters.Add ( `` @ DiscountAmount '' , SqlDbType.Money ) .Value = 0 ; } if ( isRefund ) { cmd.Parameters.Add ( `` @ OriginalPnRef '' , SqlDbType.Int ) .Value = tx.OriginalToken ; } conn.Open ( ) ; using ( SqlDataReader dr = cmd.ExecuteReader ( ) ) { while ( dr.Read ( ) ) { pnRef = SqlNull.Integer ( dr [ `` TRX_HD_Key '' ] ) ; } } } } return pnRef ; } | CA2000 Warning That Can Be Removed By Commenting out Seemingly Unrelated Code |
C_sharp : Do I have to wrap all my IDisposable objects in using ( ) { } statements , even if I 'm just passing one to another ? For example , in the following method : Could I consolidate this to just one using like this : Can I count on both the Stream and the StreamReader being disposed ? Or do I have to use two using statements ? <code> public static string ReadResponse ( HttpWebResponse response ) { string resp = null ; using ( Stream responseStream = response.GetResponseStream ( ) ) { using ( StreamReader responseReader = new StreamReader ( responseStream ) ) { resp = responseReader.ReadToEnd ( ) ; } } return resp ; } public static string ReadResponse ( HttpWebResponse response ) { string resp = null ; using ( StreamReader reader = new StreamReader ( response.GetResponseStream ( ) ) ) { resp = reader.ReadToEnd ( ) ; } return resp ; } | Is it necessary to nest usings with IDisposable objects ? |
C_sharp : I 'm trying to create a Dynamic Data website which should allow an administrator to directly edit the data in most tables in a database.So far , I have an EDMX and POCO classes , all attached to an Interface used to apply the DataAnnotations on the fields.I want to have an editable grid for each table , so I edited the ListDetails template and followed these instructions , which allows me to have inline editing in a ListView.With all of these , I can display and edit data . It works . But when I click on the header ( it is a LinkButton with the Sort Command and the column name as CommandArgument ) of a ForeignKey column , I always get the following exception ( but the sorting works on `` simple '' properties ) : [ EntitySqlException : The ORDER BY sort key ( s ) type must be order-comparable . Near member access expression , line 6 , column 3 . ] Microsoft.AspNet.EntityDataSource.EntityDataSourceView.ExecuteSelect ( DataSourceSelectArguments arguments ) +1325 System.Web.UI.DataSourceView.Select ( DataSourceSelectArguments arguments , DataSourceViewSelectCallback callback ) +21 System.Web.UI.WebControls.DataBoundControl.PerformSelect ( ) +138 System.Web.UI.WebControls.ListView.PerformSelect ( ) +167 System.Web.UI.WebControls.BaseDataBoundControl.DataBind ( ) +30 System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound ( ) +105 System.Web.UI.WebControls.BaseDataBoundControl.OnPreRender ( EventArgs e ) +22 System.Web.UI.Control.PreRenderRecursiveInternal ( ) +83 System.Web.UI.Control.PreRenderRecursiveInternal ( ) +155 System.Web.UI.Control.PreRenderRecursiveInternal ( ) +155 System.Web.UI.Control.PreRenderRecursiveInternal ( ) +155 System.Web.UI.Control.PreRenderRecursiveInternal ( ) +155 System.Web.UI.Control.PreRenderRecursiveInternal ( ) +155 System.Web.UI.Control.PreRenderRecursiveInternal ( ) +155 System.Web.UI.Page.ProcessRequestMain ( Boolean includeStagesBeforeAsyncPoint , Boolean includeStagesAfterAsyncPoint ) +974Example of the table I 'm trying to display and sort ( I 'm displaying and editing LINK_ENTITES_MODELISEES , I 'm trying to sort on the LOV_LOB column ) : It probably does n't work because it 's trying to sort on the object property and not the label it 's using , but I would expect Dynamic Data to handle that ( it uses the first string property as the display value , why ca n't it use it for sorting ? Moreover I also tried to add the DisplayColumn attribute , with the same result ) . I tried to handle the event ListView.OnSorting to manually edit the EntityDataSource.OrderBy property , adding the value it.LOV_LOB.libelle manually , for testing . It did n't work.I also tried to handle EntityDataSource.OnSelecting to see what is the value of EntityDataSource.OrderBy ( if I do n't set it manually it is always null even when the sorting works ) . It looks like it is ignored or replaced after this event . And the Exception does n't specify what OrderBy it 's trying to apply , so I 'm not sure what it 's trying to do.I tried to implement IComparable but it did n't work . I overrided the ToString ( ) to provide the display value , it did n't work either.I 'm out of idea . Any suggestion ? <code> [ MetadataType ( typeof ( ILINK_ENTITES_MODELISEES_MetaData ) ) ] public partial class LINK_ENTITES_MODELISEES : ILINK_ENTITES_MODELISEES_MetaData { public int id_entite_modelisee { get ; set ; } public short id_entite { get ; set ; } public short id_lob { get ; set ; } public System.DateTime date_val_debut { get ; set ; } public System.DateTime date_val_fin { get ; set ; } public virtual LOV_ENTITE LOV_ENTITE { get ; set ; } public virtual LOV_LOB LOV_LOB { get ; set ; } } public partial interface ILINK_ENTITES_MODELISEES_MetaData { [ Key ] [ Required ( ErrorMessage = `` id_entite_modelisee is required '' ) ] int id_entite_modelisee { get ; set ; } [ Required ( ErrorMessage = `` id_entite is required '' ) ] short id_entite { get ; set ; } [ Required ( ErrorMessage = `` id_lob is required '' ) ] short id_lob { get ; set ; } [ Required ( ErrorMessage = `` date_val_debut is required '' ) ] [ DataType ( DataType.Date ) ] System.DateTime date_val_debut { get ; set ; } [ Required ( ErrorMessage = `` date_val_fin is required '' ) ] [ DataType ( DataType.Date ) ] System.DateTime date_val_fin { get ; set ; } [ Display ( Name = `` entite '' ) ] LOV_ENTITE LOV_ENTITE { get ; set ; } [ Display ( Name = `` lob '' ) ] LOV_LOB LOV_LOB { get ; set ; } } [ MetadataType ( typeof ( ILOV_LOB_MetaData ) ) ] [ DisplayColumn ( `` libelle '' , `` libelle '' , false ) ] public partial class LOV_LOB : ILOV_LOB_MetaData { public short id { get ; set ; } public string libelle { get ; set ; } public System.DateTime date_val_debut { get ; set ; } public System.DateTime date_val_fin { get ; set ; } } public partial interface ILOV_LOB_MetaData { [ Key ] [ Required ( ErrorMessage = `` id is required '' ) ] short id { get ; set ; } [ Required ( ErrorMessage = `` libelle is required '' ) ] [ StringLength ( 5 ) ] string libelle { get ; set ; } [ Required ( ErrorMessage = `` date_val_debut is required '' ) ] [ DataType ( DataType.Date ) ] System.DateTime date_val_debut { get ; set ; } [ Required ( ErrorMessage = `` date_val_fin is required '' ) ] [ DataType ( DataType.Date ) ] System.DateTime date_val_fin { get ; set ; } } | `` The ORDER BY sort key ( s ) type must be order-comparable '' with dynamic data |
C_sharp : I have this code that emits some IL instructions that calls string.IndexOf on a null object : This is the generated IL code : As you can see there are three nop instructions before the call instruction.First I thought about Debug/Release build but this is not compiler generated code , I am emitting raw IL code and expect to see it as is.So my question is why are there three nop instruction when I had n't emitted any ? <code> MethodBuilder methodBuilder = typeBuilder.DefineMethod ( `` Foo '' , MethodAttributes.Public , typeof ( void ) , Array.Empty < Type > ( ) ) ; var methodInfo = typeof ( string ) .GetMethod ( `` IndexOf '' , new [ ] { typeof ( char ) } ) ; ILGenerator ilGenerator = methodBuilder.GetILGenerator ( ) ; ilGenerator.Emit ( OpCodes.Ldnull ) ; ilGenerator.Emit ( OpCodes.Ldc_I4_S , 120 ) ; ilGenerator.Emit ( OpCodes.Call , methodInfo ) ; ilGenerator.Emit ( OpCodes.Ret ) ; .method public instance int32 Foo ( ) cil managed { // Code size 12 ( 0xc ) .maxstack 2 IL_0000 : ldnull IL_0001 : ldc.i4.s 120 IL_0003 : nop IL_0004 : nop IL_0005 : nop IL_0006 : call instance int32 [ mscorlib ] System.String : :IndexOf ( char ) IL_000b : ret } // end of method MyDynamicType : :Foo | Why is IL.Emit method adding additional nop instructions ? |
C_sharp : Consider a class like this : How do I make the following code work ? Now I get this exception : InvalidCastException : Unable to cast object of type 'MyString ' to type 'System.String ' . <code> public class MyString { private string _string ; public string String { get { return _string ; } set { _string = value ; } } public MyString ( string s ) { _string = s ; } public static implicit operator string ( MyString str ) { return str.String ; } public static implicit operator MyString ( string str ) { return new MyString ( str ) ; } } MyString a = `` test '' ; object b = a ; var c = ( string ) b ; | String cast not working |
C_sharp : This is weird ... done updates loads of times before but can not spot why this is different.although I am using .net 4.0 now - however i doubt its a bug in its L2S implementation . Its not like this is a wierd and wonderful application of it . Although i am fairly sure this code worked whilst i was using the RC.I have also managed to reproduce this error by building a project from scratch using the information below.the problem here is that the update statement generated by L2S has no fields in the set statement . I have tried checking the that the pk is set ( only reason why i would think ervery field would be required in the where ) and also read aroudn the other dbml properties . I have been using linq2Sql for about 1 year and have never had a problem .. i still think i am just having a huge brain fart.Note : I have cleaned up the equals and GetHashCode methods to remove some fields - the problem persists after this . I have not cleaned up the SQL though.I have a client class from the dbml I added a method called updateThe CopyToMe method is inherited from an interfacealso the class has getHashCode overriddenand equalsthe update method in the partial classThe CopytoMe methodIm taking a client that was selected , changing its name and then calling this update method.The generated sql is as followsI have no idea why this is not working ... used this kind ofselect object - > set field to new value - > submit the selected objectpattern many times and not had this problem . there is also nothing obviously wrong with the dbml - although this is probably a false statementany ideas ? This problem make sit look like i 'm going to have to revert back to ADO.Net which would make me sad . <code> public partial class Client : ICopyToMe < Client > public interface ICopyToMe < T > { void CopyToMe ( T theObject ) ; } public override int GetHashCode ( ) { int retVal = 13 ^ ID ^ name.GetHashCode ( ) ; return retVal ; } public override bool Equals ( object obj ) { bool retVal = false ; Client c = obj as Client ; if ( c ! = null ) if ( c.ID == this.ID & & c._name == this._name ) retVal = true ; return retVal ; } public void UpdateSingle ( ) { L2SDataContext dc = new L2SDataContext ( ) ; Client c = dc.Clients.Single < Client > ( p = > p.ID == this.ID ) ; c.CopyToMe ( this ) ; c.updatedOn = DateTime.Now ; dc.SubmitChanges ( ) ; dc.Dispose ( ) ; } public void CopyToMe ( Client theObject ) { ID = theObject.ID ; name = theObject.name ; } exec sp_executesql N'UPDATE [ dbo ] . [ tblClient ] SET WHERE ( [ ID ] = @ p0 ) AND ( [ name ] = @ p1 ) AND ( [ insertedOn ] = @ p2 ) AND ( [ insertedBy ] = @ p3 ) AND ( [ updatedOn ] = @ p4 ) AND ( [ updatedBy ] = @ p5 ) AND ( [ deletedOn ] IS NULL ) AND ( [ deletedBy ] IS NULL ) AND ( NOT ( [ deleted ] = 1 ) ) ' , N ' @ p0 int , @ p1 varchar ( 8000 ) , @ p2 datetime , @ p3 int , @ p4 datetime , @ p5 int ' , @ p0=103 , @ p1='UnitTestClient ' , @ p2= '' 2010-05-17 11:33:22:520 '' , @ p3=3 , @ p4= '' 2010-05-17 11:33:22:520 '' , @ p5=3 | Linq2Sql - attempting to update but the Set statement in sql is empty |
C_sharp : I 'm working with a MongoDB database . I know when you insert a DateTime into Mongo , it converts it to UTC . But I 'm making a unit test , and my Assert is failing.I must be missing something obvious . When I look in the debugger , I can see that the datetime 's match , but the assert still says they do not ( but they do ) : Any ideas what I 'm doing wrong here ? EDIT : I 've come up with two possible solutions , both of which require me to remember to do something ( which is n't always the best thing to rely on ... ) : One is to use an extension method to truncate any DateTime coming out of the database : The other , after reading http : //alexmg.com/datetime-precision-with-mongodb-and-the-c-driver/ , is to tag any DateTime in the POCO class : <code> [ TestMethod ] public void MongoDateConversion ( ) { DateTime beforeInsert = DateTime.Now ; DateTime afterInsert ; Car entity = new Car { Name = `` Putt putt '' , LastTimestamp = beforeInsert } ; // insert 'entity ' // update 'entity ' from the database afterInsert = entity.LastTimestamp.ToLocalTime ( ) ; Assert.AreEqual ( beforeInsert , afterInsert ) ; // fails here } Result Message : Assert.AreEqual failed . Expected : < 5/21/2015 8:27:04 PM > . Actual : < 5/21/2015 8:27:04 PM > . public static DateTime Truncate ( this DateTime dateTime ) { var timeSpan = TimeSpan.FromMilliseconds ( 1 ) ; var ticks = - ( dateTime.Ticks % timeSpan.Ticks ) ; return dateTime.AddTicks ( ticks ) ; } public class Car : IEntity { public Guid Id { get ; set ; } [ BsonDateTimeOptions ( Representation = BsonType.Document ) ] public DateTime LastTimestamp { get ; set ; } } | DateTime ToLocalTime failing |
C_sharp : I asked a question and got answered here about performance issues which I had a with a large collection of data . ( created with linq ) ok , let 's leave it aside.But one of the interesting ( and geniusly ) optimization - suggested by Marc - was to Batchify the linq query . Here , the purpose of Batchify is to ensure that we are n't helping the server too much by taking appreciable time between each operation - the data is invented in batches of 1000 and each batch is made available very quickly.Now , I understand what it is doing , but I ca n't tell the difference since I might be missing the way it actually works . ( sometimes you think you know something ... till ... ) OK , back to basics : AFAIK , Linq works like this chain – : So , we ca n't start enumerating till the result of select in : was accomplished.So basically i 'm waiting for select to have all correct data ( after where , after orderby ) , and only then - my code can touch those values . ( yielded from the select ) But according to my understanding of Marc 's answer , it seems that there is a gap between those yields which allows other resources to do something ... ( ? ) If so , then between each iteration of # 4 , after line # 9 , there is a time for CPU to do something else ? QuestionCan someone shed a light please ? how does this work ? nbI already know that ( for example ) select is nothing but : But if so , my code ca n't touch it till all values ( after where , orderby ) were calculated ... edit : For those who ask if there 's difference : http : //i.stack.imgur.com/19Ojw.jpg2 seconds for 1M items . 9 seconds for 5M items . ( ignore the second line of time , ( extra console.write line ) . ) here it is for 5m list : http : //i.stack.imgur.com/DflGR.jpg ( the first one is withBatchify , the other is not ) <code> /*1*/ static IEnumerable < T > Batchify < T > ( this IEnumerable < T > source , int count ) /*2*/ { /*3*/ var list = new List < T > ( count ) ; /*4*/ foreach ( var item in source ) /*5*/ { /*6*/ list.Add ( item ) ; /*7*/ if ( list.Count == count ) /*8*/ { /*9*/ foreach ( var x in list ) yield return x ; /*10*/ list.Clear ( ) ; /*11*/ } /*12*/ } /*13*/ foreach ( var item in list ) yield return item ; /*14*/ } Where -- > OrderBy -- > Select public static IEnumerable < TResult > Select < TSource , TResult > ( this IEnumerable < TSource > source , Func < TSource , TResult > selector ) { foreach ( TSource element in source ) yield return selector ( elem ! [ enter image description here ] [ 3 ] ent ) ; } | Batchify long Linq operations ? |
C_sharp : I was excited to create my first app with C # 5.0 , and I wanted to use the async/await keywords to ease the pains of async data calls.I 'm a bit baffled that interfaces does not allow the async keyword to be part of the contract , as the await keyword only works for async marked methods . This would mean that it is impossible to call async methods through interface references . This also goes for abstract methods . Am I missing something here ? This would mean that my regular DI-stuff will no longer work : // client code : This is my current solution : Will I have to choose between abstraction and the langauge feature ? Please tell me I 'm missing something . <code> IAsyncRepository < T > { Task < IList < T > > GetAsync ( ) ; // no 'async ' allowed } abstract class AsyncRepositoryBase < T > { public abstract Task < IList < T > > GetAsync ( ) ; // no 'async ' allowed IAsyncRepository < Model > repo = ioc.Resolve < IAsyncRepository < Model > > ( ) ; var items = await repo.GetAsync ( ) ; // DOOOOOH , will not compile ! public abstract class AsyncRepositoryBase < T > { protected Task < IList < T > > _fetcherTask ; protected AsyncRepositoryBase ( Task < IList < T > > fetcherTask ) { _fetcherTask = fetcherTask ; } public virtual async Task < IList < T > > GetASync ( ) { return await _fetcherTask ; } } | Does the lack of the async keyword in interfaces break DI in C # 5.0 ? |
C_sharp : Let 's say that I have a class ( ClassA ) containing one method which calls the constructor of another class , like this : The class ClassB looks like this : ... and ClassC is even more simple : If I put these classes in their own assembly and compile the whole solution I do n't get any errors . But if I replace the using statement with this : I get a compile error asking me to add a reference to [ mynamespace ] .ClassC in ClassA . Since I 'm not calling ClassB ( ClassC myC ) at all this makes no sense to me - why do I have to include the types of other constructors regardless of whether I use them or not ? What if ClassC was included in a licensed or hard-to-aquire assembly ? Is this an example of bad design that developers should avoid or am I missing something here ? <code> public class ClassA { public void CallClassBConstructor ( ) { using ( ClassB myB = new ClassB ( ) ) { ... } } } public class ClassB : IDisposable { public ClassB ( ) { } public ClassB ( string myString ) { } public ClassB ( ClassC myC ) { } public void Dispose ( ) { ... } } public class ClassC { } using ( ClassB myB = new ClassB ( `` mystring '' ) ) { ... } | Why am I forced to reference types in unused constructors ? |
C_sharp : I have an instance variable with several members , many of which have their own members and so on . Using the debugger and watch variables , I found a string variable with a specific value that I need by diving into this variable 's members.However , after spending some time on other things and coming back to this , I am now unable to find where this value is located . When I have my application paused , is there a way to search the values of variables in the current context for a given value ? To clarify , if I have the given structure : Is there a way ( possibly using the watch list in VS debugger ) to search myVariable for any member or submember with the value `` A value '' , returning to me the path myVariable- > aMember- > subMember ? <code> myVariable|| -- aMember1| | -- subMember = `` A value '' || -- aMember2 | -- subMember = `` Another value '' | Find a variable with a given value in VS2008 |
C_sharp : For the following code : The result is B.G ( ) , whereas the result of similar C++ code would be D.G ( ) .Why is there this difference ? <code> class B { public String G ( ) { return `` B.G ( ) '' ; } } class D : B { public String G ( ) { return `` D.G ( ) '' ; } } class TestCompile { private static String TestG < T > ( T b ) where T : B { return b.G ( ) ; } static void Main ( string [ ] args ) { TestG ( new D ( ) ) ; } } | Why does this generic method call the base class method , not the derived class method ? |
C_sharp : For example , is there anything wrong with something like this ? If it were just a simple integer variable declaration it would be fine because once it went out of scope and would later be collected by the garbage collector but events are a bit .. longer-living ? Do I have to manually unsubscribe or take any sort of measures to make sure this works properly ? It just feels.. weird . Not sure if it is correct or not . Usually when I add to an event handler it lasts for the entirety of the application so I 'm not sure about what happens when constantly adding and removing event handlers . <code> private void button1_Click ( object sender , EventArgs e ) { Packet packet = new Packet ( ) ; packet.DataNotSent += packet_DataNotSent ; packet.Send ( ) ; } private void packet_DataNotSent ( object sender , EventArgs e ) { Console.WriteLine ( `` Packet was n't sent . `` ) ; } class Packet { public event EventHandler DataNotSent ; public void Send ( ) { if ( DataNotSent ! = null ) { DataNotSent ( null , EventArgs.Empty ) ; } } } | Anything wrong with short-lived event handlers ? |
C_sharp : I have a map-tile setting I 'm updating through a menu-button . I 've got an odd situation where I was only hitting an error on release builds . Code is as follows : View-ModelViewThis was all working fine in my developer environment but when I generated a release build I was getting the following : ErrorSystem.InvalidOperationException : A TwoWay or OneWay ToSource binding can not work on the read-only property 'SelectedTile ' ... Simple solution , change private set to set in the above SelectedTile property . So how come this was not throwing the error during debug and only during release ? I ca n't see how this was ever working during debug mode . <code> private KnownTileSource _selectedTile ; public KnownTileSource SelectedTile { get { return _selectedTile ; } private set { _selectedTile = value ; ... OnPropertyChanged ( `` SelectedTile '' ) ; } } < Window ... xmlns : predefined= '' clr-namespace : BruTile.Predefined ; assembly=BruTile '' > ... < MenuItem Header= '' _Bing Aerial '' Command= '' { Binding ChangeTileCommand } '' CommandParameter= '' { x : Static predefined : KnownTileSource.BingAerial } '' IsChecked= '' { Binding Path=SelectedTile , Mode=TwoWay , Converter= { local : EnumToBooleanConverter } , ConverterParameter=BingAerial } '' / > ... < /Window > | Private setter throwing error only on release build |
C_sharp : I need to make my mutable class immutable , now it looks like as following . However , still I 'm not sure that I have a fully `` immutable* class , and if it is , what kind of immutability this is called ? Based on my application B needs to be changed from time to time ; hence to keep the property of immutability , every update needs to be done throught Update function that returns a totally new B. UpdateTo shed a light on IMetaData that was cleverly spotted by Jon Skeet please consider following definitions : and following class is passed as M to B < C , M > <code> public class B < C , M > where C : IComparable < C > where M : IMetaData { internal B ( char tau , M metadata , B < C , M > nextBlock ) { if ( tau == ' R ' ) omega = 1 ; _lambda = new List < Lambda < C , M > > ( ) ; _lambda.Add ( new Lambda < C , M > ( tau : tau , atI : metadata ) ) ; foreach ( var item in nextBlock.lambda ) if ( item.tau ! = ' L ' ) _lambda.Add ( new Lambda < C , M > ( tau : 'M ' , atI : item.atI ) ) ; } internal int omega { private set ; get ; } private List < Lambda < C , M > > _lambda { set ; get ; } internal ReadOnlyCollection < Lambda < C , M > > lambda { get { return _lambda.AsReadOnly ( ) ; } } internal B < C , M > Update ( int Omega , char tau , M metadata ) { B < C , M > newBlock = new B < C , M > ( ) ; newBlock.omega = Omega ; newBlock._lambda = new List < Lambda < C , M > > ( this._lambda ) ; newBlock._lambda.Add ( new Lambda < C , M > ( tau : tau , atI : metadata ) ) ; return newBlock ; } internal B < C , M > Update ( Dictionary < uint , Lambda < C , M > > lambdas ) { B < C , M > newBlock = new B < C , M > ( ) ; newBlock.omega = this.omega ; newBlock._lambda = new List < Lambda < C , M > > ( ) ; foreach ( var l in lambdas ) newBlock._lambda.Add ( new Lambda < C , M > ( tau : l.Value.tau , atI : l.Value.atI ) ) ; return newBlock ; } } public class Lambda < C , M > where C : IComparable < C > where M : IMetaData { internal Lambda ( char tau , M atI ) { this.tau = tau ; this.atI = atI ; } internal char tau { private set ; get ; } internal M atI { private set ; get ; } } public interface IMetaData { UInt32 hashKey { set ; get ; } } public class MetaData : IMetaData { public UInt32 hashKey { set ; get ; } } | Can I call this C # class `` immutable '' ? |
C_sharp : What I am trying to do is load in objects from an XML save file . The problem is those objects are configurable by the user at runtime , meaning i had to use reflection to get the names and attributes of those objects stored in an XML file.I am in the middle of a recursive loop through the XML and up to the part where I need to create an object then thought ... .. ah - no idea how to do that : ( I have an array stuffed with empty objects ( m_MenuDataTypes ) , one of each possible type . My recursive loading function looks like thisI need to put some code where my comment is but I ca n't have a big switch statement or anything . The objects in my array can change depending on how the user has configured the app . <code> private void LoadMenuData ( XmlNode menuDataNode ) { foreach ( object menuDataObject in m_MenuDataTypes ) { Type menuDataObjectType = menuDataObject.GetType ( ) ; if ( menuDataObjectType.Name == menuDataNode.Name ) { //create object } } } | Generically creating objects in C # |
C_sharp : I am running the following program on two different machines : On one machine , with .NET 4.5 and Visual Studio 2012 installed this prints `` true '' , on another one , with .NET Framework 4.6.2 and Visual Studio 2015 it prints `` false '' .I thought that anonymous methods were static if they are defined in a static context . Did this change ( in a documented way ) during some of the last framework updates ? What I need to do , is to use Expression.Call on lambda.GetMethodInfo ( ) , and in the non-static case this requires an instance on which the lambda is defined . If I wanted to use lambda.GetMethodInfo ( ) .Invoke I would face the same problem.How can I get such an instance ? <code> static class Program { static void Main ( string [ ] args ) { Func < int > lambda = ( ) = > 5 ; Console.WriteLine ( lambda.GetMethodInfo ( ) .IsStatic ) ; Console.ReadLine ( ) ; } } | Anonymous method in static class is non-static ? How to invoke it ? |
C_sharp : I want to convert a DateTime ? to string . If a date is null then return `` '' , else return a string format like this : `` 2020-03-05T07:52:59.665Z '' . The code is something like this but it wo n't work . It said `` DateTime ? '' do not contain a definition for `` ToUniversalTime '' . Someone know how to fix this ? <code> DateTime ? date = DateTime.UtcNow ; var dateInUTCString = date == null ? `` '' : date.ToUniversalTime ( ) .ToString ( `` yyyy'-'MM'-'dd'T'HH ' : 'mm ' : 'ss ' . 'fff ' Z ' '' ) ; | Convert DateTime ? to string |
C_sharp : Just for fun I built a quicksort implementation in C # with Linq : It sorts 10000 random integers in about 13 seconds.Changing it to use int [ ] instead of List results in about 700 times better performance ! It only takes 21ms to sort the same 10000 random integers . Just looking at the code I would have assumed this would have worseperformance . I assumed that .ToArray ( ) would create an additional array in memory and copy all integers there.I think passing an array vs. passing a list should take about the same time.So where does this huge performance difference come from ? <code> public static IEnumerable < T > quicksort < T > ( IEnumerable < T > input ) where T : IComparable < T > { if ( input.Count ( ) < = 1 ) return input ; var pivot = input.FirstOrDefault ( ) ; var lesser = quicksort ( input.Skip ( 1 ) .Where ( i = > i.CompareTo ( pivot ) < = 0 ) ) ; var greater = quicksort ( input.Where ( i = > i.CompareTo ( pivot ) > 0 ) ) ; return lesser.Append ( pivot ) .Concat ( greater ) ; } public static T [ ] quicksortArray < T > ( T [ ] input ) where T : IComparable < T > { if ( input.Count ( ) < = 1 ) return input ; var pivot = input.FirstOrDefault ( ) ; var lesser = quicksortArray ( input.Skip ( 1 ) .Where ( i = > i.CompareTo ( pivot ) < = 0 ) .ToArray ( ) ) ; var greater = quicksortArray ( input.Where ( i = > i.CompareTo ( pivot ) > 0 ) .ToArray ( ) ) ; return lesser.Append ( pivot ) .Concat ( greater ) .ToArray ( ) ; } | Quicksort with Linq performance Advantage passing T [ ] vs. IEnumerable < T > |
C_sharp : We have several modules in our software that ship as a single product . When a module is activated , those features become available . We would like our OData APIs to follow the same pattern . However I ca n't figure out how to make the $ metadata ignore controllers for modules that have been disabled . Basically I want to determine what is available at any time instead of application start time . We are using the following type of cod to register the routes : So we only want Module1Entity to show up in the metadata if the module has been activated . We already have code to disable the associated controller when the module is deactivated.Any ideas ? <code> static public void Register ( HttpConfiguration config ) { config.MapHttpAttributeRoutes ( ) ; var builder = new ODataConventionModelBuilder ( ) ; builder.EntitySet < Module1Entity > ( `` Module1Entities '' ) ; builder.EntitySet < Module2Entity > ( `` Module2Entities '' ) ; config.MapODataServiceRoute ( `` odata '' , `` api '' , builder.GetEdmModel ( ) ) ; } protected void Application_Start ( object sender , EventArgs e ) { GlobalConfiguration.Configure ( Register ) ; } | Disabling OData V4 meta data and controllers at runtime |
C_sharp : The following short but complete example programwith T replaced by the following typesyields the following interesting results on my machine ( Windows 7 .NET 4.5 32-bit ) Question 1 : Why is ComplexClass so much slower than SimpleClass ? The elapsed time seems to increase linearly with the number of fields in the class . Writing to the first field of a class with a lot of fields should n't be very different from writing to the first field of a class with only one field , no ? Question 2 : Why is ComplexStruct slower than SimpleStruct ? A look at the IL code shows that i is written directly to the array , not to a local instance of ComplexStruct that is then copied into the array . So there should be no overhead caused by copying more fields.Bonus question : Why is ComplexStruct faster than ComplexClass ? Edit : Updated test results with a smaller array , T [ ] array = new T [ 1 < < 8 ] ; : So virtually no difference between SimpleClass and ComplexClass , and only a small difference between SimpleStruct and ComplexStruct . However , the performance significantly decreased for SimpleClass and SimpleStruct . Edit : And now with T [ ] array = new T [ 1 < < 16 ] ; : The result for 1 < < 15 is like 1 < < 8 , and the result for 1 < < 17 is like 1 < < 20 . <code> const long iterations = 1000000000 ; T [ ] array = new T [ 1 < < 20 ] ; for ( int i = 0 ; i < array.Length ; i++ ) { array [ i ] = new T ( ) ; } Stopwatch sw = Stopwatch.StartNew ( ) ; for ( int i = 0 ; i < iterations ; i++ ) { array [ i % array.Length ] .Value0 = i ; } Console.WriteLine ( `` { 0 , -15 } { 1 } { 2 : n0 } iterations/s '' , typeof ( T ) .Name , sw.Elapsed , iterations * 1000d / sw.ElapsedMilliseconds ) ; class SimpleClass struct SimpleStruct { { public int Value0 ; public int Value0 ; } } class ComplexClass struct ComplexStruct { { public int Value0 ; public int Value0 ; public int Value1 ; public int Value1 ; public int Value2 ; public int Value2 ; public int Value3 ; public int Value3 ; public int Value4 ; public int Value4 ; public int Value5 ; public int Value5 ; public int Value6 ; public int Value6 ; public int Value7 ; public int Value7 ; public int Value8 ; public int Value8 ; public int Value9 ; public int Value9 ; public int Value10 ; public int Value10 ; public int Value11 ; public int Value11 ; } } SimpleClass 00:00:10.4471717 95,721,260 iterations/sComplexClass 00:00:37.8199150 26,441,736 iterations/sSimpleStruct 00:00:12.3075100 81,254,571 iterations/sComplexStruct 00:00:32.6140182 30,661,679 iterations/s SimpleClass 00:00:13.5091446 74,024,724 iterations/sComplexClass 00:00:13.2505217 75,471,698 iterations/sSimpleStruct 00:00:14.8397693 67,389,986 iterations/sComplexStruct 00:00:13.4821834 74,172,971 iterations/s SimpleClass 00:00:09.7477715 102,595,670 iterations/sComplexClass 00:00:10.1279081 98,745,927 iterations/sSimpleStruct 00:00:12.1539631 82,284,210 iterations/sComplexStruct 00:00:10.5914174 94,419,790 iterations/s | Field access through array is slower for types with more fields |
C_sharp : I 'm working with an external library that has an enum . There are some members of this enum that , when you call ToString ( ) on them , return the name of a different member of the enum.I know that when two enum members have the same numerical value , you can get behavior like this , but I know , from decompilation and checking the values at run-time , that each member in the enum has a unique value.Here 's a snippet of the enum 's definition ( generated by dotPeek ) : Why is this happening ? Is there something I 'm doing wrong , or is this just another one of those fun quirks of enums in .NET ? If the latter , is there a workaround for it ? ( For what it 's worth , Tokens is part of of the Microsoft.SqlServer.Management.SqlParser.Parser namespace in .NET . ) <code> Console.WriteLine ( `` TOKEN_RIGHT = { 0 } '' , Tokens.TOKEN_RIGHT.ToString ( ) ) ; //prints TOKEN_OUTERConsole.WriteLine ( `` TOKEN_FROM = { 0 } '' , Tokens.TOKEN_FROM.ToString ( ) ) ; //prints TOKEN_FROMConsole.WriteLine ( `` TOKEN_OUTER = { 0 } '' , Tokens.TOKEN_OUTER.ToString ( ) ) ; //prints TOKEN_FULL public enum Tokens { TOKEN_OR = 134 , TOKEN_AND = 135 , TOKEN_NOT = 136 , TOKEN_DOUBLECOLON = 137 , TOKEN_ELSE = 138 , TOKEN_WITH = 139 , TOKEN_WITH_CHECK = 140 , TOKEN_GRANT = 141 , TOKEN_CREATE = 142 , TOKEN_DENY = 143 , TOKEN_DROP = 144 , TOKEN_ADD = 145 , TOKEN_SET = 146 , TOKEN_REVOKE = 147 , TOKEN_CROSS = 148 , TOKEN_FULL = 149 , TOKEN_INNER = 150 , TOKEN_OUTER = 151 , TOKEN_LEFT = 152 , TOKEN_RIGHT = 153 , TOKEN_UNION = 154 , TOKEN_JOIN = 155 , TOKEN_PIVOT = 156 , TOKEN_UNPIVOT = 157 , TOKEN_FROM = 242 , } | Why does Enum.ToString ( ) not return the correct enum name ? |
C_sharp : Let 's say I have an interface like that : Is there any way to implement the DoSomething method with type constraint ? Obviously , this wo n't work : This obviously wo n't work because this DoSomething ( ) wo n't fully satisfy the contract of IAwesome - it only work for a subset of all possible values of the type parameter T. Is there any way to get this work short of some `` casting black magic '' ( which is what I 'm going to do as last resort if the answer is no ) ? Honestly , I do n't think it 's possible but I wonder what you guys think.EDIT : The interface in question is System.Linq.IQueryProvider so I ca n't modify the interface itself . <code> interface IAwesome { T DoSomething < T > ( ) ; } class IncrediblyAwesome < T > : IAwesome where T : PonyFactoryFactoryFacade { public T DoSomething ( ) { throw new NotImplementedException ( ) ; } } | Type constraints on implementations of generic members of non-generic interfaces in C # |
C_sharp : I 'm working on project in which I 'm Posting data from asp.net webform to WCF service . I 'm posting data through params and the service respond me back a JSON string . Now I have an issue in deserialize . I read many threads but did n't find any solution . Hope someone can sort out my problem . Thanks in AdvanceResponse from WCF { `` LoginResult '' : false } I just want `` false '' value.How I tried : <code> string URL = `` http : //localhost:32319/ServiceEmployeeLogin.svc '' ; WebRequest wrGETURL ; wrGETURL = WebRequest.Create ( URL+ '' / '' +emp_username+ '' / '' +emp_password+ '' / '' +emp_type ) ; wrGETURL.Method = `` POST '' ; wrGETURL.ContentType = @ '' application/json ; charset=utf-8 '' ; HttpWebResponse webresponse = wrGETURL.GetResponse ( ) as HttpWebResponse ; Encoding enc = System.Text.Encoding.GetEncoding ( `` utf-8 '' ) ; // read response stream from response object StreamReader loResponseStream = new StreamReader ( webresponse.GetResponseStream ( ) , enc ) ; // read string from stream data strResult = loResponseStream.ReadToEnd ( ) ; var jObj = JObject.Parse ( strResult ) ; var dict = jObj [ `` LoginResult '' ] .Children ( ) .Cast < JProperty > ( ) ; | How to Deserialize JSON |
C_sharp : I found with or without flags attributes , I can do bit operation if I defined the following enumI am wondering why we need flags attribute ? <code> enum TestType { None = 0x0 , Type1 = 0x1 , Type2 = 0x2 } | Is flags attribute necessary ? |
C_sharp : I have a generic class A < T > , that implements IEnumerable < T [ ] > .I want to have a convenience wrapper B that inherits from A < char > and implements IEnumerable < string > .Now , this works perfectly fine , foreach variable type is inferred to be string : But this wo n't compile , saying `` The type arguments can not be inferred from usage , try specifying the type arguments explicitly '' : However , this works : Can anyone explain this compiler behavior ? Obviously , B implements both IEnumerable < char [ ] > and IEnumerable < string > and probably it ca n't figure out which of them I want to call , but why it works fine in `` foreach '' sample ? Please , do n't suggest me to solve my problem by composition - this is the last resort for me . <code> public class A < T > : IEnumerable < T [ ] > { public IEnumerator < T [ ] > GetEnumerator ( ) { return Enumerate ( ) .GetEnumerator ( ) ; } IEnumerator IEnumerable.GetEnumerator ( ) { return GetEnumerator ( ) ; } protected IEnumerable < T [ ] > Enumerate ( ) { throw new System.NotImplementedException ( ) ; } } public class B : A < char > , IEnumerable < string > { public IEnumerator < string > GetEnumerator ( ) { return Enumerate ( ) .Select ( s = > new string ( s ) ) .GetEnumerator ( ) ; } IEnumerator IEnumerable.GetEnumerator ( ) { return GetEnumerator ( ) ; } } B b = new B ( ) ; foreach ( var s in b ) { string [ ] split = s.Split ( ' ' ) ; } string [ ] strings = b.ToArray ( ) ; string [ ] strings = b.ToArray < string > ( ) ; | Multiple IEnumerable implementations paradox |
C_sharp : I just established a connection to SWI Prolog and want to manipulate facts . e.g . retract and assert them.I have some function like this : As you can see this function , it 's working for assertion as expected , but not for retract . The matter is that , I want to delete all tablets facts ( they are dynamic ) from file before inserting the next ones . PlQuery.PlCall ( `` retractall ( tablet/2 ) . `` ) ; this query must delete all record that are in the file . and also how to delete a fact for example tablet ( 4 , newatomic ) , but not to delete another facts.The resulting file after execution is : <code> String [ ] param = { `` -q '' } ; PlEngine.Initialize ( param ) ; PlQuery.PlCall ( `` consult ( 'tablets.pl ' ) . `` ) ; PlQuery.PlCall ( `` assert ( tablet ( 4 , newatomic ) ) . `` ) ; PlQuery.PlCall ( `` tell ( 'tablets.pl ' ) , listing ( tablet/2 ) , told . `` ) ; PlQuery.PlCall ( `` retractall ( tablet/2 ) . `` ) ; PlQuery.PlCall ( `` assert ( tablet ( 1 , n1ewatomic ) ) . `` ) ; PlQuery.PlCall ( `` assert ( tablet ( 2 , n2ewatomic ) ) . `` ) ; PlQuery.PlCall ( `` tell ( 'tablets.pl ' ) , listing ( tablet/2 ) , told . `` ) ; : - dynamic tablet/2.tablet ( 4 , newatomic ) .tablet ( 1 , n1ewatomic ) .tablet ( 2 , n2ewatomic ) . | Prolog C # Interface retract from file |
C_sharp : I 'm trying to hold in memory a collection of references of type Action < T > where T is variable type I 've found a solution with dynamic but I would prefer not to use dynamic the solutionDoes anyone know a better approach to handling this ? Thanks in advance . <code> public class MessageSubscriptor : IMessageSubscriptorPool { Dictionary < Type , Action < dynamic > > Callbacks = new Dictionary < Type , Action < dynamic > > ( ) ; public void Subscribe < T > ( Action < T > callback ) where T : IMessage { Callbacks.Add ( typeof ( T ) , ( obj ) = > callback ( obj ) ) ; } } | Storing Action < T > in a single collection for later usage |
C_sharp : This is extremely slow : This is about 5x faster : Can anybody tell me why ? <code> try { x = k / y ; } catch ( DivideByZeroException ) { } if ( y > 0 ) x = k / y ; | DivideByZeroException too slow |
C_sharp : I have to query collection like this : s.CountryCode above is an example . I want to make it variable and call for different columns , like this : So I would like to define function where the column expression is a parameter . What is the signature of such function ? myList is an ObservableCollection , and myFilters is List < string > <code> myList.Where ( s = > myFilters.Contains ( s.CountryCode ) ) myList.Where ( s = > myFilters.Contains ( s.City ) ) myList.Where ( s = > myFilters.Contains ( s.Region ) ) myList.Where ( s = > myFilters.Contains ( s.Zipcode ) ) public void MySelect ( ? ? ? ) { myList.Where ( s = > myFilters.Contains ( ? ? ? ) ; } | linq expression as parameter |
C_sharp : I have a marker interface something like this : And i want to apply it to methods on different classes in different assemblies ... Then I want to Get a MethodInfo for all methods that have this attribute applied . I need to search the whole AppDomain and get a reference to all these methods . I know we can get all types and then get all methods , but is there a quicker/better way to do this ? ... or is this the quickest manner to get the information I need ? ( I 'm using ASP.NET MVC 1.0 , C # , ./NET 3.5 ) Thanks heaps ! <code> [ AttributeUsage ( AttributeTargets.Method , AllowMultiple=false , Inherited=true ) ] public class MyAttribute : Attribute { } | Is there a quicker/better way to get Methods that have attribute applied in C # |
C_sharp : Put default ( T ) in an interface . Explicitly implement the interface . The result does not compileI fully expect default ( ConcreteWhatever ) . What I get is default ( T ) which results in a compilation error . I just go in and replace default ( T ) with null and things are fine . But this is hideous . Why is this happening ? <code> public interface IWhatever < T > { List < T > Foo ( T BarObject = default ( T ) ) ; } public class ConcreteWhatever : IWhatever < ConcreteWhatever > { List < ConcreteWhatever > Foo ( ConcreteWhatever BarObject = default ( T ) ) { } } | C # - How are we supposed to implement default ( T ) in Interfaces ? |
C_sharp : A bit of a conceptual question : I 'm creating my custom structure , in the vein of a Vector3 ( 3 int values ) and I was working through overloading the standard operators ( + , - , * , / , == etc ... ) As I 'm building a library for external use , I 'm attempting to conform to FxCop rules . As such , they recommend having methods that perform the same function.Eg . .Add ( ) , .Subtract ( ) , etc ... To save on code duplication , one of these methods ( the operator overload , or the actual method ) is going to call the other one.My question is , which should call which ? Is it ( and this is only an example code ) : A ) or : B ) I 'm really not sure either is preferable , but I 'm looking for some opinions : ) <code> public static MyStruct operator + ( MyStruct struc1 , MyStruct struct2 ) { return struc1.Add ( struct2 ) ; } public MyStruct Add ( MyStruct other ) { return new MyStruct ( this.X + other.X , this.Y + other.Y , this.Z + other.Z ) ; } public static MyStruct operator + ( MyStruct struc1 , MyStruct struct2 ) { return new MyStruct ( struct1.X + struct2.X , struct1.Y + struct2.Y , struct1.Z + struct2.Z ) ; } public MyStruct Add ( MyStruct other ) { return this + other ; } | Operator Overloading in C # - Where should the actual code code go ? |
C_sharp : Here is a simplified function that I want to create : In that code block , I get the compiler error : Error CS0029 Can not implicitly convert type 'System.Collections.Generic.List < > ' to 'System.Collections.Generic.List'In the documentation for Anonymous types , it says that anonymous types are treated as type object . Why does n't the C # compiler return a List < object > on names.ToList ( ) ? Further more , why does n't the following code cause an error ? If List < < anonymous type : string FirstName > > can not be converted to List < object > , then why can it be converted to IEnumberable < object > ? <code> static List < object > GetAnonList ( IEnumerable < string > names ) { return names.Select ( name = > new { FirstName = name } ) .ToList ( ) ; } static IEnumerable < object > GetAnonList ( IEnumerable < string > names ) { return names.Select ( name = > new { FirstName = name } ) .ToList ( ) ; } | Why does n't IEnumerable of anonymous types return a List < object > on ToList ( ) ? |
C_sharp : I know I ca n't overload a return type ( I think I know this ) ... produces error already defines a member called ' F ' with the same parameter typesHowever , I 'm reading the documentation for ISet from MSDN , and I think I see the two Add methods that only vary by return type.What is going on here ? <code> void F ( ) { } bool F ( ) { return true ; } | How does ISet have two Add ( T item ) methods that vary only by return type ? |
C_sharp : I am trying to use the following custom task scheduler to limit concurrent web requests : I 'm using it like this : The problem is that the inner tasks are using my LimitedConcurrencyLevelTaskScheduler instead of the default TaskScheduler . This leads to self blocking and the output is like this : When I change the CONCURRENCY_LEVEL to 3 or change the factory to Task.Factory then obviously everything is working fine and the output is like : I can not change the code in SomeAction . What else can I do ? Is there a bug in the Microsoft sample ? <code> const int CONCURRENCY_LEVEL = 2 ; static void Main ( ) { TaskFactory factory = new TaskFactory ( new LimitedConcurrencyLevelTaskScheduler ( CONCURRENCY_LEVEL ) ) ; Task.WaitAll ( new [ ] { factory.StartNew ( ( ) = > SomeAction ( `` first '' ) ) , factory.StartNew ( ( ) = > SomeAction ( `` second '' ) ) } ) ; Console.WriteLine ( `` All tasks ended '' ) ; Console.Read ( ) ; } static void SomeAction ( string task ) { Console.WriteLine ( task + `` task started '' ) ; Console.WriteLine ( AnotherTask ( task ) .Result ) ; Console.WriteLine ( task + `` task ended '' ) ; } static async Task < string > AnotherTask ( string task ) { return await Task.Run ( ( ) = > { Console.WriteLine ( task + `` inner task started '' ) ; // imitate web requests Thread.Sleep ( 200 ) ; Console.WriteLine ( task + `` inner task ended '' ) ; return `` ok '' ; } ) ; } second task startedfirst task startedfirst inner task startedsecond inner task startedsecond inner task endedfirst inner task ended first task startedsecond task startedfirst inner task startedsecond inner task startedsecond inner task endedfirst inner task endedoksecond task endedokfirst task endedAll tasks ended | TaskScheduler with limited concurrency blocks itself |
C_sharp : I am trying to format some precise dates , converting them from a Unix timestamp to a DateTime object . I noticed that the AddSeconds method has an overload that accepts a floating point number.My expectation is that I may pass in a number such as 1413459415.93417 and it will give me a DateTime object with tick-level precision . Is this a decent assumption , or does the AddSeconds method still provide no better than millisecond precision ? In the conversion , do I have to add the ticks myself ? My conversion code is below : I expect to format the ToString of this date like 16 Oct 2014 11:36:55.93417 using the format string below : Instead of giving me 16 Oct 2014 11:36:55.93417 , it is giving me 16 Oct 2014 11:36:55.93400Am I doing something wrong or is .NET truncating my floating-point seconds representation ? I am new to .NET , so the former is quite possible.Thanks <code> public static DateTime CalendarDateFromUnix ( double unixTime ) { DateTime calendarTime = UnixEpoch.AddSeconds ( unixTime ) ; return calendarTime ; } dd MMM yyyy HH : mm : ss.fffff | Is .NET DateTime truncating my seconds ? |
C_sharp : I have two questions : 1 ) What is the fastest algorithm to put this list in a `` connecting '' order ? 2 ) Is this an existing problem/algorithm , and what name does it have ? The nodes are always connected in a circular fashion , so my starting ID does not matter . Given this list : node1 & node2 are not in a specific order so id A can be 4 - 9 as well as 9 - 4.The output should be this ( it does n't matter if it starts with A , as long as the output is a chain ) . ( I am writing my code in C # . But pseudo code in any language will do ) <code> id node1 node2A 4 9B 6 1C 1 3D 3 10E 7 2F 4 2G 9 8H 10 5I 7 5J 6 8 node ids : 4 - 9 - 8 - 6 - 1 - 3 - 10 - 5 - 7 - 2 - 4ids : A G J B C D H I E F | Fastest algorithm for a 'circular linked list builder ' |
C_sharp : I want to upload a file ( VideoFile ) to server through BackgroundTransferService.My problem is , I also want to send 2 parameters along with File ( POST request ) .So , is it possible to send parameters along with File upload while using BackgroundTransferService API.. ? Code with BackgroundTransferService : Please ask if anyone wants more info and unable to understand my question.I want a quick response . Yes or No.. and if Yes then How.. ? <code> BackgroundTransferRequest req = new BackgroundTransferRequest ( new Uri ( `` ServerURL '' , UriKind.Absolute ) ) ; req.Method = `` POST '' ; req.TransferPreferences = TransferPreferences.AllowCellularAndBattery ; string uploadLocationPath = `` /Shared/Transfers/myVideoFile.mp4 '' ; string downloadLocationPath = `` /Shared/Transfers/response.txt '' ; req.UploadLocation = new Uri ( uploadLocationPath , UriKind.Relative ) ; req.DownloadLocation = new Uri ( downloadLocationPath , UriKind.Relative ) ; req.TransferProgressChanged += req_TransferProgressChanged ; req.TransferStatusChanged += req_TransferStatusChanged ; try { BackgroundTransferService.Add ( req ) ; } catch ( Exception ex ) { MessageBox.Show ( `` Unable to add video to upload queue.\nPlease try again later . `` , App.appName , MessageBoxButton.OK ) ; } | BackgroundTransferService with POST method and Parameters |
C_sharp : So here 's what I 'm looking to achieve . I would like to give my users a single google-like textbox where they can type their queries . And I would like them to be able to express semi-natural language such asit 's ok if the syntax has to be fairly structured and limited to this specific domain ... these are expert users who will be using this.Ultimately , I think I 'd like the parse results to be available as some sort of expression tree . But if you 've got some other ideas about what data structure might be better.This is in C # : - ) <code> `` view all between 1/1/2008 and 1/2/2008 '' | Parsing a User 's Query |
C_sharp : I have a class library with numerous EF6 entities . I generated a NuGet from this library . Whenever I reference the library directly only the DLL is placed in the bin , however when I install the library via NuGet it copies over the entities *Content.tt and *.tt files into a folder in the project.I have a couple of questions around this difference : Why does the NuGet require these files present when a reference to the project does not ? Is there a need for these entity files or am I able to force the NuGet to not clone these files over when installed ? My .nuspec file is standard like follows : The commands I am using to generate the package are : c : \nuget.exe pack MYID.csproj -IncludeReferencedProjects -PropPlatform=AnyCPUc : \nuget.exe add MYID.1.0.0.nupkg -Source M : \Dev\NuGetPackages <code> < ? xml version= '' 1.0 '' ? > < package > < metadata > < id > MYID < /id > < version > 12.0.2 < /version > < title > MYTITLE < /title > < authors > MYNAME < /authors > < owners > < /owners > < requireLicenseAcceptance > false < /requireLicenseAcceptance > < description < /description > < releaseNotes > < /releaseNotes > < copyright > Copyright 2017 < /copyright > < tags > < /tags > < /metadata > < /package > | NuGet vs Direct Reference of Class w/ EF6 Entities |
C_sharp : I have a string like this : I want to do a replacement on this string such that each word ( case-insensitive ) will be matched , and replaced with a numbered index span tag like so : I tried doing it like this.The output is something like this : Where all the ids are the same ( m_1 ) because the regex does n't evaluate match++ for each match , but one for the whole Regex . How do I get around this ? <code> string s = `` < p > Hello world , hello world < /p > '' ; string [ ] terms = new string [ ] { `` hello '' , `` world '' } ; < p > < span id= '' m_1 '' > Hello < /span > < span id= '' m_2 '' > world < /span > , < span id= '' m_3 '' > hello < /span > < span id= '' m_4 '' > world < /span > ! < /p > int match = 1 ; Regex.Replace ( s , String.Join ( `` | '' , String.Join ( `` | '' , terms.OrderByDescending ( s = > s.Length ) .Select ( Regex.Escape ) ) ) , String.Format ( `` < span id=\ '' m_ { 0 } \ '' > $ & < /span > '' , match++ ) , RegexOptions.IgnoreCase ) ; < p > < span id= '' m_1 '' > Hello < /span > < span id= '' m_1 '' > world < /span > , < span id= '' m_1 '' > hello < /span > < span id= '' m_1 '' > world < /span > ! < /p > | C # Regex change replacement string for each match |
C_sharp : I 'm toying around with the idea of using C # 's ability to compile code on-demand as the basis of a scripting language . I was wondering , how can I sandbox the scripts that I am executing so that they can not access the file system , network , etc . Basically , I want restricted permissions on the script being run.Steps that I take : <code> CompilerResults r = CSharpCodeProvider.CompileAssemblyFromSource ( source ) ; Assembly a = r.CompiledAssembly ; IScript s = a.CreateInstance ( ... ) ; s.EntryPoint ( ... ) ; | Assembly.CreateInstance and security |
C_sharp : I was trying to create my own factorial function when I found that the that the calculation is twice as fast if it is calculated in pairs . Like this : Groups of 1 : 2*3*4 ... 50000*50001 = 4.1 secondsGroups of 2 : ( 2*3 ) * ( 4*5 ) * ( 6*7 ) ... ( 50000*50001 ) = 2.0 secondsGroups of 3 : ( 2*3*4 ) * ( 5*6*7 ) ... ( 49999*50000*50001 ) = 4.8 secondsHere is the c # I used to test this.I tested this at different levels and put the average times over a few tests in a bar graph . I expected it to become more efficient as I increased the number of groups , but 3 was the least efficient and 4 had no improvement over groups of 1.Link to First DataLink to Second DataWhat causes this difference , and is there an optimal way to calculate this ? <code> Stopwatch timer = new Stopwatch ( ) ; timer.Start ( ) ; // Seperate the calculation into groups of this size.int k = 2 ; BigInteger total = 1 ; // Iterates from 2 to 50002 , but instead of incrementing ' i ' by one , it increments it ' k ' times , // and the inner loop calculates the product of ' i ' to ' i+k ' , and multiplies 'total ' by that result.for ( var i = 2 ; i < 50000 + 2 ; i += k ) { BigInteger partialTotal = 1 ; for ( var j = 0 ; j < k ; j++ ) { // Stops if it exceeds 50000. if ( i + j > = 50000 ) break ; partialTotal *= i + j ; } total *= partialTotal ; } Console.WriteLine ( timer.ElapsedMilliseconds / 1000.0 + `` s '' ) ; | Why is it faster to calculate the product of a consecutive array of integers by performing the calculation in pairs ? |
C_sharp : I have a Main method like this : Since I am accessing a local variable b here the compiler creates a class to capture that variable and b becomes the field of that class . Then the b lives as long as the life time of the compiler generated class and it causes a memory leak . Even if b goes out of scope ( maybe not in this situation but imagine this is inside of another method and not Main ) , the byte array wo n't be deallocated.What I wonder is , since I am not accessing or modifying the b anywhere after declaring Func , why ca n't the compiler inline that local variable and not bother with creating a class ? Like this : I compiled this code in Debug and Release modes , the DisplayClass is generated in both : Is this just not implemented as an optimization or is there anything I am missing ? <code> static void Main ( string [ ] args ) { var b = new byte [ 1024 * 1024 ] ; Func < double > f = ( ) = > { new Random ( ) .NextBytes ( b ) ; return b.Cast < int > ( ) .Average ( ) ; } ; var avg = f ( ) ; Console.WriteLine ( avg ) ; } Func < double > f = ( ) = > { var b = new byte [ 1024 * 1024 ] ; new Random ( ) .NextBytes ( b ) ; return b.Cast < int > ( ) .Average ( ) ; } ; | Why ca n't the compiler optimize closure variable by inlining ? |
C_sharp : I have the following entities : An account class with a list of subscriptions : the subscription class with a list of variations and add ons : the add on class with a list of variations : And the variation class : What I 'm trying to do is to group all add ons with specific Code and sum the quantity . For example I tried : This one correct groups add ons but I want a list with with add ons per subscription group by code and total quantity per code.For example if a Subscription has X number of add ons and the Code of each add on is 1 , 2 , ... , X , I want to group by the add ons by Code and total Quantity with this Code . I expect the result will be something like if I have the following structure : A pseudo-code with current structure ( Code refers to Variation Class that each add on has ) : What I expect : You can use this dotnetfiddle to test dummy data . Sorry for the long post and I will appreciate any help . Also keep in mind my c # and Linq knowledge is limited . <code> public class Account { /// < summary > /// Account ID /// < /summary > public string ID { get ; set ; } /// < summary > /// A List with all subscriptions /// < /summary > public IEnumerable < Subscription > Subscriptions { get ; set ; } } public class Subscription { /// < summary > /// Subscription ID /// < /summary > public string ID { get ; set ; } /// < summary > /// Quantity of the subscription . /// < /summary > public int Quantity { get ; set ; } /// < summary > /// A list with all subscription add ons /// < /summary > public IEnumerable < AddOn > AddOns { get ; set ; } /// < summary > /// A List with all subscription variations /// < /summary > public IEnumerable < Variation > Variations { get ; set ; } } public class AddOn { /// < summary > /// Gets or Sets add on id /// < /summary > public string ID { get ; set ; } /// < summary > /// Quantity of the add on . /// < /summary > public int Quantity { get ; set ; } /// < summary > /// A List with all add on variations /// < /summary > public IEnumerable < Variation > Variations { get ; set ; } } public class Variation { /// < summary > /// Variation ID /// < /summary > public string ID { get ; set ; } /// < summary > /// offerUri /// < /summary > public string Code { get ; set ; } /// < summary > /// Variation Value /// < /summary > public string Value { get ; set ; } /// < summary > /// Variation Name /// < /summary > public string Name { get ; set ; } } var groupAddOnsByCode = acc.Subscriptions.Select ( s = > s.AddOns.GroupBy ( a = > a.Variations.Select ( v = > v.Code ) .FirstOrDefault ( ) ) ) .ToList ( ) ; Subscription { //a list with X number of add ons AddOn1 = { Variation = { Code = 1 } , Quantity = 2 } , AddOn2 = { Variation = { Code = 2 } , Quantity = 3 } , ... AddOnX = { Variation = { Code = X } , Quantity = 4 } } Subscription { AddOn1 { Variation = { Code = 1 } , Quantity = totalAmountOfQuantityForAddOnsWithCode = 1 } , ... AddOnX { Variation = { Code = X } , Quantity = totalAmountOfQuantityForAddOnsWithCode = X } , } | Linq Group by and sum problems |
C_sharp : I want to create a new group when the difference between the values in rows are greater then five.Example : should give me 3 groups : Is it possible to use Linq here ? Thx ! <code> int [ ] list = { 5,10,15,40,45,50,70,75 } ; 1 , [ 5,10,15 ] 2 , [ 40,45,50 ] 3 , [ 70,75 ] | How can I group by the difference between rows in a column with linq and c # ? |
C_sharp : Databound to an ObservableCollection , I am filling an ItemsControl with Buttons . I am using UniformGrid to help evenly spread things out whether there are 5 or 5000 objects in the ObservableCollection . Desire : After the user searches/filters the ObservableCollection , I would like to update an IsVisible property on items to show/hide them ... while also consolidating the space.Rationale : I figured , performance wise , updating a property would be better than doing a Clear ( ) and loop to re-add the filtered items back to the databound ObservableCollection.Problem : While the current implementation ( code below ) does visibly hide the buttons , the space they take up still is present regardless of which Visibility property I try to use.Disclaimer : I am open to more than just simply `` fixing '' my current code . For example , if a viable solution does not use UniformGrid for example but still achieves a sustainable result , I can probably use it ! The same is true on the ViewModel side.Update : I did not simply copy and paste the entire answer.In the code above , at Button , inside of the DataTemplate , I removed the Visibility line.I only added the following code : <code> < ItemsControl Name= '' ItemsList '' Width= '' Auto '' HorizontalContentAlignment= '' Left '' ItemsSource= '' { Binding ItemsVM.WorkList } '' ScrollViewer.CanContentScroll= '' True '' VirtualizingStackPanel.IsVirtualizing= '' true '' VirtualizingStackPanel.VirtualizationMode= '' Standard '' > < ItemsControl.ItemsPanel > < ItemsPanelTemplate > < UniformGrid Columns= '' 5 '' / > < /ItemsPanelTemplate > < /ItemsControl.ItemsPanel > < ItemsControl.ItemTemplate > < DataTemplate > < Button Width= '' 250 '' Height= '' 50 '' FontSize= '' 18 '' FontWeight= '' Bold '' Background= '' { Binding TextColor , Converter= { StaticResource TextToColorConvert } , UpdateSourceTrigger=PropertyChanged } '' Margin= '' 1,1,1,1 '' HorizontalAlignment= '' Center '' VerticalAlignment= '' Center '' BorderBrush= '' WhiteSmoke '' BorderThickness= '' 0 '' Click= '' workNumSelect '' Content= '' { Binding Workload.WorkNum } '' Cursor= '' Hand '' Opacity= '' .8 '' Visibility= '' { Binding IsVisible , Converter= { StaticResource BoolToCollapsedVisConvert } , UpdateSourceTrigger=PropertyChanged } '' / > < /DataTemplate > < /ItemsControl.ItemTemplate > < ItemsControl.Template > < ControlTemplate TargetType= '' ItemsControl '' > < ScrollViewer Width= '' Auto '' VerticalScrollBarVisibility= '' Visible '' > < ItemsPresenter / > < /ScrollViewer > < /ControlTemplate > < /ItemsControl.Template > < /ItemsControl > < ItemsControl.ItemContainerStyle > < Style TargetType= '' ContentPresenter '' > < Style.Triggers > < DataTrigger Binding= '' { Binding IsVisible } '' Value= '' False '' > < Setter Property= '' Visibility '' Value= '' Collapsed '' / > < /DataTrigger > < /Style.Triggers > < /Style > < /ItemsControl.ItemContainerStyle > | WPF - Hide items in ItemControl - > UniformGrid from taking up UI space based on databinding |
C_sharp : In my current application , I have the following MongoDB FindAndModify call to the MongoDB server Am I reinventing yet another queue system with MongoDB ? That 's not my intention here but it 's what it 's . Just ignore the business logic there.In CQRS , Query and Command mean the following ( I believe ) : Command : Changes the state of the system and return no values.Query : Does n't change the state of the system and return some values.If that 's the case , where does my above FindAndModify call ( or any other similar one like this query ) fit ? <code> public static TEntity PeekForRemoveSync < TEntity > ( this MongoCollection < TEntity > collection , string reason ) where TEntity : class , IEntity , IUpdatesTrackable , ISyncable , IDeletable , IApprovable { if ( reason == null ) { throw new ArgumentNullException ( nameof ( reason ) ) ; } IMongoQuery query = Query.And ( Query < TEntity > .EQ ( e = > e.SyncInfo.IsDirty , true ) , Query < TEntity > .NE ( e = > e.Deletion , null ) , Query < TEntity > .NE ( e = > e.Approval , null ) , Query < TEntity > .EQ ( e = > e.SyncInfo.HumanInvestigateFlag , null ) , Query.Or ( Query < TEntity > .EQ ( e = > e.SyncInfo.IsUpdateInProgress , false ) , Query < TEntity > .LT ( e = > e.SyncInfo.UpdateStartInfo.OccuredOn , DateTime.UtcNow.AddSeconds ( -SyncConstants.PeekExpireTimeInSeconds ) ) ) , Query < TEntity > .LTE ( e = > e.SyncInfo.PeekedCount , MaxPeekedCount ) ) ; return PeekForSync ( collection , query , reason ) ; } private static TEntity PeekForSync < TEntity > ( this MongoCollection < TEntity > collection , IMongoQuery query , string reason ) where TEntity : class , IEntity , IUpdatesTrackable , ISyncable , IDeletable { UpdateBuilder < TEntity > update = Update < TEntity > .Inc ( e = > e.SyncInfo.PeekedCount , 1 ) .Set ( e = > e.SyncInfo.UpdateStartInfo , new OccuranceWithReason ( reason ) ) .Set ( e = > e.SyncInfo.IsUpdateInProgress , true ) ; SortByBuilder < TEntity > sort = SortBy < TEntity > .Descending ( e = > e.LastUpdatedOn ) ; FindAndModifyArgs fmArgs = new FindAndModifyArgs { Query = query , Update = update , SortBy = sort , VersionReturned = FindAndModifyDocumentVersion.Modified } ; FindAndModifyResult result = collection.FindAndModify ( fmArgs ) ; return result.ModifiedDocument ! = null ? result.GetModifiedDocumentAs < TEntity > ( ) : null ; } | Where does FindAndModify fit into CQRS ? |
C_sharp : I declare a Byte-Array like this : and assign some values : Now I want to zero the array again and call : which does n't work . The array remains unchanged . Is n't b a value-type array ? <code> Byte [ ] b = new Byte [ 10 ] ; for ( int i=0 ; i < b.Length ; i++ ) { b [ i ] = 1 ; } b.Initialize ( ) ; | C # : Why does n't Initialize work with a Byte-Array ? |
C_sharp : Assume we have this model : I created a extension method for all classes that inherit from AbstractTableReferentielEntity.But for one specific type of AbstractTableReferentielEntity ( like EstimationTauxReussite ) , I would like to perform a specific action , so I created a second extension method.All extensions methods are declared in the same namespace.After that , I retrieve some data from a DB with Entity Framework : It compiles.When T at runtime is a EstimationTauxReussite type , it goes into the wrong method ToEntityItem when I call Select ( item = > item.ToEntityItem ( ) ) . It does n't go into the most specific extension method . Any ideas ? <code> public abstract class AbstractTableReferentielEntity { } public class EstimationTauxReussite : AbstractTableReferentielEntity { } public static EntityItemViewModel ToEntityItem < T > ( this T entity ) where T : AbstractTableReferentielEntity { } public static EntityItemViewModel ToEntityItem ( this EstimationTauxReussite entity ) { } protected List < EntityItemViewModel > GetAllActifEntityItem < T > ( ) where T : AbstractTableReferentielEntity { return Context .Set < T > ( ) .Where ( item = > item.IsActif ) .Select ( item = > item.ToEntityItem ( ) ) .ToList ( ) ; } | Extension methods with interface |
C_sharp : I 'm currently working on a desktop tool in .NET Framework 4.8 that takes in a list of images with potential cracks and uses a model trained with ML.Net ( C # ) to perform crack detection . Ideally , I 'd like the prediction to take less than 100ms on 10 images ( Note : a single image prediction takes between 36-41ms ) .At first , I tried performing multiple predictions in different threads using a list of PredictionEngines and a Parallel.For-loop ( using a list of threads since there is no PredictionEnginePool implementation for .Net Framework ) . I later learned that using an ITransformer to do predictions is a recommended , thread-safe , approach for .Net Framework and moved to using that , but in both cases it did not give me the performance I was hoping for.It takes around 255-281ms ( 267.1ms on average ) to execute the following code : Where _LoadedModel is an ITransformer representing the previously trained and loaded model , and inputDataEnumerable is a list of ModelInput which contains two properties : ImageData ( byte [ ] of image data extracted from a png image ) and Label ( string type , set to null ) .I tried to speed up this process by switching the TensorFlow package dependency from SciSharp.TensorFlow.Redist toSciSharp.TensorFlow.Redist-Windows-GPUas described in this tutorial.However , the execution time remained pretty much the same ( average of 262.4ms for 10 images ) . I also tried comparing the training times on a small data set of 5760 images and could n't see much of a difference ( both took about 7min 21s ) .From these results it seemed like it was n't using the GPU , so I first tried deleting the bin folders of my projects and removing the old CPU-oriented tensorflow package ( in case it was a simple build issue ) .When that did n't help , I reinstalled CUDA 10.0 , following instructions described here . I also double checked that CUDA was working properly with my graphics card by running a few of the sample projects ( DeviceQuery , DeviceQueryDrv , and bandwidthTest ) just to be sure the card is actually compatible , and those ran just fine.At this point it seems like I 've set something up wrong or the GPU is just not applicable for my particular use case , but I ca n't pin-point which it is . According to the tutorial I was following , GPU acceleration should be available for predictions , but I 'm not seeing any significant differences in execution time after trying to use the GPU.If anyone has any suggests for further troubleshooting steps I can take , or if they have an idea about where I went wrong , or if they think this is the wrong use case , I 'd greatly appreciate any help/feedback.If it helps , here are some system specs : OS : Windows 10 ProCPU : Intel ( R ) Xeon ( R ) CPU E3-1275 v5 @ 3.60GHzRAM : 16.0 GBGPU : Quadro P1000 ( Installed Driver : version 452.06 ) here are the ML.Packages ( Version ) I 'm running : Microsoft.ML ( v1.5.0 ) Microsoft.ML.ImageAnalytics ( v1.5.0 ) Microsoft.ML.TensorFlow ( v1.5.0 ) Microsoft.ML.Vision ( v1.5.0 ) SciSharp.TensorFlow.Redist-Windows-GPU ( v1.15.1 ) and for GPU support I 've installed CUDA v10.0 along with CUDNN v7.6.4.EditThe issue turned out to not be ML.Net specific , but rather related to TensorFlow.Net . After I updated the SciSharp.TensorFlow.Redist-Windows-GPU to version 2.3.0 ( released 8/31/2020 ) , I updated CUDA to 10.1 , and followed guidance from the TensorFlow.Net GitHub which had some slightly different steps for getting GPU support to work . I can now get the 10 predictions in less than 50ms which is even better than my target . <code> MLContext mlContext = new MLContext ( ) ; IDataView inputData = mlContext.Data.LoadFromEnumerable ( inputDataEnumerable ) ; IDataView results = _LoadedModel.Transform ( inputData ) ; var imageClassificationPredictions = mlContext.Data.CreateEnumerable < ImageClassificationPrediction > ( results , false ) .ToList ( ) ; | C # ML.Net Image classification : Does GPU acceleration help improve the performance of predictions and how can I tell if it is ? |
C_sharp : Causes : Struct member 'Unit.u ' of type 'Unit ' causes a cycle in the struct layout.Butcompiles . I understand the problem I suppose . An endless cycle will be formed when referencing a Unit object since it will have to initialize another member Unit and so on . But why does the compiler restrict the problem just for structs ? Does n't the issue persist for class too ? Am I missing something ? <code> public struct Unit { Unit u ; } public class Unit { Unit u ; } | Why is there no cyclic layout issue for classes in C # ? |
C_sharp : I created a simple UWP application with no code , just XAML.If I zoom in to about US state level , the application will crash with an unhandled exception.The event viewer Application Log shows : I 'm running on Windows 10 Version 20H2 ( OS Build 19042.630 ) .How can I fix or diagnose this crash further ? Update 1I was able to capture the call stack at the time of the crash : Update 2The crash does not occur in Aerial mode : Update 3From Microsoft support , Upon investigation , the Bing Maps UWP control was inadvertently unableto handle a certain condition around the tiles . To mitigate thisissue , our Product Group has initiated rolling back the change thatimpacted this experience . This issue should be beginning to resolvewithin the next hour , if not already . <code> < Grid > < maps : MapControl/ > < /Grid > Faulting module name : ucrtbase.dll , version : 10.0.19041.546 , time stamp : 0x43cbc11dException code : 0xc0000409 ucrtbase.dll ! abort ( ) Unknown ucrtbase.dll ! terminate ( ) Unknown ucrtbase.dll ! __crt_state_management : :wrapped_invoke < void ( * ) ( void ) , void > ( void ( * ) ( void ) ) Unknown BingMaps.dll ! MapControl : :DetailTextureSource : :beginGetTexture ( class MapControl : :TileFrameKey const & , class std : :shared_ptr < class Pal : :AsyncOperationImplementation < class MapControl : :Versioned < class std : :shared_ptr < class Engine : :Texture > > , class std : :shared_ptr < class Pal : :UntypedAsyncOperation > > > const & , class std : :shared_ptr < class MapControl : :TileImage > , class Math : :TileId const & ) Unknown BingMaps.dll ! MapControl : :DetailTextureSource : :childOperationCompleted ( class MapControl : :TileFrameKey const & , class std : :shared_ptr < class Pal : :AsyncOperationImplementation < class MapControl : :Versioned < class std : :shared_ptr < class Engine : :Texture > > , class std : :shared_ptr < class Pal : :UntypedAsyncOperation > > > , class Math : :TileId , class Pal : :AsyncOperation < class std : :shared_ptr < class MapControl : :TileImage > > const & ) Unknown BingMaps.dll ! std : :_Func_impl_no_alloc < class std : :_Binder < struct std : :_Unforced , void ( MapControl : :DetailTextureSource : :* ) ( class MapControl : :TileFrameKey const & , class std : :shared_ptr < class Pal : :AsyncOperationImplementation < class MapControl : :Versioned < class std : :shared_ptr < class Engine : :Texture > > , class std : :shared_ptr < class Pal : :UntypedAsyncOperation > > > , class Math : :TileId , class Pal : :AsyncOperation < class std : :shared_ptr < class MapControl : :TileImage > > const & ) , class MapControl : :DetailTextureSource * , class MapControl : :TileFrameKey const & , class std : :shared_ptr < class Pal : :AsyncOperationImplementation < class MapControl : :Versioned < class std : :shared_ptr < class Engine : :Texture > > , class std : :shared_ptr < class Pal : :UntypedAsyncOperation > > > & , class Math : :TileId const & , struct std : :_Ph < 1 > const & > , void , class Pal : :AsyncOperation < class std : :shared_ptr < class MapControl : :TileImage > > & > : :_Do_call ( class Pal : :AsyncOperation < class std : :shared_ptr < class MapControl : :TileImage > > & ) Unknown BingMaps.dll ! Pal : :AsyncOperation < struct Core : :DummyType > : :callbackFromBaseClass ( void ) Unknown BingMaps.dll ! Pal : :UntypedAsyncOperation : :tryComplete ( class Core : :StatusCode ) Unknown BingMaps.dll ! Pal : :UntypedAsyncOperation : :setSucceededOrFailedInternal ( class Core : :StatusCode ) Unknown BingMaps.dll ! MapControl : :PipelineAsyncSource < class std : :shared_ptr < class MapControl : :TileImage > , class std : :shared_ptr < class Pal : :AsyncOperation < class MapControl : :DownloadedResource > > > : :process ( class MapControl : :TileFrameKey const & , class std : :shared_ptr < class Pal : :AsyncOperationImplementation < class std : :shared_ptr < class MapControl : :TileImage > , struct std : :pair < class std : :shared_ptr < class Pal : :AsyncOperation < class MapControl : :DownloadedResource > > , class std : :shared_ptr < class Utility : :PrioritizableTask > > > > const & , class std : :shared_ptr < class Pal : :UntypedAsyncOperationCancelList > const & ) Unknown BingMaps.dll ! std : :_Func_impl_no_alloc < class std : :_Binder < struct std : :_Unforced , void ( MapControl : :PipelineAsyncSource < class MapControl : :Versioned < class std : :shared_ptr < class MapControl : :GenericMesh < struct Engine : :xyzFloat3uvShort2stShort2 > > > , class std : :shared_ptr < class Pal : :AsyncOperation < class MapControl : :DownloadedResource > > > : :* ) ( class MapControl : :TileFrameKey const & , class std : :shared_ptr < class Pal : :AsyncOperationImplementation < class MapControl : :Versioned < class std : :shared_ptr < class MapControl : :GenericMesh < struct Engine : :xyzFloat3uvShort2stShort2 > > > , struct std : :pair < class std : :shared_ptr < class Pal : :AsyncOperation < class MapControl : :DownloadedResource > > , class std : :shared_ptr < class Utility : :PrioritizableTask > > > > const & , class std : :shared_ptr < class Pal : :UntypedAsyncOperationCancelList > const & ) , class MapControl : :PipelineAsyncSource < class MapControl : :Versioned < class std : :shared_ptr < class MapControl : :GenericMesh < struct Engine : :xyzFloat3uvShort2stShort2 > > > , class std : :shared_ptr < class Pal : :AsyncOperation < class Map Unknown MapConfiguration.dll ! Pal : :Task : :run ( void ) Unknown MapConfiguration.dll ! Utility : :PrioritizedTaskQueue : :executeNextTask ( void ) Unknown MapConfiguration.dll ! Pal : :Task : :run ( void ) Unknown MapConfiguration.dll ! Microsoft : :WRL : :Details : :DelegateArgTraits < long ( __cdecl ABI : :Windows : :System : :Threading : :IWorkItemHandler : :* ) ( ABI : :Windows : :Foundation : :IAsyncAction * ) > : :DelegateInvokeHelper < Microsoft : :WRL : :Implements < Microsoft : :WRL : :RuntimeClassFlags < 2 > , ABI : :Windows : :System : :Threading : :IWorkItemHandler , Microsoft : :WRL : :FtmBase > , < lambda_a2440968369958b092dc7b4a3993b234 > & , -1 , ABI : :Windows : :Foundation : :IAsyncAction * > : :Invoke ( ) Unknown threadpoolwinrt.dll ! Windows : :System : :Threading : :CThreadPoolWorkItem : :CommonWorkCallback ( ) Unknown threadpoolwinrt.dll ! Windows : :System : :Threading : :CThreadPoolWorkItem : :BatchedCallback ( ) Unknown ntdll.dll ! TppWorkpExecuteCallback ( ) Unknown ntdll.dll ! TppWorkerThread ( ) Unknown kernel32.dll ! BaseThreadInitThunk ( ) Unknown ntdll.dll ! RtlUserThreadStart ( ) Unknown < maps : MapControl Style= '' AerialWithRoads '' / > | UWP MapControl crashes after zooming in |
C_sharp : I am writing a method that will take a screenshot of a passed form element , and print it out . There are a few challenges I am facing . I want to be able to make this method generic enough to accept just about any type of form element . I set the `` element '' argument to type `` object '' . I think I will also need to pass a `` type '' argument or is there a way to figure out what type the object is after it is passed ? Am I approaching this problem the right way ? Any advice would be appreciated thanks ! <code> static public void PrintFormElement ( object element , ? type ? ) { } | Accepting Form Elements As Method Arguments ? |
C_sharp : How do I convert this date to `` 20110504 14:33:41 '' ? <code> DateTime date = DateTime.Parse ( `` 2011-05-04 14:33:41 '' ) ; //4 may 2011 | DateTime format string |
C_sharp : I 'm having a hard time understanding why it would be beneficial to do something like this : ( Sample is a class ) Would n't it be better to to just pass Sample into the method ? <code> static void PrintResults < T > ( T result ) where T : Sample static void PrintResults ( Sample result ) | What is the purpose of a restricting the type of generic in a method ? |
C_sharp : The following pair of functions attempt to replicate the null conditional operator available in C # 6.0 : The first function is constrained to classes and for a String s allows me to write something like : The second function is where I am running into trouble . For example , given a int ? number I would like to write : However , this gives me the following error : The call is ambiguous between the following methods or properties : 'BindingExtensions.Bind < T , TResult > ( T , Func < T , TResult > ) ' and 'BindingExtensions.Bind < T , TResult > ( T ? , Func < T , TResult > ) ' I 'm guessing that this has something to do with the interplay between the type inference of the anonymous function and the method overload resolution . If I specify the type of a as int than it compiles just fine.However , this is clearly less than desirable . Can anyone tell me why the compiler thinks the above call to bind is ambiguous and/or offer a way to fix this ? I know I could simply name the two functions differently , but what fun is that ? <code> public static TResult Bind < T , TResult > ( this T obj , Func < T , TResult > func ) where T : class { return obj == null ? default ( TResult ) : func ( obj ) ; } public static TResult Bind < T , TResult > ( this Nullable < T > obj , Func < T , TResult > func ) where T : struct { return obj.HasValue ? func ( obj.Value ) : default ( TResult ) ; } var x = s.Bind ( a = > a.Substring ( 1 ) ) ; var y = number.Bind ( a = > a + 1 ) ; var y = number.Bind ( ( int a ) = > a + 1 ) ; | C # why is this type inferred method call ambiguous ? |
C_sharp : If there are n properties , then is the Big-O of .GetProperties O ( n ) or are there are processes involved in the reflection that add complexity ? Say there is this defined class : And then this call is made : What is the time complexity , i.e . Big-O , of .GetProperties ( ) ? Considering that there are 4 properties , would this only take 4 iterations or is it more complex than that ? Or , is it O ( 1 ) with some standard set of complexity to get to the list - which seems it must still be O ( n ) just to build the properties array ? <code> public class Reflector { public string name { get ; set ; } public int number { get ; set ; } public bool flag { get ; set ; } public List < string > etc { get ; set ; } } var reflect = new Reflector ( ) ; PropertyInfo [ ] properties = reflect.GetType ( ) .GetProperties ( ) ; | Big-O of .GetProperties ( ) |
C_sharp : I am trying to understand how events can cause a memory leak . I found a good explaination at this stackoverflow question but when looking at objects in Windg , I am getting confused with the result . To start with , I have a simple class as follows.Now I am using this class in a windows form application as follows.As you can see , I instaniated Person class and subscribed to UponWakingUp event . I have a button on this form . When user click this button , I set this Person instance to null without un-subscribing to the event . Then I call GC.Collect to be sure that Garbade collection is been performed . I am showing a message box here so that I can attach Windbg to look references help by Form1 class and within this class I do n't see any reference to that event ( Windbg output is shown below although Form1 has too long data , I am displaying related to my question ) . This class has a reference to Person class but it is null . Basically this does not seem like a memory leak to me as Form1 does not has any reference to Person class even thouh it did not unsubscribed to the event . My question is if this does cause memory leak . If not , why not ? <code> class Person { public string LastName { get ; set ; } public string FirstName { get ; set ; } public event EventHandler UponWakingUp ; public Person ( ) { } public void Wakeup ( ) { Console.WriteLine ( `` Waking up '' ) ; if ( UponWakingUp ! = null ) UponWakingUp ( null , EventArgs.Empty ) ; } } public partial class Form1 : Form { Person John = new Person ( ) { LastName = `` Doe '' , FirstName = `` John '' } ; public Form1 ( ) { InitializeComponent ( ) ; John.UponWakingUp += new EventHandler ( John_UponWakingUp ) ; } void John_UponWakingUp ( object sender , EventArgs e ) { Console.WriteLine ( `` John is waking up '' ) ; } private void button1_Click ( object sender , EventArgs e ) { John = null ; GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ; GC.Collect ( ) ; MessageBox.Show ( `` done '' ) ; } } 0:005 > ! do 0158d334 Name : WindowsFormsApplication1.Form1 MethodTable : 00366390 EEClass : 00361718 Size : 332 ( 0x14c ) bytes File : c : \Sandbox\\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\WindowsFormsApplication1.exe Fields : MT Field Offset Type VT Attr Value Name 619af744 40001e0 4 System.Object 0 instance 00000000 __identity 60fc6c58 40002c3 8 ... ponentModel.ISite 0 instance 00000000 site 619af744 4001534 b80 System.Object 0 static 0158dad0 EVENT_MAXIMIZEDBOUNDSCHANGED **00366b70 4000001 13c ... plication1.Person 0 instance 00000000 John** 60fc6c10 4000002 140 ... tModel.IContainer 0 instance 00000000 components 6039aadc 4000003 144 ... dows.Forms.Button 0 instance 015ad06c button1 0:008 > ! DumpHeap -mt 00366b70 Address MT Size total 0 objects Statistics : MT Count TotalSize Class Name Total 0 objects | Why this does not cause a memory leak when event is not unsubscribed |
C_sharp : I want to iterate through an enum so I can call a method with each value of that enum . How can I do that ? I want it instead to be something likeIs there a way to do this ? <code> enum Base { ANC , BTC , DGC } ; XmlDocument doc ; doc = vircurex.get_lowest_ask ( Base.ANC ) doc = vircurex.get_lowest_ask ( Base.BTC ) doc = vircurex.get_lowest_ask ( Base.DGC ) foreach ( var val in values ) doc = vircurex.get_lowest_ask ( ... . ) | How to iterate through an enum in C # ? |
C_sharp : The example php regex ( below ) uses subroutine calls to work.If I try use it with the C # Regex class I get an error : Unrecognized grouping constructIs it possible to rewrite this in to C # regex syntax ? Would it be a simple translation , or does another ( regex ) approach need to be used ? If it is not possible what is the name of the thing it is using , so I can add it to this question to make it more useful to others with the same problem ? PHP which works with all json RFC test dataAnd not working in C # Edit : This question is NOT about using regex with json , it is about how to do something ( subroutine calls ) in C # , which CAN be done in PHP regexJust because there is a way of parsing json in C # DOES NOT answer the question . Please keep your answers and comments on topic . <code> $ pcre_regex = ' / ( ? ( DEFINE ) ( ? < number > - ? ( ? : [ 1-9 ] \d*| 0 ) ( \.\d+ ) ? ( e [ +- ] ? \d+ ) ? ) ( ? < boolean > true | false | null ) ( ? < string > `` ( ? > [ ^ '' \\\\ ] + | \\\\ [ `` \\\\bfnrt\/ ] | \\\\ u [ 0-9a-f ] { 4 } ) * `` ) ( ? < array > \ [ ( ? : ( ? & json ) ( ? : , ( ? & json ) ) * ) ? \s* \ ] ) ( ? < pair > \s* ( ? & string ) \s* : ( ? & json ) ) ( ? < object > \ { ( ? : ( ? & pair ) ( ? : , ( ? & pair ) ) * ) ? \s* \ } ) ( ? < json > \s* ( ? : ( ? & number ) | ( ? & boolean ) | ( ? & string ) | ( ? & array ) | ( ? & object ) ) \s* ) ) \A ( ? & json ) \z /six ' ; string pattern = @ '' ( ? ( DEFINE ) ( ? < number > - ? ( ? : [ 1-9 ] \d* | 0 ) ( \.\d+ ) ? ( e [ +- ] ? \d+ ) ? ) ( ? < boolean > true | false | null ) ( ? < string > `` '' ( ? > [ ^ '' '' \\\\ ] + | \\\\ [ `` '' \\\\bfnrt\/ ] | \\\\ u [ 0-9a-f ] { 4 } ) * `` '' ) ( ? < array > \ [ ( ? : ( ? & json ) ( ? : , ( ? & json ) ) * ) ? \s* \ ] ) ( ? < pair > \s* ( ? & string ) \s* : ( ? & json ) ) ( ? < object > \ { ( ? : ( ? & pair ) ( ? : , ( ? & pair ) ) * ) ? \s* \ } ) ( ? < json > \s* ( ? : ( ? & number ) | ( ? & boolean ) | ( ? & string ) | ( ? & array ) | ( ? & object ) ) \s* ) ) \A ( ? & json ) \z '' ; string input = @ '' [ { \ '' Example\ '' : \ '' data\ '' } ] '' ; RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline ; bool isValid = Regex.IsMatch ( input , pattern , options ) ; | Is it possible to convert PHP Regex ( using subroutine calls ) to C # regex ? |
C_sharp : I noticed something in C # when dealing with custom objects that I found to be a little odd . I am certain it is just a lack of understanding on my part so maybe someone can enlighten me.If I create a custom object and then I assign that object to the property of another object and the second object modifies the object assigned to it , those changes are reflected in the same class that did the assigning even though nothing is returned.You want that in English ? Here is an example : In the above sample I would have thought that , because SomeObject.DoSomething ( ) returns void , this program would only display `` I was added from MyProgram.Main ( ) . '' . However , the List < string > in fact contains both that line and `` I was added from SomeObject.DoSomething ( ) '' .Here is another example . In this example the string remains unchanged . What is the difference and what am I missing ? This program sample ends up displaying `` I was set in MyProgram.Main ( ) '' . After seeing the results of the first sample I would have assumed that the second program would have overwritten the string with `` I was set in SomeObject.DoSomething ( ) . '' . I think I must be misunderstanding something . <code> class MyProgram { static void Main ( ) { var myList = new List < string > ( ) ; myList.Add ( `` I was added from MyProgram.Main ( ) . `` ) ; var myObject = new SomeObject ( ) ; myObject.MyList = myList ; myObject.DoSomething ( ) ; foreach ( string s in myList ) Console.WriteLine ( s ) ; // This displays both strings . } } public class SomeObject { public List < string > MyList { get ; set ; } public void DoSomething ( ) { this.MyList.Add ( `` I was added from SomeObject.DoSomething ( ) '' ) ; } } class MyProgram { static void Main ( ) { var myString = `` I was set in MyProgram.Main ( ) '' ; var myObject = new SomeObject ( ) ; myObject.MyString = myString ; myObject.DoSomething ( ) ; Console.WriteLine ( myString ) ; // Displays original string . } } public class SomeObject { public string MyString { get ; set ; } public void DoSomething ( ) { this.MyString = `` I was set in SomeObject.DoSomething ( ) . `` ; } } | C # odd object behavior |
C_sharp : All these string prefixes are legal to use in C # : Why is n't this ? One would have thought that the order of these operators does n't matter , because they have no other meaning in C # but to prefix strings . I can not think of a situation when this inverted double prefix would not compile . Is the order enforced only for aesthetic purposes ? <code> `` text '' @ '' text '' $ '' text '' $ @ '' text '' @ $ '' text '' | Why ca n't I use @ $ prefix before strings ? |
C_sharp : Guys I have a `` best practice question '' For example I have this classes : What is recommended to pass ? Just what I need ( int-value type ) or the whole object ( reference type ) Im asking this because Im using LINQ on an app that I am making and I have created many entities where I should pass the IDs ( foreing keys ) , but Im passing objects.What is the best approach ? <code> class Person { public int age { get ; set ; } } class Computer { public void checkAge ( Person p ) // Which one is recommended THIS { // Do smthg with the AGE } public void checkAge ( int p ) // OR THIS { //Do smthg with the age . } } | What to pass ? Reference Object or Value Type ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.