text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
C_sharp : If I attempt to write two overloads of a method , one accepting an Expression < Func < T > > parameter and another accepting a Func < T > , I will get a compiler error on trying to call the method with a lambda expression because the two signatures create ambiguity . The following would be problematic , for example : I get that . But I do n't like the approach of just accepting an Expression < Func < string > > , as this forces calling code to use a lambda expression . What if I want to be able to accept a method group as well ? My basis for asking this question is that I 'm working on some code where I 'd like to be able to write something like this : ... and get output like this : Meanwhile , I 'd like to be able to do this as well : ... and get output like this : Is there any way to do what I 'm trying to do here , without just using two different method names ( e.g. , ExpressionMethod and FuncMethod ) ? I realize that would n't be such a big deal ; I 'm just curious if there 's another way . <code> Method ( ( ) = > `` Hello '' ) ; // Is that a Func < string > , // or is it an Expression < Func < string > > ? Method ( ( ) = > `` Hello '' ) ; Executed ' ( ) = > `` Hello '' ' and got `` Hello '' back . Method ( ReturnHello ) ; Executed 'ReturnHello ' and got `` Hello '' back . | Can I define a method to accept EITHER a Func < T > OR an Expression < Func < T > > ? |
C_sharp : This is strange.I have a windows application that dynamically loads DLLs using Reflection.Assembly.LoadFrom ( dll_file_name_here ) .It works as expected , until I ILMerge the application with another DLL.So this scenario works fine : MyApp.exeMyAppComponent.dllPlugin.dllOnce I ILMerge MyApp.exe and MyAppComponent.dll resulting in : MyApp.exePlugin.dllCalling Reflection.Assembly.LoadFrom ( `` Plugin.dll '' ) seems to load successfully , however once I try to do anything with it eg : I get an exception `` unable to load one or more of the requested types . retrieve the loader exceptions property for more informtion '' .The frustrating thing is I ca n't really debug it , because debugging pre merging works perfectly ! Help ? <code> foreach ( typeAsm in Reflection.Assembly.LoadFrom ( `` Plugin.dll '' ) ) | Dynamic loading working fine , except after the executable is ILMerged |
C_sharp : I have a bunch of SKUs ( stock keeping units ) that represent a series of strings that I 'd like to create a single Regex to match for.So , for example , if I have SKUs : ... I 'd like to automatically generate the Regex to recognize any one of the SKUs.I know that I could do simply do `` BATPAG003|BATTWLP03|BATTWLP04|BATTWSP04|SPIFATB01 '' , but list of SKUs can be quite lengthy and I 'd like to compress the resulting Regex to look like `` BAT ( PAG003|TW ( LP0 ( 3|4 ) |SP04 ) ) |SPIFATB01 '' So this is a combinatorics exercise . I want to generate the all of the possible Regex to match any of my input strings , with the view that the shortest is probably the best.I could , for example , produce any of these : Any of those would work , but the shortest is probably the one I 'd choose.To start with I 've tried to implement this function : This takes my source skus and results in a list of possible Regex 's , but it 's not working . This is the current output : It feels very close , and I think I 'm slightly doing something wrong . <code> var skus = new [ ] { `` BATPAG003 '' , `` BATTWLP03 '' , `` BATTWLP04 '' , `` BATTWSP04 '' , `` SPIFATB01 '' } ; BATPAG003|BATTWLP03|BATTWLP04|BATTWSP04|SPIFATB01BAT ( PAG003|TW ( LP0 ( 3|4 ) |SP04 ) ) |SPIFATB01BAT ( PAG003|TW ( LP ( 03|04 ) |SP04 ) ) |SPIFATB01B ( ATPAG003|ATTW ( LP0 ( 3|4 ) |ATSP04 ) ) |SPIFATB01 Func < IEnumerable < string > , IEnumerable < string > > regexify = null ; regexify = xs = > from n in Enumerable.Range ( 1 , 10 ) let g = xs.ToArray ( ) .Where ( s = > ! String.IsNullOrWhiteSpace ( s ) ) .GroupBy ( x = > new String ( x.Take ( n ) .ToArray ( ) ) , x = > new String ( x.Skip ( n ) .ToArray ( ) ) ) let parts = g.SelectMany ( x = > x.Count ( ) > 1 ? regexify ( x ) .Select ( y = > x.Key + `` ( `` + String.Join ( `` | '' , y ) + `` ) '' ) : new [ ] { x.Key + String.Join ( `` '' , x ) } ) let regex = String.Join ( `` | '' , parts ) orderby regex.Length select regex ; BATPAG003|BATTWLP03|BATTWLP04|BATTWSP04|SPIFATB01 BATPAG003|BATTWLP03|BATTWLP04|BATTWSP04|SPIFATB01 BATPAG003|BATTWLP0 ( 3|4 ) |BATTWLP0 ( 3|4 ) |BATTWLP0 ( 3|4 ) |BATTWLP0 ( 3|4 ) |BATTWLP0 ( 3|4 ) |BATTWLP0 ( 3|4 ) |BATTWLP0 ( 3|4 ) |BATTWLP0 ( 3|4 ) |BATTWLP0 ( 3|4 ) |BATTWLP0 ( 3|4 ) |BATTWSP04|SPIFATB01 BATPAG003|BATTWLP ( 03|04 ) |BATTWLP ( 03|04 ) |BATTWLP ( 03|04 ) |BATTWLP ( 03|04 ) |BATTWLP ( 03|04 ) |BATTWLP ( 03|04 ) |BATTWLP ( 03|04 ) |BATTWLP ( 03|04 ) |BATTWLP ( 03|04 ) |BATTWLP ( 0 ( 3|4 ) |0 ( 3|4 ) |0 ( 3|4 ) |0 ( 3|4 ) |0 ( 3|4 ) |0 ( 3|4 ) |0 ( 3|4 ) |0 ( 3|4 ) |0 ( 3|4 ) |0 ( 3|4 ) ) |BATTWSP04|SPIFATB01 BATPAG003|BATTWL ( P03|P04 ) |BATTWL ( P03|P04 ) |BATTWL ( P03|P04 ) |BATTWL ( P03|P04 ) |BATTWL ( P03|P04 ) |BATTWL ( P03|P04 ) |BATTWL ( P03|P04 ) |BATTWL ( P03|P04 ) |BATTWL ( P0 ( 3|4 ) |P0 ( 3|4 ) |P0 ( 3|4 ) |P0 ( 3|4 ) |P0 ( 3|4 ) |P0 ( 3|4 ) |P0 ( 3|4 ) |P0 ( 3|4 ) |P0 ( 3|4 ) |P0 ( 3|4 ) ) |BATTWL ( P ( 03|04 ) |P ( 03|04 ) |P ( 03|04 ) |P ( 03|04 ) |P ( 03|04 ) |P ( 03|04 ) |P ( 03|04 ) |P ( 03|04 ) |P ( 03|04 ) |P ( 0 ( 3|4 ) |0 ( 3|4 ) |0 ( 3|4 ) |0 ( 3|4 ) |0 ( 3|4 ) |0 ( 3|4 ) |0 ( 3|4 ) |0 ( 3|4 ) |0 ( 3|4 ) |0 ( 3|4 ) ) ) |BATTWSP04|SPIFATB01 BATPAG003|BATTW ( LP03|LP04|SP04 ) |BATTW ( LP03|LP04|SP04 ) |BATTW ( LP03|LP04|SP04 ) |BATTW ( LP03|LP04|SP04 ) |BATTW ( LP03|LP04|SP04 ) |BATTW ( LP03|LP04|SP04 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 ) |L ( P03|P04 ) |L ( P03|P04 ) |L ( P03|P04 ) |L ( P0 ( 3|4 ) |P0 ( 3|4 ) |P0 ( 3|4 ) |P0 ( 3|4 ) |P0 ( 3|4 ) |P0 ( 3|4 ) |P0 ( 3|4 ) |P0 ( 3|4 ) |P0 ( 3|4 ) |P0 ( 3|4 ) ) |L ( P ( 03|04 ) |P ( 03|04 ) |P ( 03|04 ) |P ( 03|04 ) |P ( 03|04 ) |P ( 03|04 ) |P ( 03|04 ) |P ( 03|04 ) |P ( 03|04 ) |P ( 0 ( 3|4 ) |0 ( 3|4 ) |0 ( 3|4 ) |0 ( 3|4 ) |0 ( 3|4 ) |0 ( 3|4 ) |0 ( 3|4 ) |0 ( 3|4 ) |0 ( 3|4 ) |0 ( 3|4 ) ) ) |SP04 ) ) ) ) ) |SPIFATB01 | Generating the Shortest Regex Dynamically from a source List of Strings |
C_sharp : I want to call a constructor of a struct , that has default values for all parameters . But when I call the parameterless constructor of MyRectangle a not defined constructor get 's called . Why is that ? Is it possible to not have a not from me created constructor called ? <code> using System ; namespace UebungClasses { class Program { static void Main ( string [ ] args ) { MyRectangle sixRec = new MyRectangle ( 3 , 2 ) ; MyRectangle oneRec = new MyRectangle ( ) ; Console.WriteLine ( `` area of six : `` + sixRec.Area ( ) + `` area of one : `` + oneRec.Area ( ) ) ; } } public struct MyRectangle { public MyRectangle ( double w = 1 , double l = 1 ) { width = w ; length = l ; Console.WriteLine ( `` Width : `` + width + `` Lenght : `` + length ) ; } public double Area ( ) { return width * length ; } private double width ; private double length ; } } | Calling a constructor with default parameters instead of default constructor |
C_sharp : I have two classes Order and OrderDetail : They are mapped like this : When I create order and order details : Details of order empty there and OrderId of orderdetails is null also . When I add created order detail in context then it will be added to Details and OrderId becomes Id of created order . Why it works only when I add it to context ? I want that it works without adding it to context . Maybe , I should do something in consctructor of classes ( with Context parameter ) ? How can I do this ? EDIT : Order and OrderDetails classes inherited from abstact class Entity : Also , as you see , I have constructor without parameter . I created them because EF shows this message when I 'm getting entities from context : How can I avoid this error without creating conscrtuctors without parameter ? <code> public class Order : Entity { public Order ( KitchenAppContext context ) : base ( context ) { } public Order ( ) : base ( ) { } public DateTime Date { get ; set ; } public Guid MenuId { get ; set ; } public virtual Menu Menu { get ; set ; } public bool IsClosed { get ; set ; } public decimal Price { get ; set ; } public virtual int PeopleCount { get { return Details.Count ; } } public virtual List < OrderDetail > Details { get ; set ; } = new List < OrderDetail > ( ) ; } public class OrderDetail : Entity { public OrderDetail ( KitchenAppContext context ) : base ( context ) { } public OrderDetail ( ) : base ( ) { } public Guid UserId { get ; set ; } public virtual User User { get ; set ; } public virtual List < PaymentDetail > Payments { get ; set ; } = new List < PaymentDetail > ( ) ; public virtual Order Order { get ; set ; } public Guid OrderId { get ; set ; } } void OrderMapping ( ModelBuilder builder ) { var etBuilder = builder.Entity < Order > ( ) ; etBuilder.HasKey ( m = > new { m.Id } ) ; etBuilder.HasOne ( o = > o.Menu ) .WithMany ( a = > a.Orders ) .HasForeignKey ( f = > f.MenuId ) ; etBuilder.HasMany ( o = > o.Details ) .WithOne ( d = > d.Order ) .HasForeignKey ( f = > f.OrderId ) ; } void OrderDetailMapping ( ModelBuilder builder ) { var etBuilder = builder.Entity < OrderDetail > ( ) ; etBuilder.HasKey ( m = > new { m.Id } ) ; etBuilder.HasOne ( o = > o.User ) .WithMany ( u = > u.Details ) .HasForeignKey ( f = > f.UserId ) ; etBuilder.HasOne ( o = > o.Order ) .WithMany ( u = > u.Details ) .HasForeignKey ( f = > f.OrderId ) ; etBuilder.HasMany ( o = > o.Payments ) .WithOne ( d = > d.OrderDetail ) .HasForeignKey ( f = > f.OrderDetailId ) ; } var order = new Order ( Context ) ; Context.Orders.Add ( order ) ; var oderDetail = new OrderDetail ( Context ) { Order = order } ; public abstract class Entity { Guid id ; public Guid Id { get { if ( id == null || id == Guid.Empty ) { id = Guid.NewGuid ( ) ; } return id ; } set { id = value ; } } public Entity ( KitchenAppContext context ) { Context = context ; } public Entity ( ) { } public MainContext Context ; } System.InvalidOperationException : ' A parameterless constructor was not found on entity type 'Order ' . In order to create an instance of 'Order ' EF requires that a parameterless constructor be declared . ' | Why reference properties works only through context |
C_sharp : What is the equivalent c # generics notation of the above java generics ? Parameter listenerClass will be a type & not a object . But the object T has to belong to a specific hierachy . <code> public < T extends java.util.EventListener > T [ ] getListeners ( final Class < T > listenerClass ) { ... } | C # generics & not going insane |
C_sharp : Right now my code looks like this : Is there a more succinct way of creating a list in one line of code , with one element added optionally ? <code> var ids = projectId.HasValue ? new List < Guid > { projectId.Value } : new List < Guid > ( ) ; | C # collection initializer – is it possible to add an element optionally , based on a condition ? |
C_sharp : I get the following response from a webservice : How must the json-object look like to deserialize this ? Or is there another way to get the values of the properties ? <code> { `` data '' : { `` foo.hugo.info '' : { `` path '' : `` logon.cgi '' , `` minVersion '' : 1 , `` maxVersion '' : 2 } , `` foo.Fritz.Task '' : { `` path '' : `` Fritz/process.cgi '' , `` minVersion '' : 1 , `` maxVersion '' : 1 } } , `` success '' : true } | How to make an c # object from json |
C_sharp : I am writing a short program which will eventually play connect four.Here it is so far , pastebinThere is one part which is n't working . I have a jagged array declared on line 16 : Which I think looks like this : when I do this board [ 5 ] [ 2 ] = '* ' I getinstead of what I 'd like : How it runs at the moment ( output should only have one asterisk ) : <code> char [ ] [ ] board = Enumerable.Repeat ( Enumerable.Repeat ( '- ' , 7 ) .ToArray ( ) , 7 ) .ToArray ( ) ; -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - -- * -- -- -- * -- -- -- * -- -- -- * -- -- -- * -- -- -- * -- -- -- * -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -* -- -- -- -- -- - | How to assign to a jagged array ? |
C_sharp : I have to zoom an image in uwp application , which works fine , but the design requires to have another image ( that works as a button ) in front of it and I dont want that element to be zoomed as well . It has to be only the image inside the canvas tag , this is how I have it now . thats the xaml I have and which makes the zoom work for all elements inside of it . I tried to set scrollViewer.zoomMode=disabled for the elements that are not in the canvas but without luck . Any ideas ? Thanks ! <code> < ScrollViewer MinZoomFactor= '' 1 '' ZoomMode= '' Enabled '' VerticalScrollBarVisibility= '' Auto '' HorizontalScrollBarVisibility= '' Auto '' > < RelativePanel HorizontalAlignment = `` Stretch '' > < Canvas x : Name= '' canvas '' > < Image Source = `` { Binding Test , UpdateSourceTrigger=PropertyChanged , Mode=TwoWay } '' / > < /Canvas > < Button RelativePanel.AlignTopWithPanel= '' True '' Height= '' 55 '' Command= '' { Binding Path=CollapseSplitView } '' CommandParameter= '' { Binding ElementName=SplitV } '' > < Button.Background > < ImageBrush ImageSource = `` /Assets/btlist.png '' > < / ImageBrush > < /Button.Background > < /Button > < Image RelativePanel.AlignBottomWithPanel= '' True '' RelativePanel.AlignRightWithPanel= '' True '' Source= '' /Assets/escala-x.png '' Width= '' 130 '' Height= '' 70 '' Margin= '' 0,0,20,0 '' ScrollViewer.IsZoomChainingEnabled= '' False '' ScrollViewer.IsZoomInertiaEnabled= '' False '' > < /Image > < /RelativePanel > < /ScrollViewer > | scrollviewer zoom only one element |
C_sharp : What is the best way to synchronize 2 sets of data via Binding ? Now my question is , when I receive an update from one collection ( e.g . Source.CollectionChanged event ) I need to call the custom TargetSetters , and ignore the events called which originated from my update.And also the other way , when the Target custom events get fired , i need to update the source , but ignore the CollectionChanged event.At the moment , I am keeping a reference to my handlers , and removing that before updating any of the collections . e.g.I have seen that you can use an if statement to check if the updates are from source , and if they are ignore them . e.g.After Google + SO Search came back with nothing , I wanted to see how other people are doing this , and is there something really simple I am missing here that solves this problem ? ( I know that the examples are not thread-safe ) If not , what is the preferred way ? Removing and attaching handlers , or setting a boolean flag ? What is more performant ( yes i know this is highly unlikely to cause a bottleneck but out of curiosity ) Reason I am asking is because , currently I am implementing Attached Behaviours and for each behaviour , I am creating 2 sets of Dictionaries which hold the references to the handlers for each object as state has to be passed around.I ca n't seem to find the the source code for the binding mechanism of the .NET Binding classes , to see how MS implemented it . If anyone has a link to those it would be greatly appreciated . <code> Target = Custom Setters - raises custom events whenever something changedSource = ObservableCollection - raises events whenever collection changed private void ObservableCollection_OnCollectionChanged ( object sender , NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs ) { CustomObject.SelectionChanged -= CustomObject_SelectionChanged ; // Do change logic and update Custom Object ... . CustomObject.SelectionChanged += CustomObject_SelectionChanged ; } void CustomObject_SelectionChanged ( object sender , SelectionChangedEventArgs e ) { ObservableCollection.CollectionChanged -= ObservableCollection_OnCollectionChanged ; // Do change logic and update ObservableCollection ... ObservableCollection.CollectionChanged += ObservableCollection_OnCollectionChanged ; } private void ObservableCollection_OnCollectionChanged2 ( object sender , NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs ) { if ( BindingTargetUpdating ) return ; BindingSourceUpdating = true ; // Do change logic and update Custom Object ... . BindingSourceUpdating = false ; } void CustomObject_SelectionChanged2 ( object sender , SelectionChangedEventArgs e ) { if ( BindingSourceUpdating ) return ; BindingTargetUpdating = true ; // Do change logic and update ObservableCollection ... BindingTargetUpdating = false ; } | TwoWay Collection Binding Sync/Lock |
C_sharp : After de-compiling the Linq IEnumerable extension methods I was glad to see thatthe Count ( ) method , prior to trying to iterate the whole enumerable , attempts to downcast it to an ICollection or an ICollection < T > e.g : Why is n't this happening in Any ( ) ? wo n't it benefit from using .Count > 0 instead of creating an array enumerator ? <code> public static int Count < TSource > ( this IEnumerable < TSource > source ) { if ( source == null ) throw Error.ArgumentNull ( `` source '' ) ; ICollection < TSource > collectionoft = source as ICollection < TSource > ; if ( collectionoft ! = null ) return collectionoft.Count ; ICollection collection = source as ICollection ; if ( collection ! = null ) return collection.Count ; int count = 0 ; using ( IEnumerator < TSource > e = source.GetEnumerator ( ) ) { checked { while ( e.MoveNext ( ) ) count++ ; } } return count ; } | In IEnumerable extensions - why is only Count ( ) optimized for ICollection ? |
C_sharp : I have the following method that takes in a details object , validates it , converts it to a request and enqueues it . Everything is fine apart from the validate request which I am having trouble with . Basically , there is different validation logic for each different details object . I know from the generic constraint that the details object must have a base class of BaseDetails and from the actual generic parameter I know the exact derived type , but do not know how to use these to write my validator class so it handles all types of details : <code> private void Enqueue < TDetails , TRequest > ( TDetails details ) where TDetails : BaseDetails where TRequest : BaseRequest { bool isValid = _validator.Validate ( details ) ; if ( isValid ) { TRequest request = ObjectMapper .CreateMappedMessage < TDetails , TRequest > ( details ) ; _queue.Enqueue ( request ) ; } } | Newbie polymorphism question using generics |
C_sharp : What if I had something like this : Now as we can see , I 'm trying to handle exceptions for some different cases . BUT whenever an exception is raised , I 'm always calling the method DoSomething ( ) at the end . Is there a smarter way to call DoSomething ( ) if there is an exception ? If I added a finally block and called DoSomething ( ) there , it would always be called , even when there is no exception . Any suggestions ? <code> try { //work } catch ( ArgumentNullException e ) { HandleNullException ( ) ; Logger.log ( `` ArgumentNullException `` + e ) ; DoSomething ( ) ; } catch ( SomeOtherException e ) { HandleSomeOtherException ( ) ; Logger.log ( `` SomeOtherException `` + e ) ; DoSomething ( ) ; } catch ( Exception e ) { HandleException ( ) ; Logger.log ( `` Exception `` + e ) ; DoSomething ( ) ; } | A lot of catch blocks , but in all of them the same function |
C_sharp : I have columns list in which I need to assign Isselected as true for all except for two columns . ( Bug and feature ) . I have used this following code to achieve it and working fine , but is there any quick or easy way to achieve the same ? Thanks in advance <code> DisplayColumns.ToList ( ) .ForEach ( a = > a.IsSelected = true ) ; DisplayColumns.ToList ( ) .Where ( a = > a.ColumnName == `` Bug '' || a.ColumnName == `` Feature '' ) .ToList ( ) .ForEach ( a = > a.IsSelected = false ) ; | Optimize Linq in C # |
C_sharp : I am facing a strange issue , sometimes i am getting the url from the sendgrid ashttps : //localhost:81/Activation ? username=ats8 @ test.com & activationToken=EAAAAA which works fine . but sometimes i am getting url which is encoded as follows , '' https : //localhost:81/Activation ? username=ats8 % 40test.com & activationToken=EAAAAA '' and my ViewModel is as follows , and the Method goes as follows , on the 2nd case , the activationToken comes as null . how can i detect activationToken even if the url is encoded ? <code> public class Verification { [ DataType ( DataType.EmailAddress ) ] public string Username { get ; set ; } [ Required ] [ DataType ( DataType.Password ) ] public string Password { get ; set ; } [ Required ] [ DataType ( DataType.Password ) ] [ Compare ( `` Password '' ) ] public string ConfirmPassword { get ; set ; } public string ActivationToken { get ; set ; } } public ActionResult Activation ( string username , string activationToken ) { var model = new Verification { Username = username , ActivationToken = activationToken } ; return View ( model ) ; } | Why my ViewModel field becomes empty when the url is HTML encoded ? |
C_sharp : This code does n't look clean and this if condition can grow Is there any better solution to this problem ? Sadly that function is n't linear so it 's not easy to code that in a mathematical way . <code> public int VisitMonth ( int months ) { int visit = 0 ; if ( months < = 1 ) { visit = 1 ; } else if ( months < = 2 ) { visit = 2 ; } else if ( months < = 4 ) { visit = 3 ; } else if ( months < = 6 ) { visit = 4 ; } else if ( months < = 9 ) { visit = 5 ; } else if ( months < = 12 ) { visit = 6 ; } else if ( months < = 15 ) { visit = 7 ; } else if ( months < = 18 ) { visit = 8 ; } else if ( months < = 24 ) { visit = 9 ; } else if ( months < = 30 ) { visit = 10 ; } else if ( months < = 36 ) { visit = 11 ; } else if ( months < = 48 ) { visit = 12 ; } else if ( months < = 60 ) { visit = 13 ; } else { visit = 14 ; } return visit ; } | Replacing if else statement with any design pattern or better approach |
C_sharp : I have problem to get image bytes data from oracle . reader ( `` image '' ) always returning 0 length . Is their any workaround ? If i used oledb then its working but not working with Microsoft EnterpriseLibrary . <code> using ( IDataReader reader = ExecuteNonQueryOracle ( Query ) ) { while ( reader.Read ) { dict ( `` image '' ) = reader ( `` image '' ) ; } } public object ExecuteNonQueryOracle ( string Query ) { using ( dbCommand == CurrentDatabase.GetSqlStringCommand ( Query ) ) { dbCommand.CommandType = CommandType.Text ; return CurrentDatabase.ExecuteReader ( dbCommand ) ; } } | Obtaining LONG RAW Data ( Bytes ) from EnterpriseLibrary |
C_sharp : I just have started to design with DDD ( I have no experience neither a teacher ) I have some domain service classes that have to reference each other in some point . So I decided to inject the references through constructor.And when I created a view that has a lot of data to display in the controller I had to create a bunch of service ( some of which referencing each other ) At this point one of my controller 's first lines looked like this : But I started to create interfaces for the services and using a IoC controller ( named StructureMap ) And now the same controller 's first lines looked like this : I think that it 's far more good to use , but I to know if it is a good practice in DDD or not . <code> EmployeeRepository employRepository = new EmployeeRepository ( ) ; ShiftModelRepository shiftModelRepository = new ShiftModelRepository ( ) ; ShiftModelService shiftModelService = new ShiftModelService ( shiftModelRepository ) ; EmployeeService employeeService = new EmployeeService ( employRepository , shiftModelService ) ; OvertimeRepository overtimeRepository = new OvertimeRepository ( ) ; OvertimeService overtimeService = new OvertimeService ( overtimeRepository , employeeService ) ; IShiftModelService shiftModelService = ObjectFactory.GetInstance < IShiftModelService > ( ) ; IOvertimeService overtimeService = ObjectFactory.GetInstance < IOvertimeService > ( ) ; IEmployeeService employeeService = ObjectFactory.GetInstance < IEmployeeService > ( ) ; | Is it a good design practice to have an interface for each service class in DDD ? |
C_sharp : Hello everyone i 'm new to c # language i was use vb.net , in below what is the error with this code and why , thank youbut when i try this code to c # i get Errorerror : Property or indexer ‘ Example.splitstring.current ’ can not ve assigned to – it is read only <code> vb.net codeClass SplitStringImplements IEnumerableImplements IEnumeratorPrivate currentPosition As Integer = 0Private m_Sentence As StringProperty Sentence ( ) As String Get Return m_Sentence End Get Set ( ByVal Value As String ) m_Sentence = Value Me.Reset ( ) End SetEnd PropertyPublic ReadOnly Property Current As Object Implements IEnumerator.Current Get Dim counter As Integer Dim tmpLength As Integer = 0 For counter = Me.currentPosition To Me.Sentence.Length - 1 If Me.Sentence.Chars ( counter ) = `` `` c Then Exit For Else tmpLength += 1 End If Next Current = Me.Sentence.Substring ( Me.currentPosition , tmpLength ) ' ok Me.currentPosition += tmpLength + 1 End GetEnd PropertyPublic Function MoveNext ( ) As Boolean Implements IEnumerator.MoveNext If Me.currentPosition > Me.Sentence.Length - 1 Then Me.Reset ( ) Return False Else Return True End IfEnd FunctionPublic Sub Reset ( ) Implements IEnumerator.Reset Me.currentPosition = 0End SubPublic Function GetEnumerator ( ) As IEnumerator Implements IEnumerable.GetEnumerator Return MeEnd FunctionEnd Class c # codeclass SplitString : IEnumerable , IEnumerator { private int currentPosition = 0 ; private string m_Sentence ; public string Sentence { get { return m_Sentence ; } set { m_Sentence = value ; this.Reset ( ) ; } } public IEnumerator GetEnumerator ( ) { return this ; } public object Current { get { int counter = 0 ; int tmpLength = 0 ; for ( counter = this.currentPosition ; counter < = this.Sentence.Length - 1 ; counter++ ) { if ( this.Sentence [ counter ] == ' ' ) { break ; } else { tmpLength += 1 ; } } Current = this.Sentence.Substring ( this.currentPosition , tmpLength ) ; // Error this.currentPosition += tmpLength + 1 ; return functionReturnValue ; } } public bool MoveNext ( ) { if ( this.currentPosition > this.Sentence.Length-1 ) { this.Reset ( ) ; return false ; } else { return true ; } } public void Reset ( ) { this.currentPosition=0 ; } } | IEnumerator IEnumerable vb to C # |
C_sharp : The title suggests that i 've already an idea what 's going on , but i can not explain it . I 've tried to order a List < string [ ] > dynamically by each `` column '' , beginning with the first and ending with the minimum Length of all arrays.So in this sample it is 2 , because the last string [ ] has only two elements : Now i 've tried to order all by the first and second column . I could do it statically in this way : But if i do n't know the number of `` columns '' i could use this loop ( that 's what I thought ) : But that does n't work , it fails with an IndexOutOfRangeException at the last line . The debugger tells me that i is 2 at that time , so the for-loop condition seems to be ignored , i is already == minDim . Why is that so ? What is the correct way for this ? <code> List < string [ ] > someValues = new List < string [ ] > ( ) ; someValues.Add ( new [ ] { `` c '' , `` 3 '' , `` b '' } ) ; someValues.Add ( new [ ] { `` a '' , `` 1 '' , `` d '' } ) ; someValues.Add ( new [ ] { `` d '' , `` 4 '' , `` a '' } ) ; someValues.Add ( new [ ] { `` b '' , `` 2 '' } ) ; someValues = someValues .OrderBy ( t = > t [ 0 ] ) .ThenBy ( t = > t [ 1 ] ) .ToList ( ) ; int minDim = someValues.Min ( t = > t.GetLength ( 0 ) ) ; // 2IOrderedEnumerable < string [ ] > orderedValues = someValues.OrderBy ( t = > t [ 0 ] ) ; for ( int i = 1 ; i < minDim ; i++ ) { orderedValues = orderedValues.ThenBy ( t = > t [ i ] ) ; } someValues = orderedValues.ToList ( ) ; // IndexOutOfRangeException | For-Loop and LINQ 's deferred execution do n't play well together |
C_sharp : What are the implications of doing this ... ... versus this ? I suspect that the compiler is creating a new instance for me in the second example . I 'm sure this is a bit of a newbie question , but Google did n't turn up anything . Can anyone give me some insight ? <code> this.myButton.Click += new EventHandler ( this.myButton_Clicked ) ; this.myButton.Click += this.myButton_Clicked ; | Should I Create a New Delegate Instance ? |
C_sharp : I am trying to open a proxy on a thread ( in background ) , the thread makes a new instance of the proxy , calls a method of the service and immediately after disposes the service.All of this happens on a thread : I keep seeing intermittent timeout issues happening even though I have set the timeout to max for CloseTimeout , OpenTimeout , ReceiveTimeout , SendTimeout.I just want to make sure design wise this is not an issue i.e . opening a service on a thread and disposing it ? EDIT : Proxy internally establishes a channel with custom binding on different endpoints for each thread . <code> var background = new Thread ( ( ) = > { var proxy = new AssignmentSvcProxy ( new EndpointAddress ( worker.Address ) ) ; try { proxy.Channel.StartWork ( workload ) ; proxy.Dispose ( ) ; } catch ( EndpointNotFoundException ex ) { logService.Error ( ex ) ; proxy.Dispose ( ) ; proxy = null ; } catch ( CommunicationException ex ) { logService.Error ( ex ) ; proxy.Dispose ( ) ; proxy = null ; } catch ( TimeoutException ex ) { logService.Error ( ex ) ; proxy.Dispose ( ) ; proxy = null ; } catch ( Exception ex ) { logService.Error ( ex ) ; proxy.Dispose ( ) ; proxy = null ; } } ) { IsBackground = true } ; background.Start ( ) ; | Starting multiple services on threads |
C_sharp : Just wondering why Expression Blend outputs a path nested in two canvases ( rather than just one ) , I 've also seen some with 3 or more but still outputting just one path : Is there any way I can get rid of the extra nested canvases in expression blends outputs ? <code> < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < Canvas xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' x : Name= '' cross '' Width= '' 146.768 '' Height= '' 146.768 '' Clip= '' F1 M 0,0L 146.768,0L 146.768,146.768L 0,146.768L 0,0 '' UseLayoutRounding= '' False '' > < Canvas x : Name= '' Layer_1 '' Width= '' 146.768 '' Height= '' 146.768 '' Canvas.Left= '' 0 '' Canvas.Top= '' 0 '' > < Path x : Name= '' Path '' Width= '' 138.605 '' Height= '' 138.605 '' Canvas.Left= '' 4.12044 '' Canvas.Top= '' 4.04301 '' Stretch= '' Fill '' Fill= '' # FFF80000 '' Data= '' F1 M 4.28074,121.084L 4.15843,120.962C 4.40034,118.924 6.48998,117.557 7.9421,116.108C 10.772,113.284 13.6019,110.46 16.4318,107.637C 24.1129,99.9719 31.794,92.3074 39.4752,84.6428C 41.9008,82.2224 44.3264,79.802 46.752,77.3816C 47.1563,76.9782 47.5606,76.5748 47.9648,76.1714C 48.3691,75.768 48.7734,75.3646 49.1776,74.9613C 49.5819,74.5579 50.143,74.2658 50.3904,73.7511C 50.5336,73.4532 50.4055,73.0526 50.2299,72.7726C 49.9265,72.2889 49.4216,71.9658 49.0175,71.5624C 48.6134,71.159 48.2092,70.7556 47.8051,70.3522C 46.5927,69.142 45.3803,67.9318 44.1679,66.7216C 40.1265,62.6877 36.0852,58.6537 32.0438,54.6197C 25.9818,48.5687 19.9197,42.5177 13.8577,36.4668C 11.837,34.4498 9.81633,32.4328 7.79565,30.4158C 6.58325,29.2056 5.06703,28.2374 4.15843,26.7852C 4.04955,26.6112 4.20685,26.3775 4.23105,26.1737C 4.25526,25.9698 4.18553,25.73 4.30367,25.5621C 4.62703,25.1027 5.10008,24.7694 5.49829,24.3731C 5.89649,23.9767 6.2947,23.5803 6.6929,23.184C 8.28572,21.5985 9.87855,20.013 11.4714,18.4276C 14.657,15.2567 17.8427,12.0857 21.0283,8.91483C 22.6211,7.32936 23.8951,5.34012 25.8068,4.15845C 26.5968,3.67004 27.5839,4.85898 28.24,5.51649C 28.6434,5.92078 29.0468,6.32503 29.4502,6.72931C 29.8536,7.13358 30.257,7.53784 30.6604,7.94211C 33.8876,11.1763 37.1148,14.4104 40.342,17.6446C 47.6031,24.9215 54.8643,32.1983 62.1255,39.4752C 64.5459,41.9008 66.9662,44.3264 69.3866,46.752C 69.79,47.1563 70.1934,47.5606 70.5968,47.9648C 71.0002,48.3691 71.4036,48.7734 71.807,49.1776C 72.2104,49.5819 72.5025,50.143 73.0172,50.3904C 73.3151,50.5337 73.7157,50.4056 73.9957,50.2299C 74.4794,49.9265 74.8025,49.4216 75.2059,49.0175C 75.6093,48.6134 76.0127,48.2092 76.4161,47.8051C 76.8195,47.401 77.2229,46.9968 77.6263,46.5927C 80.8534,43.3596 84.0806,40.1265 87.3078,36.8934C 94.569,29.619 101.83,22.3446 109.091,15.0701C 111.512,12.6453 113.932,10.2205 116.352,7.79567C 117.563,6.58325 118.531,5.06705 119.983,4.15845C 120.763,3.67059 121.746,4.84642 122.395,5.49829C 122.792,5.89648 123.188,6.29471 123.584,6.6929C 123.981,7.09113 124.377,7.48932 124.773,7.88753C 127.152,10.2768 129.53,12.666 131.908,15.0552C 134.286,17.4445 136.664,19.8337 139.043,22.2229C 139.439,22.6211 139.835,23.0193 140.232,23.4175C 140.628,23.8157 141.024,24.2139 141.421,24.6121C 142.04,25.2343 142.971,26.3126 142.465,27.0298C 141.477,28.4297 140.039,29.4502 138.826,30.6604C 136.401,33.0808 133.975,35.5012 131.549,37.9216C 123.868,45.5862 116.187,53.2507 108.506,60.9153C 105.676,63.7391 102.846,66.5628 100.016,69.3866C 99.612,69.79 99.2077,70.1934 98.8034,70.5968C 98.3992,71.0002 97.9949,71.4036 97.5906,71.807C 97.1864,72.2104 96.6253,72.5025 96.3778,73.0172C 96.2346,73.3151 96.3627,73.7157 96.5384,73.9957C 96.8418,74.4794 97.3466,74.8025 97.7508,75.2059C 98.1549,75.6093 98.559,76.0127 98.9632,76.4161C 99.3673,76.8195 99.7714,77.2229 100.176,77.6263C 103.409,80.8534 106.642,84.0806 109.875,87.3078C 117.149,94.569 124.424,101.83 131.698,109.091C 134.123,111.512 136.548,113.932 138.973,116.352C 140.185,117.563 141.701,118.531 142.61,119.983C 143.098,120.763 141.922,121.746 141.27,122.395C 140.872,122.792 140.474,123.188 140.075,123.584C 139.677,123.981 139.279,124.377 138.881,124.773C 136.492,127.152 134.102,129.53 131.713,131.908C 129.324,134.286 126.935,136.664 124.545,139.043C 124.147,139.439 123.749,139.835 123.351,140.232C 122.953,140.628 122.554,141.024 122.156,141.421C 121.534,142.04 120.456,142.971 119.738,142.465C 118.339,141.477 117.318,140.039 116.108,138.826C 113.687,136.401 111.267,133.975 108.847,131.549C 101.182,123.868 93.5176,116.187 85.853,108.506C 83.0292,105.676 80.2054,102.846 77.3816,100.016C 76.9782,99.612 76.5748,99.2077 76.1714,98.8035C 75.768,98.3992 75.3646,97.9949 74.9612,97.5906C 74.5579,97.1864 74.2658,96.6253 73.7511,96.3778C 73.4532,96.2346 73.0526,96.3627 72.7726,96.5384C 72.2889,96.8418 71.9658,97.3466 71.5624,97.7508C 71.159,98.1549 70.7556,98.559 70.3522,98.9632C 68.3352,100.984 66.3182,103.005 64.3012,105.025C 58.2503,111.087 52.1993,117.149 46.1483,123.211C 41.7109,127.657 37.2736,132.102 32.8362,136.548C 31.626,137.76 30.4158,138.973 29.2056,140.185C 28.8022,140.589 28.3988,140.993 27.9954,141.397C 27.592,141.802 27.2693,142.307 26.7852,142.61C 26.6112,142.719 26.3775,142.561 26.1737,142.537C 25.9698,142.513 25.7301,142.583 25.5621,142.465C 25.105,142.143 24.7739,141.673 24.3798,141.277C 23.9857,140.881 23.5916,140.485 23.1975,140.089C 21.6211,138.505 20.0447,136.921 18.4683,135.338C 13.7391,130.586 9.00994,125.835 4.28074,121.084 Z `` / > < /Canvas > < /Canvas > | Multiple nested canvases in Expression Design xaml output , why ? |
C_sharp : I use this code And get true result : But when i try to lower : object text2 = `` test '' .ToLower ( ) ; i get false result ? <code> object text1 = `` test '' ; object text2 = `` test '' ; Console.WriteLine ( `` text1 == text2 : `` + ( text1 == text2 ) ) ; //return : true object text1 = `` test '' .ToLower ( ) ; object text2 = `` test '' .ToLower ( ) ; Console.WriteLine ( `` text1 == text2 : `` + ( text1 == text2 ) ) ; //return : false | How to compare two object which have string values ? |
C_sharp : Is there a way to create a strongly typed controller action ? For example : In a Controller I use : I would like to use : I do not want to re-invent the wheel . I am sure someone has some clever solution . This would allow me to add compile time checking to controller methods . <code> aClientLink = Url.Action ( `` MethodName '' , `` ControllerName '' , new { Params ... } ) ; aClientLink = Url.Action ( Controller.MethodName , ControllerName ) ; | Compile-time checking for action links to controller methods |
C_sharp : Code to illustrate : Now , `` DoSomethingWithStruct '' fails to compile with : `` Operator '== ' can not be applied to operands of type 'MyStruct ' and ' < null > ' '' . This makes sense , since it does n't make sense to try a reference comparison with a struct , which is a value type.OTOH , `` DoSomethingWithDateTime '' compiles , but with compiler warning : `` Unreachable code detected '' at line marked `` XX '' . Now , I 'm assuming that there is no compiler error here , because the DateTime struct overloads the `` == '' operator . But how does the compiler know that the code is unreachable ? e.g . Does it look inside the code which overloads the `` == '' operator ? ( This is using Visual Studio 2005 in case that makes a difference ) .Note : I 'm more curious than anything about the above . I do n't usually try to use `` == '' to compare structs and nulls.EDIT : I 'll try to simplify my question - why does `` DoSomethingWithDateTime '' compile , when `` DoSomethingWithMyStruct '' does not . Both arguments are structs . <code> public struct MyStruct { public int SomeNumber ; } public string DoSomethingWithMyStruct ( MyStruct s ) { if ( s == null ) return `` this ca n't happen '' ; else return `` ok '' ; } private string DoSomethingWithDateTime ( DateTime s ) { if ( s == null ) return `` this ca n't happen '' ; // XX else return `` ok '' ; } | c # `` == '' operator : compiler behaviour with different structs |
C_sharp : Is there any language which has a form of code templating ? Let me explain what I mean ... I was working on a C # project today in which one of my classes was very repetitive , a series of properties getters and setters.I realize that this could break down into basically a type , a name , and a default value.I saw this article , which is similar to what I envision , but has no room for parameters ( the default ) .Generic Property in C # But I was thinking , there are many times where code breaks down into templates.For example , the syntax could go as such : I feel like this would have a lot of possibilities in writing succinct , DRY code . This type of thing would be somewhat achievable in c # with reflection , however that is slow and this should done during the compile.So , question : Is this type of functionality possible in any existing programming language ? <code> public static int CustomerID { get { return SessionHelper.Get < int > ( `` CustomerID '' , 0 ) ; // 0 is the default value } set { SessionHelper.Set ( `` CustomerID '' , value ) ; } } public static int BasketID { get { return SessionHelper.Get < int > ( `` BasketID '' , 0 ) ; // 0 is the default value } set { SessionHelper.Set ( `` BasketID '' , value ) ; } } ... and so forth ... public template SessionAccessor ( obj defaultValue ) : static this.type this.name { get { return SessionHelper.Get < this.type > ( this.name.ToString ( ) , defaultValue ) ; } set { SessionHelper.Set ( this.name.ToString ( ) , value ) ; } } public int CustomerID ( 0 ) , BasketID ( 0 ) with template SessionAccessor ; public ShoppingCart Cart ( new ShoppingCart ( ) ) with template SessionAccessor ; // Class example | Is there any language out there which uses code templating ? |
C_sharp : Is it possible to assign an attribute on a property and use it in order to assign other attributes - doing so without using reflection ? The code : I would like to do something like this : <code> public class CashierOut : BaseActivity { [ Description ( `` Flag indicates whether break to execution . '' ) ] [ DefaultValue ( false ) ] [ MyCustomAttribute ( ParameterGroups.Extended ) ] public bool CancelExecution { get ; set ; } [ Description ( `` Flag indicates whether allow exit before declation . '' ) ] [ DefaultValue ( true ) ] [ MyCustomAttribute ( ParameterGroups.Extended ) ] [ DisplayName ( `` Exit before declaration ? '' ) ] public bool AllowExitBeforeDeclare { get ; set ; } } public class CashierOut : BaseActivity { [ MyResourceCustom ( `` CashierOut.CancelExecution '' ) ] public bool CancelExecution { get ; set ; } [ MyResourceCustom ( `` CashierOut.AllowExitBeforeDeclare '' ) ] public bool AllowExitBeforeDeclare { get ; set ; } } public sealed class MyResourceCustom : Attribute { public string ResourcePath { get ; private set ; } public ParameterGroupAttribute ( string resourcePath ) { ResourcePath = resourcePath ; // Get attributes attributes value from external resource using the path . } } | C # Attributes : One Attribute to Rule Them All ? |
C_sharp : I have to save 2 different groups of settings in my root settings group . It should looks like this : The Nuance is that I have to save it one after another in different places in my code . ( For example , GROUP_1 can be a connection strings and GROUP_2 is some environment settings and they both together are filling by users in different sections of my application ) I made this simple test class to get the expected resultBUT for some reason the result of this code is differentThe ROOT_GROUP node is duplicated and of course visual studio throws me an exception that ROOT_GROUP is already exists . Obviously , my problem is hidden in method SaveGroup2 ( ) when I add new nested group to existed root group and then save it - but why ? UPD I 've just added new methodAnd replace it in testAnd got this strange behaviourAs you can see , the strangeness is in that the result is totally expected . ROOT_GROUP was n't duplicate , as I needed it , but why it does in SaveGroup2 ( ) ? Did I miss something in SaveGroup2 ( ) ? UPD2 - HACKJust tried a simple idea - what if I would clear the root_group before adding a new nested element to it ? And how do you probably guess - it works ! I think it looks like a bug or there are some hidden things that I missed . Can somebody explain me what did I do wrong ? <code> < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < configuration > < configSections > < sectionGroup name= '' ROOT_GROUP '' > < sectionGroup name= '' GROUP_1 '' > ... ... ... ... ... ... ... ... some_settings ... ... ... ... ... ... ... ... < /sectionGroup > < sectionGroup name= '' GROUP_2 '' > ... ... ... ... ... ... ... ... some_other_settings ... ... ... ... ... ... ... ... < /sectionGroup > < /sectionGroup > < /configSections > ... ... ... ... ... ... ... ... ... ... ..other_system_tags ... ... ... ... ... ... ... ... ... ... .. < /configuration > [ TestFixture ] public class Tttt { private string ROOT_GROUP = `` ROOT_GROUP '' ; private string GROUP_1 = `` GROUP_1 '' ; private string GROUP_2 = `` GROUP_2 '' ; [ Test ] public void SaveSettingsGroups ( ) { SaveGroup1 ( ) ; SaveGroup2 ( ) ; Assert.True ( true ) ; } private Configuration GetConfig ( ) { var configFilePath = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile ; var map = new ExeConfigurationFileMap { ExeConfigFilename = configFilePath } ; var config = ConfigurationManager.OpenMappedExeConfiguration ( map , ConfigurationUserLevel.None ) ; return config ; } private void SaveGroup1 ( ) { var config = GetConfig ( ) ; var root = new UserSettingsGroup ( ) ; config.SectionGroups.Add ( ROOT_GROUP , root ) ; config.Save ( ConfigurationSaveMode.Modified ) ; ConfigurationManager.RefreshSection ( root.Name ) ; var nested = new UserSettingsGroup ( ) ; root.SectionGroups.Add ( GROUP_1 , nested ) ; config.Save ( ConfigurationSaveMode.Modified ) ; ConfigurationManager.RefreshSection ( nested.Name ) ; } private void SaveGroup2 ( ) { var config = GetConfig ( ) ; var root = config.GetSectionGroup ( ROOT_GROUP ) ; var nested = new UserSettingsGroup ( ) ; root.SectionGroups.Add ( GROUP_2 , nested ) ; config.Save ( ConfigurationSaveMode.Modified ) ; ConfigurationManager.RefreshSection ( nested.Name ) ; } } < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < configuration > < configSections > < sectionGroup name= '' ROOT_GROUP '' > < sectionGroup name= '' GROUP_1 '' > ... ... ... ... ... ... ... ... some_settings ... ... ... ... ... ... ... ... < /sectionGroup > < /sectionGroup > < sectionGroup name= '' ROOT_GROUP '' > < sectionGroup name= '' GROUP_2 '' > ... ... ... ... ... ... ... ... some_other_settings ... ... ... ... ... ... ... ... < /sectionGroup > < /sectionGroup > < /configSections > ... ... ... ... ... ... ... ... ... ... ..other_system_tags ... ... ... ... ... ... ... ... ... ... .. < /configuration > private void SaveGroup3 ( ) { var config = GetConfig ( ) ; var root = config.GetSectionGroup ( ROOT_GROUP ) ; var nested1 = root.SectionGroups.Get ( 0 ) ; var nested2 = new UserSettingsGroup ( ) ; var nested3 = new UserSettingsGroup ( ) ; nested1.SectionGroups.Add ( `` GROUP_2 '' , nested2 ) ; root.SectionGroups.Add ( `` GROUP_3 '' , nested3 ) ; config.Save ( ConfigurationSaveMode.Modified ) ; ConfigurationManager.RefreshSection ( nested2.Name ) ; ConfigurationManager.RefreshSection ( nested3.Name ) ; } [ Test ] public void SaveSettingsGroups ( ) { SaveGroup1 ( ) ; SaveGroup3 ( ) ; Assert.True ( true ) ; } < sectionGroup name= '' ROOT_GROUP '' > < sectionGroup name= '' GROUP_1 '' > < sectionGroup name= '' GROUP_2 '' > < /sectionGroup > < /sectionGroup > < sectionGroup name= '' GROUP_3 '' > < /sectionGroup > < /sectionGroup > private void SaveGroup2 ( ) { var config = GetConfig ( ) ; var root = config.GetSectionGroup ( ROOT_GROUP ) ; var nested = new ConfigurationSectionGroup ( ) ; //Copy exiting nested groups to array var gr = new ConfigurationSectionGroup [ 5 ] ; root.SectionGroups.CopyTo ( gr,0 ) ; gr [ 1 ] = nested ; // < ! -- -- root.SectionGroups.Clear ( ) ; config.Save ( ConfigurationSaveMode.Modified ) ; ConfigurationManager.RefreshSection ( root.Name ) ; root.SectionGroups.Add ( gr [ 0 ] .Name , gr [ 0 ] ) ; root.SectionGroups.Add ( GROUP_2 , gr [ 1 ] ) ; config.Save ( ConfigurationSaveMode.Modified ) ; ConfigurationManager.RefreshSection ( root.Name ) ; } < sectionGroup name= '' ROOT_GROUP '' > < sectionGroup name= '' GROUP_1 '' type= '' System.Configuration.UserSettingsGroup , System , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 '' > < /sectionGroup > < sectionGroup name= '' GROUP_2 '' type= '' System.Configuration.ConfigurationSectionGroup , System.Configuration , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=b03f5f7f11d50a3a '' > < /sectionGroup > < /sectionGroup > | App.config add nested group to existing node |
C_sharp : I have the following XML data . I need to present them on ASP.NET web page in a hierarchical tabular format.XML : Expected Output : where ( - ) is tree view 's expand/collapse control . Is it possible to achieve this using ASP.NET Data Grid ? Any code example would be really useful . <code> < Developers > < Region name= '' UK '' > < Region name= '' England '' > < Region name= '' London '' > < Data Date= '' 01-01-2019 '' > < Value name= '' DotNet '' > 100 < /Value > < /Data > < Data Date= '' 01-01-2020 '' > < Value name= '' DotNet '' > 200 < /Value > < Value name= '' Java '' > 300 < /Value > < /Data > < /Region > < Region name= '' Other '' > < Data Date= '' 01-01-2019 '' > < Value name= '' DotNet '' > 400 < /Value > < /Data > < Data Date= '' 01-06-2019 '' > < Value name= '' DotNet '' > 500 < /Value > < /Data > < /Region > < /Region > < Region name= '' Scotland '' > < Data Date= '' 01-01-2019 '' > < Value name= '' DotNet '' > 600 < /Value > < /Data > < /Region > < /Region > < Region name= '' France '' > < Data Date= '' 01-06-2020 '' > < Value name= '' DotNet '' > 700 < /Value > < /Data > < /Region > < Region name= '' Germany '' > < Data Date= '' 01-06-2019 '' > < Value name= '' Java '' > 800 < /Value > < /Data > < /Region > < /Developers > | Show hierarchical xml data using ASP.NET Grid |
C_sharp : I am curious why the following throws an error message ( text reader closed exception ) on the `` last '' assignment : However the following executes fine : What is the reason for the different behavior ? <code> IEnumerable < string > textRows = File.ReadLines ( sourceTextFileName ) ; IEnumerator < string > textEnumerator = textRows.GetEnumerator ( ) ; string first = textRows.First ( ) ; string last = textRows.Last ( ) ; IEnumerable < string > textRows = File.ReadLines ( sourceTextFileName ) ; string first = textRows.First ( ) ; string last = textRows.Last ( ) ; IEnumerator < string > textEnumerator = textRows.GetEnumerator ( ) ; | Why does IEumerator < T > affect the state of IEnumerable < T > even the enumerator never reached the end ? |
C_sharp : How can I make a linq search that ignores nulls ( or nullables ) ? I have a method And I want it to return matches on any of the ints ? that are not null.IE : if a and c have values 1 and 9 and b is null the search should render ( roughly ) toMy real method will have 5+ paramters , so iterating combinations is right out . <code> IEnumerable < X > Search ( int ? a , int ? b , int ? c ) SELECT * FROM [ TABLE ] WHERE a = 1AND c = 9 | Linq search that ignores nulls |
C_sharp : I have a problem with my code where I try to save a many to many connection between two objects , but for some reason it does n't get saved.We used the code first method to create our database , in our database we have the following entities where this problem is about : The table ProductTagProducts got automatically created , which is of course just a connection table between the two.Now creating products works fine . We can just run the following and it will create the connnections in the ProductTagProducts table : To make sure no duplicate tasks are in the database , we handle the saving for it ourselves . The productTag always contains a product tag with an existing ID.The problem occurs when we want to edit the same or another product . There are existing tags for the product . And we use the following process to save it : We split the tags by comma , that 's how it is received from the HTML element . Then we define a new entity for it and use InsertAndOrUse to determine if the tag already existed . If the tag already existed , it returns the same entity but with the ID filled in , if it did not exist yet it adds the tag to the database , and then also returns the entity with ID . We create a new list to be sure that the product does n't have duplicate Id 's in there ( I have tried it with adding it to the product 's existing tag list directly , same result ) .Then we set the list to ProductTags and let the repository handle the insert or update , of course , an update will be done . Just in case , this is the InsertOrUpdate function : The save method just calls the context 's SaveChanges method . When I edit the product , and add another tag it does n't save the new tag . However , when I set a breakpoint on the save function I can see that they are both there : And when I open the newly added tag 'Oeh-la-la ' I can even refer back to the product through it : But when the save happens , which succeeds with all other values , there are no connections made in the ProductTagProducts table . Maybe it is something really simple , but I am clueless at the moment . I really hope that someone else can give a bright look.Thanks in advance.Edit : As requested the ProductTag 's InsertAndOrUse method . The InsertOrUpdate method it calls is exactly the same as above . <code> public class Product { public int Id { get ; set ; } public string Name { get ; set ; } public virtual ICollection < ProductTag > ProductTags { get ; set ; } } public class ProductTag { public int Id { get ; set ; } public string Name { get ; set ; } public virtual ICollection < Product > Products { get ; set ; } } Product.ProductTags.Add ( productTag ) ; List < ProductTag > productTags = new List < ProductTag > ( ) ; string [ ] splittedTags = productLanguagePost.TagList.Split ( ' , ' ) ; foreach ( string tag in splittedTags ) { ProductTag productTag = new ProductTag ( ) ; productTag.Name = tag ; productTags.Add ( productTagRepository.InsertAndOrUse ( productTag ) ) ; } product.ProductTags = productTags ; productRepository.InsertOrUpdate ( product ) ; productRepository.Save ( ) ; public void InsertOrUpdate ( Product product ) { if ( product.Id == default ( int ) ) { context.Products.Add ( product ) ; } else { context.Entry ( product ) .State = EntityState.Modified ; } } public ProductTag InsertAndOrUse ( ProductTag productTag ) { ProductTag resultingdProductTag = context.ProductTags.FirstOrDefault ( t = > t.Name.ToLower ( ) == productTag.Name.ToLower ( ) ) ; if ( resultingdProductTag ! = null ) { return resultingdProductTag ; } else { this.InsertOrUpdate ( productTag ) ; this.Save ( ) ; return productTag ; } } | No new many to many connections are made in the database when saving an object in EF |
C_sharp : Short version : how does async calls scale when async methods are called thousands and thousands of times in a loop , and these methods might call other async methods ? Will my threadpool explode ? I 've been reading and experimenting with the TPL and Async and after reading a lot of material I 'm still confused about some aspects that I could not find much information about , like how async calls scale . I will try to go straight to the point.Async callsFor IO , I read it is better to use async than a new thread/start a task , but from what I understand , performing an async operation without using a different thread is impossible , which means async must use other threads/start tasks at some point.So my question is : how would code A be better than code B regarding system resources ? Code ACode BWhich leads me to the questions:1 - should async calls be avoided in a loop ? 2 - Is there a reasonable max of async calls that should be fired at a time , or is firing any number of async calls ok ? How does this scale ? 3 - Do async methods , under the hood , start a task for each call ? I tested this with 1000 urls and the number of used threadpool worker threads never even reached 30 , and the number of IO completion threads is always about 5.My Practical ExperimentI created a web application with a simple async controller.The page is composed of a single form with a textarea where the user enters all urls he wishes to request/do some work with.Upon submition , the urls are requested in loop using the HttpClient.GetUrlAsync method just like the code A above.An interesting point is that if I submit 1000 urls , it takes about 3 minutes to finish all requests.On the other hand , if I submit 3 forms from 3 different tabs ( i.e . clients ) , each with 1000 urls , it takes much much longer for the result ( about 10 minutes ) , which really got me confused , because as per msdn definition , it should not take much longer than 3 minutes , specially when even while processing all the requests at the same time the number of used threads from the threadpool is approx 25 , which means resources are not being well explored at all ! The way it is working now , this type of application is far from scalable ( say I had about 5000 clients requesting a bunch of urls all the time ) , and I fail to see how asyncis the way to fire multiple IO requests.Further explanation about the applicationClient side:1. user enter the site2 . types 1000 urls in the text area3 . submits the urlsServer side:1. receive urls as an array2 . perform the codenotifies the client that work is donePlease , enlighten me ! Thank you . <code> // an array with 5000 urls.var urls = new string [ 5000 ] ; // list of awaitable tasks.var tasks = new List < Task < string > > ( 5000 ) ; HttpClient httpClient ; foreach ( string url in urls ) { tasks.Add ( httpClient.GetStringAsync ( url ) ) ; } await Task.WhenAll ( tasks ) ; ... same variables as code A ... foreach ( string url in urls ) { tasks.Add ( Task.Factory.StartNew ( ( ) = > { // This method represents a // synchronous version of the GetStringAsync . httpClient.GetString ( url ) ; } ) ) ; } await Task.WhenAll ( tasks ) ; foreach ( string url in urls ) { tasks.Add ( GetUrlAsync ( url ) ) ; } await Task.WhenAll ( tasks ) ; //at this point the thread is// returned to the pool to receive// further requests . | Async/Await regarding system resources consumption and efficiency |
C_sharp : This project is for educational use and I am very well aware that excellent compilers already exist.I am currently fighting my way through the famous Dragon Book and just started to implement my own Lexer . It works suprisingly well except for literals . I do not understand how to handle literals using symbol ( lookup ) tables and the book does n't seem to cover that very well : In the following code 60 is a numeric literal : The Dragon Book says : Technically speaking , for the lexeme 60 we should make up a token like ( number,4 ) , where 4 points to the symbol table for the internal representation of integer 60 [ ... ] Understood - I created the following Token : And stored the literal in a dictionary like this : Since the literal itself is the key in the Dictionary , that allows me to quickly check if future literals have already been added to the symbol table ( or not ) .The Parser then recieves the Tokens from the Lexer and should be able to identify the literals in the symbol table.Questions : Why should my Token contain a lookup-index instead of containing the literal itself ? Wouldn ' t that be quicker ... How should the Parser be able to quickly find the literal values inside the symbol-table when the lookup-index is the value of the dictionary ? ( I can not make the lookup-index the dictionary-key because the Lexer would then have to check against the value of the dictionary wich is not very performant as well ) Could a multi-indexed-dictionary be a solution ? I guess not ... Must I create a symbol-table for every type of literal then ? F.e . : Dictionary < int literal , int index > and Dictionary < double literal , int index > and Dictionary < char literal , int index > etc.Maybe I am completly on the wrong track with literals . Feel free to post any better solutions . <code> int myIdentifier = 60 ; < enum TokenType , int lookupIndex > //TokenType could be 'number ' and lookupIndex could be any int Dictionary < int literal , int index > //literal could be '60 ' and index could be anything | C # Dragon Book ( Lexical analysis ) How to handle literals |
C_sharp : I am replacing the html on my page when I return dynamically generated html from a REST method called via Ajax like so : It is called from within the ready function ( when a button is clicked ) like so : The string named `` HtmlToDisplay '' ( `` returneddata '' in the Ajax call ) begins like so : As you can see , it does not begin with a spurious/superfluous `` body '' tag , but when I look at the page source via F12 in Chrome Dev Tools , the first thing ( above `` < ! DOCTYPE html > '' and the rest ) is `` < body > '' Why is < body > there ? In the console there in Chrome Dev Tools , there is an err msg `` Uncaught SyntaxError : Unexpected token var '' When I 2-click that , it takes me to the `` < body > '' tag.So not only do I wonder why `` < body > '' is there , but also why Chrome Dev Tools apparently thinks it 's a token named `` var '' I have painstakingly compared the contents of `` HtmlToDisplay '' with the html page source prior to the attempt to replace the original html , and see no significant differences ( just escape ( `` \ '' ) symbols for strings , and such ) .Why might it be that Chrome slaps a < body > tag at the top of my HTML , and why does it take me there when 2-clicking the `` Uncaught SyntaxError : Unexpected token var '' console err msg ? UPDATEWeird as it is , or seems , at least , I do n't think the superfluous/spurious < body > tag is really the problem , because for some reason it is on the unmodified page , too - before I even click the button to replace the html , the page ( View page source ) begins : UPDATE 2This superfluous/spurious `` < body > '' tag apparently came from _Layout.cshtml , which was : When I removed both ( opening and closing ) < body > tags , the mystery was resolved - they no longer appear in the html.I still have the same basic problem , though ; it 's just that the err msg in the console now goes to an empty line above `` < ! DOCTYPE html > '' when 2-clicked.Why does the html start with an empty line , and is this potentially problematic ? The initial blank line of row 1 of the doc appears both in View page source and in Chrome Dev Tools . <code> [ HttpGet ] [ Route ( `` { unit } / { begdate } / { enddate } '' , Name = `` QuadrantData '' ) ] public HttpResponseMessage GetQuadrantData ( string unit , string begdate , string enddate ) { _unit = unit ; _beginDate = begdate ; _endDate = enddate ; string beginningHtml = GetBeginningHTML ( ) ; // This could be called from any page to reuse the same `` header '' string bodyBeginningHtml = GetBodyBeginHTML ( ) ; string top10ItemsPurchasedHtml = GetTop10ItemsPurchasedHTML ( ) ; string pricingExceptionsHtml = GetPriceComplianceHTML ( ) ; string forecastedSpendHtml = GetForecastedSpendHTML ( ) ; string deliveryPerformanceHtml = GetDeliveryPerformanceHTML ( ) ; string endingHtml = GetEndingHTML ( ) ; String HtmlToDisplay = string.Format ( `` { 0 } { 1 } { 2 } { 3 } { 4 } { 5 } { 6 } '' , beginningHtml , bodyBeginningHtml , top10ItemsPurchasedHtml , pricingExceptionsHtml , forecastedSpendHtml , deliveryPerformanceHtml , endingHtml ) ; return new HttpResponseMessage ( ) { Content = new StringContent ( HtmlToDisplay , Encoding.UTF8 , `` text/html '' ) } ; } $ ( document ) .ready ( function ( ) { $ ( `` body '' ) .on ( `` click '' , `` # btnGetData '' , function ( ) { var _begdate = $ ( `` # datepickerFrom '' ) .val ( ) ; var _enddate = $ ( `` # datepickerTo '' ) .val ( ) ; var _unit = $ ( `` # unitName '' ) .text ( ) ; $ ( `` # newhourglass '' ) .removeClass ( `` hide '' ) ; $ .ajax ( { type : 'GET ' , url : ' @ Url.RouteUrl ( routeName : `` QuadrantData '' , routeValuesnew { httpRoute = true , unit = `` un '' , begdate = `` bd '' , enddate = `` ed '' } ) ' .replace ( `` un '' , encodeURIComponent ( _unit ) ) .replace ( `` bd '' , encodeURIComponent ( _begdate ) ) .replace ( `` ed '' , encodeURIComponent ( _enddate ) ) , contentType : 'text/plain ' , cache : false , xhrFields : { withCredentials : false } , success : function ( returneddata ) { $ ( `` body '' ) .html ( returneddata ) ; $ ( `` # newhourglass '' ) .addClass ( `` hide '' ) ; } , error : function ( ) { console.log ( 'error in ajax call to QuadrantData ' ) ; $ ( `` # newhourglass '' ) .addClass ( `` hide '' ) ; } } ) ; } ) ; . . . < ! DOCTYPE html > < html > < head > < meta charset=\ '' utf-8\ '' > < meta name=\ '' viewport\ '' content=\ '' width=device-width , initial-scale=1.0\ '' > < title > eServices Reporting - Customer Dashboard < /title > < link rel=\ '' stylesheet\ '' href=\ '' http : //maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css\ '' > < script src= . . . < body > < ! DOCTYPE html > < html > < head > < body > @ RenderBody ( ) < hr / > < footer > < p > & copy ; @ DateTime.Now.Year - PRO*ACT USA < /p > < /footer > < /body > | Why does Chrome slap a body at the top of my HTML , and then give me a seemingly bogus err msg ? |
C_sharp : I have a loop variable that does not appear to be getting garbage collected ( according to Red -- Gate ANTS memory profiler ) despite having gone out of scope.The code looks something like this : As far as I can tell , a reference to item remains until blockingQueue.dequeue ( ) returns . Is this intended behaviour , or could it be a bug in the memory profiler ? Secondly , if this is intended behaviour how would I force item to get collected at the end of the loop body ? Setting it to null does not appear to cause it to get collected . This is important as the queue could potentially block for a long time and item references a fairly large object tree.Note , the documentation of the profiler says that a GC is performed before taking a memory snapshot , and the reference is not on the finalizer queue.I was able to reproduce the same problem with the code here.UpdateThe code in the gist was slightly flawed in that it legitimately held on to a reference in GetFoo ( ) . Having changed it the object does now get collected when explicitly set to null . However , I believe Hans ' answer explains the situation I 'm seeing in my actual code . <code> while ( true ) { var item = blockingQueue.dequeue ( ) ; // blocks until an item is added to blockingQueue // do something with item } | Loop variable not getting collected |
C_sharp : I 'm getting a strange error with Visual Studio 10 ( and now 11 as well ) . I have an extension methodNow if I callI 'm not at all understanding what 's happening under hood . The annoying part is that the intellisense lists Foo for IEnumberable < T > s . At best it should have given a type ca n't be inferred error.If I call it this way : Why can not type be inferred in the above case ? More : Suppose I have : And if I call : The type inference is so smart here to tell me that Foo should be returning IEnumerable < int > and string is not all that ! ! So if compiler can know Foo is expecting a char as the first argument , then why does n't my first example just compile ? In other words why is that in the first example the compiler know T in that case is char ? As expectedly this works for the second example : I 'm just wondering why ca n't T be inferred as char in first example , after all string is IEnumberable < char > .Edit : I got the answer from SLaks . But it 's so strange that C # does n't do this ( kind of type inference ) considering compiler takes into account the generic constraints as well when exposing the available methods to operate on an object.In other words : makes Foo available on all objects.makes Foo available on all IEnumerable < T > s since it knows S is IEnumerable < T > . So I was thinking C # will be even inferring the type of T ! Thanks everyone ! ; ) <code> public static S Foo < S , T > ( this S s ) where S : IEnumerable < T > { return s ; } `` '' .Foo ( ) ; // = > 'string ' does not contain a definition for 'Foo ' and no extension method 'Foo ' accepting a first argument of type 'string ' could be found ( are you missing a using directive or an assembly reference ? ) Extension.Foo ( `` '' ) ; // = > The type arguments for method 'Extension.Foo < S , T > ( S ) ' can not be inferred from the usage . Try specifying the type arguments explicitly . public static S Foo < S , T > ( this S s , T t ) where S : IEnumerable < T > { return s ; } `` '' .Foo ( 1 ) ; `` '' .Foo ( ' l ' ) ; public static S Foo < S , T > ( this S s ) { return s ; } public static S Foo < S , T > ( this S s ) where S : IEnumerable < T > { return s ; } | Can not find definition though intellisense lists it ? |
C_sharp : I 'm going to retrieve information from a database using LINQ but I do n't know why I 'm getting this error : Invalid object name 'Retriveinfos'.My class is here : and then using this line of code to connect and retrieving information : <code> [ Table ( Name= '' Retriveinfos '' ) ] public class Retriveinfo { [ Column ] public string Name { get ; set ; } [ Column ] public string LastName { get ; set ; } [ Column ( IsPrimaryKey = true ) ] public int Id { get ; set ; } } DataContext dcon = new DataContext ( @ '' Data Source=.\SQLEXPRESS ; AttachDbFilename=F : \Second_School_project\Review_Site\Review_Site\App_Data\ReviewDatabase.mdf ; Integrated Security=True ; User Instance=True '' ) ; Table < Retriveinfo > Retriveinfos = dcon.GetTable < Retriveinfo > ( ) ; var c = from d in Retriveinfos where d.Id == 1 select new { d.Name , d.LastName } ; foreach ( var a in c ) Response.Write ( a.Name.ToString ( ) + `` `` + a.LastName.ToString ( ) ) ; | Retrieving info from database |
C_sharp : I 'm taking an algorithm course at the university , and for one of my projects I want to implement a red-black tree in C # ( the implementation itself is n't the project , yet just something i decided to choose to help me out ) .My red-black tree should hold string keys , and the object i created for each node looks like this : I already added some basic methods for printing the tree , finding the root , min/max key ( by alphabet ) , etc ... I 'm having trouble inserting nodes ( hence , building the tree ) .Whoever 's familiar with red-black trees knows that when adding a node to one side , you could have changed the balance of the tree.To fix this , you need to `` rotate '' around nodes on the tree in order to balance the tree out.I wrote a RightRotate and LeftRotate method in pseudo-code , and then when i tried to implement it in C # , i ran into a bunch of reference problems with the sRbTreeNode object i created.This is the pseudo-code I wrote for the LeftRotate method : I received a suggestion to implement it straight forward , but without using the 'ref ' keyword , which i tried at first.This is how i did it : Now , when i debug , i see that it works fine , but the objects i pass to this method are only rotated within the scope of the method . When it leaves this method , it seems like there was no change to the actual nodes . That is why i thought of using the 'ref ' keywords in the first place.What am i doing wrong ? <code> class sRbTreeNode { public sRbTreeNode Parent = null ; public sRbTreeNode Right = null ; public sRbTreeNode Left = null ; public String Color ; public String Key ; public sRbTreeNode ( ) { } public sRbTreeNode ( String key ) { Key = key ; } } LeftRotate ( root , node ) y < - node.Right ; node.Right < - y.Left ; if ( y.Left ! = null ) y.Left.Parent < - node ; y.Parent < - node.Parent ; if ( node.Parent = null ) root < - y ; else if ( node = node.Parent.Left ) node.Parent.Left = y ; else node.Parent.Right = y ; y.Left < - node ; node.Parent < - y public static void LeftRotate ( sRbTreeNode root , sRbTreeNode node ) { sRbTreeNode y = node.Right ; node.Right = y.Left ; if ( y.Left ! = null ) y.Left.Parent = node ; y.Parent = node.Parent ; if ( node.Parent == null ) root = y ; else if ( node == node.Parent.Left ) node.Parent.Left = y ; else node.Parent.Right = y ; y.Left = node ; node.Parent = y ; } | C # reference trouble |
C_sharp : The most efficient and typical solution that I could think of is : This will return me seven ( 7 ) dates in an array , which is the result I want . I think ruby can do something like this , simply by specifying dots but I ca n't recall.However , is there a more efficient approach ? Or is there any way to implement this using linq ( possibly via the Aggregate method ? ) , if there is , even if it is not the most efficient solution I would be curious to see . Ideally it would not require you to re-declare any object instance for the amount of `` times '' you need though , and allow you to specify DateTime.Now just once and the number of items in the array/list you want just once.Thanks <code> var dates = new DateTime [ 7 ] ; for ( int i = 0 ; i < 7 ; i++ ) dates [ i ] = DateTime.Now.AddDays ( i ) ; | What are some ways to get a list of DateTime.Now.AddDays ( 0..7 ) dynamically ? |
C_sharp : I have done some search on this website to avoid duplication , however most of the questions were about an abstract comparison between interface and abstract class.My question is more to my specific situation especially my colleague and I we do n't agree about the same approach.I have 3 classesNode ( Abstract node in a folder structure ) Folder ( Contains sub folders and files ) FileWe use the composite pattern to get all folders and their permissions per user/groupThe class Node , should it be interface or Abstract class ? Folder and File inherit from Node.In my opinion i think Node should be an abstract because File should not have all methods that Folderhas for example AddFolder ( Node node ) My colleague said that it 's better to use interface for better coding.Edit : I rewrote my Node as follow : <code> public abstract class Node { public string Name { get ; set ; } public string FullName { get ; set ; } public Node Parent { get ; set ; } public List < PermissionEntry > Permissions { get ; set ; } protected Node ( string fullName ) { FullName = fullName ; Permissions = new List < PermissionEntry > ( ) ; } public void AssignPermission ( ) { // some Codes } } | Interface vs. Abstract class ( in specific case ) |
C_sharp : I have text with this structure : I want to get this text : I tried doing the following but it does not workBasically , it should start matching at the start of every line and replace every matched group with # symbol . Currently , if more than one group is matched , everything is replaced by a single # symbol . Pattern I am using is probably incorrect , can anyone come up with a solution ? <code> 1 . Text12 . Text 2 . It has a number with a dot.3 . 1 . Text31 # Text1 # Text 2 . It has a number with a dot . ( notice that this number did not get replaced ) # # Text31 var pattern = @ '' ^ ( \s*\d+\.\s* ) + '' ; var replaced = Regex.Replace ( str , pattern , `` # '' , RegexOptions.Multiline ) ; | Regex replace any number of matches at the start of the line |
C_sharp : There are quite a few options available but none seem to be particularly designed for cases like this.i.e : UnauthorizedAccessException : I/OAccessViolationException : Memory stuffSecurityAccessDeniedException : Represents the security exception that is thrown when a security authorization request fails.etc.Should I create my own type of exception for this ? What exception should be raised when membership users do n't have enough priviledges to invoke a method ? <code> [ WebService ( Namespace = `` http : //service.site.com/service/news '' ) ] [ WebServiceBinding ( ConformsTo = WsiProfiles.BasicProfile1_1 ) ] [ ToolboxItem ( false ) ] [ ScriptService ] public class NewsService : System.Web.Services.WebService { [ WebMethod ] [ ScriptMethod ] public void DoPost ( string title , string markdown , int categoryId ) { if ( ! MembershipHelper.IsAtLeast ( RoleName.Administrator ) ) throw new AuthenticationException ( ) ; // ... } } | C # What exception should I raise here ? |
C_sharp : I have this code : How to get value of CustomAttribute for instance a ? <code> [ MyAttribute ( CustomAttribute= '' Value '' ) ] class MyClass { // some code } Main ( ) { MyClass a = new MyClass ( ) ; } | How to get attributes value |
C_sharp : I am uploading data to databases but my form upload the same data twice in databases first I was uploading data without checking weather is inserted or not it was working fine it was uploading the data single time now I have put the checked that if data inserted than show the message data inserted successful but this is uploading data twice.Here is my code : <code> SqlConnection conn1 = new SqlConnection ( `` Data Source=ZAZIKHAN\\SQLEXPRESS ; Initial Catalog=resume ; Integrated Security=True '' ) ; conn1.Open ( ) ; SqlCommand cmd3 = new SqlCommand ( `` insert into Profile ( Id , Name , JobTitle , Phone , Email , Address , Website , Facebook , Twitter , GooglePlus , Skype , Picture , WhyMeText ) values ( ' '' +ID.Text+ '' ' , ' '' + TextBox1.Text + `` ' , ' '' + TextBox2.Text + `` ' , ' '' + TextBox3.Text + `` ' , ' '' + TextBox4.Text + `` ' , ' '' + TextBox5.Text + `` ' , ' '' + TextBox6.Text + `` ' , ' '' + TextBox7.Text + `` ' , ' '' + TextBox8.Text + `` ' , ' '' + TextBox9.Text + `` ' , ' '' + TextBox10.Text + `` ' , ' '' + uploadFolderPath + `` ' , ' '' + TextArea1.InnerText + `` ' ) '' , conn1 ) ; cmd3.ExecuteNonQuery ( ) ; if ( cmd3.ExecuteNonQuery ( ) == 1 ) { Response.Write ( `` < script LANGUAGE='JavaScript ' > alert ( 'information saved Successful ' ) < /script > '' ) ; TextBox1.Text = `` '' ; TextBox2.Text = `` '' ; TextBox3.Text = `` '' ; TextBox4.Text = `` '' ; TextBox5.Text = `` '' ; TextBox6.Text = `` '' ; TextBox7.Text = `` '' ; TextBox8.Text = `` '' ; TextBox9.Text = `` '' ; TextBox10.Text = `` '' ; TextArea1.InnerText = `` '' ; } else { Response.Write ( `` < script LANGUAGE='JavaScript ' > alert ( 'sorry try again ' ) < /script > '' ) ; } conn1.Close ( ) ; | Web form upload same data twice in database |
C_sharp : In C # , instances of reference types are passed to functions as a nullable pointer . Consider for example : In most cases , the function will expect a non-null pointer ( in 95 % of all cases in my experience ) . What is the best way to document the fact that this function expects a non-null pointer ? Update : thanks a lot for your responses so far ! <code> public void f ( Class classInstanceRef ) | How to document the `` non-nullableness '' of reference types in C # ? |
C_sharp : Why does the following cause a compilation error ? Note : The same error would occur if class XY : IX and where T : IX . However , I have chosen a more complex example because a simpler one might have provoked circumventive answers such as , `` Just change the type of xy from T to IX '' , which would not answer why this conversion fails . <code> interface IX { } interface IY { } class XY : IX , IY { } void Foo < T > ( ) where T : IX , IY { T xy = new XY ( ) ; … // ^^^^^^^^ } // error : `` Implicit conversion of type 'XY ' to 'T ' is not possible . '' | Why are conversions from `` class A : IX '' to generic `` T where T : IX '' not allowed ? |
C_sharp : I would like to write a static instance property in a base class and derive this , but I am facing some problems.Here is the code for the base class - I currently have : As you can see its primary use is for WPF Resources like Converts , where you normally declare a key in XAML thats static to get this instance also for Codebehind Binding Creation.With this it should be possible to just write to get the resource declared in XAML : Now this works fine in the base class obviosly.the MethodBase.GetCurrentMethod ( ) .DeclaringType.Name willalways return `` ResourceInstance '' , and I hoped to get the derivedclass name , since in our Application the ClassName == ResourceKeyResharper , always complain about the fast that I am accessing astatic property from the derived class and wants me to access itthrough the base classHere is an example of a derived class : Hope you can help , thx . <code> public abstract class ResourceInstance < T > { private static T _instance ; public static T Instance { get { if ( _instance ! = null ) return _instance ; var method = MethodBase.GetCurrentMethod ( ) ; var declaringType = method.DeclaringType ; if ( declaringType ! = null ) { var name = declaringType.Name ; _instance = ( T ) Application.Current.TryFindResource ( name ) ; } return _instance ; } } } var fooConverter = FooConverter.Instance ; public abstract class BaseConverter : ResourceInstance < IValueConverter > , IValueConverter { public virtual object Convert ( object value , Type targetType , object parameter , CultureInfo culture ) { return value ; } public virtual object ConvertBack ( object value , Type targetType , object parameter , CultureInfo culture ) { return value ; } } public class FooConverter : BaseConverter { public override object Convert ( object value , Type targetType , object parameter , CultureInfo culture ) { return true ; } } | Static Instance Base/Derived class |
C_sharp : Or possibly there is a better way . I am building a dynamic query builder for NHibernate , we do n't want to put HQL directly into the application , we want it as ORM agnostic as possible . It looks like this currently : ok , great , however ... . there are two things in here that pose a problem : This query only handles `` and , '' my initial thought is to pass is to build a method to dynamically build the dictionary that takes the property name , value , and an operator `` and '' or `` or '' and builds the dictionary along with an array of operators . Does that sound like the right thing to do ? Ok , so , this works GREAT , however , when there is an integer it fails because of the single quotes . What I think would be the BEST way is have the dictionary accept < T.Property , string > and then reflect into T.Property to find the datatype and behave accordingly . Am I over complicating this ? Thank you . <code> public override IEnumerable < T > SelectQuery ( Dictionary < string , string > dictionary ) { string t = Convert.ToString ( typeof ( T ) .Name ) ; string criteria = string.Empty ; foreach ( KeyValuePair < string , string > item in dictionary ) { if ( criteria ! = string.Empty ) criteria += `` and `` ; criteria += item.Key + `` = ' '' + item.Value + `` ' '' ; } string query = `` from `` + t ; if ( criteria ! = string.Empty ) query += `` where `` + criteria ; return FindByHql ( query ) ; } | Can I pass in T.Property ? Also , ideas for improving this method ? |
C_sharp : Let 's say I have the following regex : Then I have the string : Here is my program : What I want to know is if there is any way to to get the regular expression part that matched ? In this case : I ca n't find it anywhere in the object , but one would think it would be accessible . <code> var r = new Regex ( `` Space ( ? < entry > [ 0-9 ] { 1,3 } ) '' ) ; `` Space123 '' void Main ( ) { Regex r = new Regex ( `` Space ( ? < entry > [ 0-9 ] { 1,3 } ) '' , RegexOptions.ExplicitCapture ) ; foreach ( Match m in r.Matches ( `` Space123 '' ) ) { m.Groups [ `` entry '' ] .Dump ( ) ; //Dump ( ) is linqpad to echo the object to console } } ( ? < entry > [ 0-9 ] { 1,3 } ) | Get named group subpattern from .NET regex object |
C_sharp : What is the difference between two variable 's ToString Calling ? Does calling i.ToString ( ) will make i first boxed then call ToString or i is already boxed before calling ToString ( ) ? <code> int i = 0 ; i.ToString ( ) ; | difference between ValueType.ToString and ReferenceType.ToString |
C_sharp : I am trying to make a custom TabControl that supports scrolling but keeps the original look and feel of the TabControl , obviously with the exception that it scrolls.To begin I chose to edit a copy of the original template TabControl used.Then I put a ScrollViewer around the TabPanel . However , this has caused a minor issue where the tabs now have a border at the bottom of them when they are selected . This can be seen below by comparing the normal TabControl and the styled TabControl in the image.At first I assumed this was the z indexing of the scroll viewer but after trying different values and making sure the z index of the scroll viewer and TabPanel are both explicitly higher than the Border 's z index , it made no difference.How can I achieve the same effect where there is no border at the bottom of the selected tab , whilst it is wrapped in a ScrollViewer ? MainWindow.xaml <code> < Window x : Class= '' ScrollableTabControl.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' mc : Ignorable= '' d '' Title= '' MainWindow '' Height= '' 450 '' Width= '' 800 '' > < Window.Resources > < SolidColorBrush x : Key= '' TabItem.Selected.Background '' Color= '' # FFFFFF '' / > < SolidColorBrush x : Key= '' TabItem.Selected.Border '' Color= '' # ACACAC '' / > < Style x : Key= '' TabControlStyle1 '' TargetType= '' { x : Type TabControl } '' > < Setter Property= '' Padding '' Value= '' 2 '' / > < Setter Property= '' HorizontalContentAlignment '' Value= '' Center '' / > < Setter Property= '' VerticalContentAlignment '' Value= '' Center '' / > < Setter Property= '' Background '' Value= '' { StaticResource TabItem.Selected.Background } '' / > < Setter Property= '' BorderBrush '' Value= '' { StaticResource TabItem.Selected.Border } '' / > < Setter Property= '' BorderThickness '' Value= '' 1 '' / > < Setter Property= '' Foreground '' Value= '' { DynamicResource { x : Static SystemColors.ControlTextBrushKey } } '' / > < Setter Property= '' Template '' > < Setter.Value > < ControlTemplate TargetType= '' { x : Type TabControl } '' > < Grid x : Name= '' templateRoot '' ClipToBounds= '' true '' SnapsToDevicePixels= '' true '' KeyboardNavigation.TabNavigation= '' Local '' > < Grid.ColumnDefinitions > < ColumnDefinition x : Name= '' ColumnDefinition0 '' / > < ColumnDefinition x : Name= '' ColumnDefinition1 '' Width= '' 0 '' / > < /Grid.ColumnDefinitions > < Grid.RowDefinitions > < RowDefinition x : Name= '' RowDefinition0 '' Height= '' Auto '' / > < RowDefinition x : Name= '' RowDefinition1 '' Height= '' * '' / > < /Grid.RowDefinitions > < ScrollViewer VerticalScrollBarVisibility= '' Disabled '' HorizontalScrollBarVisibility= '' Disabled '' Grid.Column= '' 0 '' Grid.Row= '' 0 '' Panel.ZIndex= '' 1 '' Background= '' Transparent '' > < TabPanel IsItemsHost= '' true '' Margin= '' 2,2,2,0 '' Panel.ZIndex= '' 2 '' Background= '' Transparent '' KeyboardNavigation.TabIndex= '' 1 '' x : Name= '' headerPanel '' / > < /ScrollViewer > < Border x : Name= '' contentPanel '' BorderBrush= '' { TemplateBinding BorderBrush } '' BorderThickness= '' { TemplateBinding BorderThickness } '' Background= '' { TemplateBinding Background } '' Grid.Column= '' 0 '' Panel.ZIndex= '' 0 '' KeyboardNavigation.DirectionalNavigation= '' Contained '' Grid.Row= '' 1 '' KeyboardNavigation.TabIndex= '' 2 '' KeyboardNavigation.TabNavigation= '' Local '' > < ContentPresenter x : Name= '' PART_SelectedContentHost '' ContentSource= '' SelectedContent '' Margin= '' { TemplateBinding Padding } '' SnapsToDevicePixels= '' { TemplateBinding SnapsToDevicePixels } '' / > < /Border > < /Grid > < /ControlTemplate > < /Setter.Value > < /Setter > < /Style > < /Window.Resources > < Grid > < Grid.RowDefinitions > < RowDefinition Height= '' * '' / > < RowDefinition Height= '' * '' / > < /Grid.RowDefinitions > < TabControl Margin= '' 5 '' Grid.Row= '' 0 '' > < TabItem Header= '' Tab 1 '' / > < TabItem Header= '' Tab 2 '' / > < TabItem Header= '' Tab 3 '' / > < /TabControl > < TabControl Margin= '' 5 '' Grid.Row= '' 1 '' Style= '' { DynamicResource TabControlStyle1 } '' > < TabItem Header= '' Tab 1 '' / > < TabItem Header= '' Tab 2 '' / > < TabItem Header= '' Tab 3 '' / > < /TabControl > < /Grid > < /Window > | XAML TabControl Border Issues |
C_sharp : I 'd like to write a Map-Extension Method for ParallelQuery without destroying the parallelism . Problem is , I have no idea how . I am using ParallelQuery because I 'm confident the Multithreading will boost my performance , here 's my code so far : As you can see , this kind of defeats the purpose of parallelism if I am correct . How would I do this correctly ? Thanks to Dykam for pointing out the the Select-Method has exactly the behaviour I want . However , just for learning purposes I 'd like to see how exactly this 'd work , thanks ! <code> public static List < T2 > Map < T , T2 > ( this ParallelQuery < T > source , Func < T , T2 > func ) { List < T2 > result = new List < T2 > ( ) ; foreach ( T item in source ) { result.Add ( func ( item ) ) ; } return result ; } | How to write a Map-Method for ParallelQuery without defeating its purpose ? |
C_sharp : Solved : IntelliSense just does n't show the Extension ! Lets say we got the following extension method in F # : In C # I can call it like this way : But the equivalent VB code to this returns an error , it does n't find the extension method for the type integer : While it 's possible to call the method by the standard way : So where is the difference between handling VB and C # on calling F # code , why is n't the VB environment able to resolve the extension methods ? <code> [ < Extension > ] module Extension = [ < Extension > ] let Increment ( value : System.Int32 ) = value + 1 x.Increment ( ) ; //Result x=1 x.Increment ( ) 'No method called `` Increment ( ) '' for type Int32 Increment ( x ) 'Works | Unable to call F # Extension in VB.Net |
C_sharp : Ok , I have this string Player.Character with this in it `` Average Man { [ Attributes ( Mind 10 ) ( Body 10 ) ( Soul 10 ) ] } '' . And I have this do-loop set up so that it should be going through this string 1 character at a time and seeing if its this `` [ `` while adding each character it checks to another string ContainerName . The thing is ContainerName only has this in it `` [ `` and I want it should have `` Average Man { `` .If some one could help me understand why it that this is happening and possibly a solution that my amature mind could handle I would be most gracious.O ya , here be my code . <code> int count = -1 ; string ContainerName = `` '' ; //Finds Start of containerdo { count = count + 1 ; ContainerName = ContainerName + Player.Character [ count ] .ToString ( ) ; } while ( Player.Character [ count ] .ToString ( ) ! = `` [ `` & & Player.Character.Length - 1 > count ) ; textBox1.Text = ContainerName ; | C # Do-Loop not adding Characters to a string |
C_sharp : I 'm currently working on a web application in asp.net . In certain api-calls it is necessary to compare ListA with a ListB of Lists to determine if ListA has the same elements of any List in ListB . In other words : If ListA is included in ListB.Both collections are queried with Linq of an EF-Code-First db . ListB has either one matching List or none , never more than one . In the worst case ListB has millions of elements , so the comparison needs to be scalable.Instead of doing nested foreach loops , i 'm looking for a pure linq query , which will let the db do the work . ( before i consider multi column index ) To illustrate the structure : Update StructureSince its a EF Database i 'll provide the relevant Object Structure . I 'm not sure if i 'm allowed to post real code , so this example is still generic.The controller ( for the api-call ) wants to serve the right Curve-Object . To identify the right Object , a filter ( ListA ) is provided ( which is in fact a Curve Object ) Now the filter ( ListA ) needs to be compared to the List of Curves in Result ( ListB ) The only way to compare the Curves is by comparing the Points both have . ( So infact comparing Lists ) Curves have around 1 - 50 Points.Result can have around 500.000.000 CurvesIt 's possible to compare by Object-Identity here , because all Objects ( even the filter ) is re-queried of the db . I 'm looking for a way to implement this mechanism , not how to get around this situation . ( e.g . by using multi column index ( altering the table ) ) ( for illustration purposes ) : <code> //In reality Lists are queried of EF var ListA = new List < Element > ( ) ; var ListB = new List < List < Element > > ( ) ; List < Element > solution ; bool flag = false ; foreach ( List e1 in ListB ) { foreach ( Element e2 in ListA ) { if ( e1.Any ( e = > e.id == e2.id ) ) flag = true ; else { flag = false ; break ; } } if ( flag ) { solution = e1 ; break ; } } //List Bclass Result { ... public int Id ; public virtual ICollection < Curve > curves ; ... } class Curve { ... public int Id ; public virtual Result result ; public int resultId ; public virtual ICollection < Point > points ; ... } public class Point { ... public int Id ; ... } class controller { ... public Response serveRequest ( Curve filter ) { foreach ( Curve c in db.Result.curves ) { if ( compare ( filter.points , c.points ) ) return c ; } } } | How to compare list efficiently ? |
C_sharp : I am creating a simple function that creates a random file . To be thread safe , it creates the file in a retry loop and if the file exists it tries again.According to MSDN , the HResult value is derived from COM which would seem to indicate it will only work on Windows , and it specifically lists them as `` Win32 codes '' . But this is in a library which targets .NET Standard and ideally it should work on every platform .NET Standard supports.What I am wondering is whether I can rely on the above approach that uses the value from HResult to be cross-platform ? The documentation is not clear on this point.If not , how do I determine what HResult values to expect on other platforms ? NOTE : There is a similar question Does .NET define common HRESULT values ? , but it was asked before .NET Standard ( and cross-platform support for .NET ) existed , so I can not rely on that answer for this purpose.For now , our codebase only uses:0x00000020 - ERROR_SHARING_VIOLATION0x00000021 - ERROR_LOCK_VIOLATION0x00000050 - ERROR_FILE_EXISTSWe are targeting .NET Standard 1.5 . NOTE : While the accepted answer does satisfy what I asked here , I have a follow-up question How do I make catching generic IOExceptions reliably portable across platforms ? <code> while ( true ) { fileName = NewTempFileName ( prefix , suffix , directory ) ; if ( File.Exists ( fileName ) ) { continue ; } try { // Create the file , and close it immediately using ( var stream = new FileStream ( fileName , FileMode.CreateNew , FileAccess.Write , FileShare.Read ) ) { break ; } } catch ( IOException e ) { // If the error was because the file exists , try again if ( ( e.HResult & 0xFFFF ) == 0x00000050 ) { continue ; } // else rethrow it throw ; } } | Does .NET Standard normalize HResult values across every platform it supports ? |
C_sharp : A compiler that must translate a generic type or method ( in any language , not just Java ) has in principle two choices : Code specialization . The compiler generates a new representation for every instantiation of a generic type or method . For instance , the compiler would generate code for a list of integers and additional , different code for a list of strings , a list of dates , a list of buffers , and so on . Code sharing . The compiler generates code for only one representation of a generic type or method and maps all the instantiations of the generic type or method to the unique representation , performing type checks and type conversions where needed.Java uses code sharing method . I believe C # follows the code specialization method , so all the code below is logical according to me using C # .Assuming this Java code snippet : Code sharing method will lead to this code after type erasure occurs : So my question is : What is the need to precise this initial cast ? : instead of doing simply ( before type erasure , at coding time ) : Is this cast really necessary for the compiler ? Ok , Arrays.copyOf returns Object [ ] and are not directly referenceable by a more specific type without explicit downcast . But ca n't the compiler make an effort in this case since it deals with a generic type ( the return type ! ) ? Indeed , is n't it enough that compilers apply an explicit cast to the method 's caller line ? : UPDATED -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -Thanks to @ ruakh for his answer.Here a sample that proves that explicit cast even just present at compile-time is relevant : Casting to T [ ] is the only way to put some warning to user signaling the cast may not relevant . And indeed , here we end up with a downcast of Object [ ] to String [ ] , which leads to a ClassCastException at runtime.So , to the point saying `` is n't it enough that compilers apply an explicit cast to the method 's caller line '' , the answer is : Developer does n't master this casting since it is created automatically at compilation step , so this runtime feature does n't warn the user to check deeply his code for its safety BEFORE launching compilation . To put it a nutshell , this cast is worth to be present . <code> public class Test { public static void main ( String [ ] args ) { Test t = new Test ( ) ; String [ ] newArray = t.toArray ( new String [ 4 ] ) ; } @ SuppressWarnings ( `` unchecked '' ) public < T > T [ ] toArray ( T [ ] a ) { //5 as static size for the sample ... return ( T [ ] ) Arrays.copyOf ( a , 5 , a.getClass ( ) ) ; } } public class Test { public static void main ( String [ ] args ) { Test t = new Test ( ) ; //Notice the cast added by the compiler here String [ ] newArray = ( String [ ] ) t.toArray ( new String [ 4 ] ) ; } @ SuppressWarnings ( `` unchecked '' ) public Object [ ] toArray ( Object [ ] a ) { //5 as static size for the sample ... return Arrays.copyOf ( a , 5 , a.getClass ( ) ) ; } } ( T [ ] ) Arrays.copyOf ( a , 5 , a.getClass ( ) ) ; Arrays.copyOf ( a , 5 , a.getClass ( ) ) ; ( String [ ] ) t.toArray ( new String [ 4 ] ) ; public static void main ( String [ ] args ) { Test t = new Test ( ) ; String [ ] newArray = t.toArray ( new String [ 4 ] ) ; } public < T > T [ ] toArray ( T [ ] a ) { return ( T [ ] ) Arrays.copyOf ( a , 5 , Object [ ] .class ) ; } | Useless expectation from compiler when dealing with generics ? |
C_sharp : I have a VB class which overloads the Not operator ; this does n't seem to be usable from C # applications.I can use this in VB.NET : I am trying to us this in a C # application but it wo n't build.I get the error Operator ' ! ' can not be applied to operand of type 'MyClass'Can anyone tell me what I am missing ? <code> Public Shared Operator Not ( item As MyClass ) As Boolean Return FalseEnd Operator If Not MyClassInstance Then ' Do somethingEnd If if ( ! MyClassInstance ) { // do something } | Using overloaded VB.NET Not operator from C # |
C_sharp : Possible Duplicate : What is the “ ? ? ” operator for ? Please explain me what is use of `` ? ? '' in below code and what is `` ? ? '' used for . { e.Description = `` The Order Date must not be in the future . `` ; return false ; } the above code is at http : //nettiers.com/EntityLayer.ashxThanks . <code> if ( ( this.OrderDate ? ? DateTime.MinValue ) > DateTime.Today ) | What is use of `` ? ? '' |
C_sharp : I 'm writing an application using Roslyn to syntactically and semantically analyse C # source code . For each type defined in the source code being analysed , I would like to store whether it 's a reference type ( a class ) , a value type ( a struct ) or an interface.What 's the appropriate/official term for a type 's type ? Example : <code> class A { //This type 's type ( A 's type ) is 'class ' ( i.e . a reference type ) . } | What 's the ( official ) term for a type 's type ? |
C_sharp : http : //dotnetpad.net/ViewPaste/s6VZDImprk2_CqulFcDJ1AIf I run this program I get `` list '' sent out to the output . Why does n't this trigger an ambiguous reference error in the compiler ? <code> public class A { public virtual string Go ( string str ) { return str ; } } public class B : A { public override string Go ( string str ) { return base.Go ( str ) ; } public string Go ( IList < string > list ) { return `` list '' ; } } public static void Main ( string [ ] args ) { var ob = new B ( ) ; Console.WriteLine ( ob.Go ( null ) ) ; } | Why does n't this trigger an `` Ambiguous Reference Error '' ? |
C_sharp : That is , I have a method such as the following : I would like to call this method from the command line , by reading the standard array of command line arguments . The obvious way to do it would be as follows : Is it possible to do this in a more concise way ? <code> public static int CreateTaskGroup ( string TaskGroupName , string Market = `` en-us '' , string Project = `` MyProject '' , string Team = `` DefaultTeam '' , string SatelliteID= '' abc '' ) ; if ( args.Length == 1 ) CreateTaskGroup ( args [ 0 ] ) ; if ( args.Length == 2 ) CreateTaskGroup ( args [ 0 ] , args [ 1 ] ) ; if ( args.Length == 3 ) CreateTaskGroup ( args [ 0 ] , args [ 1 ] , args [ 2 ] ) ; | In C # , is it possible to call a method ( which has default parameters ) with `` as many parameters as I have '' ? |
C_sharp : I 'm just asking this , because the same happened to me when trying to iterate over a DataRowCollection : I saw @ Marc Gravell answer in Why is there no Intellisense with 'var ' variables in 'foreach ' statements in C # ? , and now it 's clear to me why this is happening.I decided to take a look at the code of the DataRowCollection class , and GetEnumerator ( ) is : where list is a DataRowTree type that inherits the abstract class RBTree < K > ( by the way , never knew there was an implementation of a Red-Black Tree in .NET before ) which implements IEnumerable instead of IEnumerable < K > .Is too hard to make RBTree < K > implement IEnumerable < K > ? That would solve the main problem here.I suppose it was developed like this in previous versions of .NET , but that does n't really make sense anymore , does it ? My question is : Is .NET old code updated in new releases ? ( for example , make DataRowCollection implement IEnumerable < DataRow > instead of IEnumerable ) <code> DataSet s ; ... foreach ( var x in s.Tables [ 0 ] .Rows ) { //IntelliSense does n't work here . It takes ' x ' as an object . } return this.list.GetEnumerator ( ) ; | Is .NET old code updated in new releases ? |
C_sharp : In C # , would there be any difference in performance when comparing the following THREE alternatives ? ONETWOTHREE <code> void ONE ( int x ) { if ( x == 10 ) { int y = 20 ; int z = 30 ; // do other stuff } else { // do other stuff } } void TWO ( int x ) { int y ; int z ; if ( x == 10 ) { y = 20 ; z = 30 ; // do other stuff } else { // do other stuff } } void THREE ( int x ) { int y = 20 ; int z = 30 ; if ( x == 10 ) { // do other stuff } else { // do other stuff } } | will declaring variables inside sub-blocks improve performance ? |
C_sharp : I have several bool elements and I am checking it if returns me false.I want if one of p* ( ) returns false in any case i returns false.Is it right way or two false returns true ? I want all p* ( ) return true i returns true.. <code> bool i = false ; switch ( idcount ) { case 1 : i = p1 ( ) ; break ; case 2 : i = p1 ( ) & p2 ( ) ; break ; case 3 : i = p1 ( ) & p2 ( ) & p3 ( ) ; break ; case 4 : i = p1 ( ) & p2 ( ) & p3 ( ) & p4 ( ) ; break ; case 5 : i = p1 ( ) & p2 ( ) & p3 ( ) & p4 ( ) & p5 ( ) ; break ; case 6 : i = p1 ( ) & p2 ( ) & p3 ( ) & p4 ( ) & p5 ( ) & p6 ( ) ; break ; case 7 : i = p1 ( ) & p2 ( ) & p3 ( ) & p4 ( ) & p5 ( ) & p6 ( ) & p7 ( ) ; break ; } return i ; | Check severeal boolean returns in same time |
C_sharp : I have a helper method for my unit tests that asserts that a specific sequence of events were raised in a specific order . The code is as follows : Example usage is as follows : And the code under test : So the test expects FuelFilled to be fired before FuelChanged but in actuality FuelChanged is fired first , which fails the test.However my test is instead reporting that FuelChanged is being fired twice , but when I step through the code it is clear that FuelFilled is fired after FuelChanged and FuelChanged is only fired once.I assumed that it was something to do with the way lambdas work with local state , maybe the for loop iterator variable was only ever set to the final value , so I replaced the for loop with this : However the result is the same , fired contains { 1 ; 1 } instead of { 1 ; 0 } .Now I 'm wondering if the same lambda is being assigned to both events instead of using the different subscription / index state . Any ideas ? Update : I was unable to get success with either answer posted so far ( same as my initial results ) , despite their similarities to my actual code , so I presume the issue is located elsewhere in my FuelTank code . I 've pasted the full code for FuelTank below : FuelEventArgs looks like this : The FireEvent extension method is looks like this : The full test code can be found above in the question , there is no other code called during test execution.I am using NUnit test framework via the Unity Testing Tools plugin for the Unity3D engine , .NET version 3.5 ( ish , it 's closer to Mono 2.0 , I believe ) , and Visual Studio 2013.Update 2 : After extracting the code and tests to their own project ( outside of the Unity3D ecosystem ) all tests run as expected , so I 'm going to have to chalk this one up to a bug in the Unity - > Visual Studio bridge . <code> public static void ExpectEventSequence ( Queue < Action < EventHandler > > subscribeActions , Action triggerAction ) { var expectedSequence = new Queue < int > ( ) ; for ( int i = 0 ; i < subscribeActions.Count ; i++ ) { expectedSequence.Enqueue ( i ) ; } ExpectEventSequence ( subscribeActions , triggerAction , expectedSequence ) ; } public static void ExpectEventSequence ( Queue < Action < EventHandler > > subscribeActions , Action triggerAction , Queue < int > expectedSequence ) { var fired = new Queue < int > ( ) ; var actionsCount = subscribeActions.Count ; for ( var i =0 ; i < actionsCount ; i++ ) { subscription ( ( o , e ) = > { fired.Enqueue ( i ) ; } ) ; } triggerAction ( ) ; var executionIndex = 0 ; var inOrder = true ; foreach ( var firedIndex in fired ) { if ( firedIndex ! = expectedSequence.Dequeue ( ) ) { inOrder = false ; break ; } executionIndex++ ; } if ( subscribeActions.Count ! = fired.Count ) { Assert.Fail ( `` Not all events were fired . `` ) ; } if ( ! inOrder ) { Assert.Fail ( string.Format ( CultureInfo.CurrentCulture , `` Events were not fired in the expected sequence from element { 0 } '' , executionIndex ) ) ; } } [ Test ( ) ] public void FillFuel_Test ( [ Values ( 1 , 5 , 10 , 100 ) ] float maxFuel ) { var fuelTank = new FuelTank ( ) { MaxFuel = maxFuel } ; var eventHandlerSequence = new Queue < Action < EventHandler > > ( ) ; eventHandlerSequence.Enqueue ( x = > fuelTank.FuelFull += x ) ; //Dealing with a subclass of EventHandler eventHandlerSequence.Enqueue ( x = > fuelTank.FuelChanged += ( o , e ) = > x ( o , e ) ) ; Test.ExpectEventSequence ( eventHandlerSequence , ( ) = > fuelTank.FillFuel ( ) ) ; } public float Fuel { get { return fuel ; } private set { var adjustedFuel = Math.Max ( 0 , Math.Min ( value , MaxFuel ) ) ; if ( fuel ! = adjustedFuel ) { var oldFuel = fuel ; fuel = adjustedFuel ; RaiseCheckFuelChangedEvents ( oldFuel ) ; } } } public void FillFuel ( ) { Fuel = MaxFuel ; } private void RaiseCheckFuelChangedEvents ( float oldFuel ) { FuelChanged.FireEvent ( this , new FuelEventArgs ( oldFuel , Fuel ) ) ; if ( fuel == 0 ) { FuelEmpty.FireEvent ( this , EventArgs.Empty ) ; } else if ( fuel == MaxFuel ) { FuelFull.FireEvent ( this , EventArgs.Empty ) ; } if ( oldFuel == 0 & & Fuel ! = 0 ) { FuelNoLongerEmpty.FireEvent ( this , EventArgs.Empty ) ; } else if ( oldFuel == MaxFuel & & Fuel ! = MaxFuel ) { FuelNoLongerFull.FireEvent ( this , EventArgs.Empty ) ; } } var subscriptions = subscribeActions.ToList ( ) ; foreach ( var subscription in subscriptions ) { subscription ( ( o , e ) = > { var index = subscriptions.IndexOf ( subscription ) ; fired.Enqueue ( index ) ; } ) ; } public class FuelTank { public FuelTank ( ) { } public FuelTank ( float initialFuel , float maxFuel ) { MaxFuel = maxFuel ; Fuel = initialFuel ; } public float Fuel { get { return fuel ; } private set { var adjustedFuel = Math.Max ( 0 , Math.Min ( value , MaxFuel ) ) ; if ( fuel ! = adjustedFuel ) { var oldFuel = fuel ; fuel = adjustedFuel ; RaiseCheckFuelChangedEvents ( oldFuel ) ; } } } private float maxFuel ; public float MaxFuel { get { return maxFuel ; } set { if ( value < 0 ) { throw new ArgumentOutOfRangeException ( `` MaxFuel '' , value , `` Argument must be not be less than 0 . `` ) ; } maxFuel = value ; } } private float fuel ; public event EventHandler < FuelEventArgs > FuelChanged ; public event EventHandler FuelEmpty ; public event EventHandler FuelFull ; public event EventHandler FuelNoLongerEmpty ; public event EventHandler FuelNoLongerFull ; public void AddFuel ( float fuel ) { Fuel += fuel ; } public void ClearFuel ( ) { Fuel = 0 ; } public void DrainFuel ( float fuel ) { Fuel -= fuel ; } public void FillFuel ( ) { Fuel = MaxFuel ; } private void RaiseCheckFuelChangedEvents ( float oldFuel ) { FuelChanged.FireEvent ( this , new FuelEventArgs ( oldFuel , Fuel ) ) ; if ( fuel == 0 ) { FuelEmpty.FireEvent ( this , EventArgs.Empty ) ; } else if ( fuel == MaxFuel ) { FuelFull.FireEvent ( this , EventArgs.Empty ) ; } if ( oldFuel == 0 & & Fuel ! = 0 ) { FuelNoLongerEmpty.FireEvent ( this , EventArgs.Empty ) ; } else if ( oldFuel == MaxFuel & & Fuel ! = MaxFuel ) { FuelNoLongerFull.FireEvent ( this , EventArgs.Empty ) ; } } } public class FuelEventArgs : EventArgs { public float NewFuel { get ; private set ; } public float OldFuel { get ; private set ; } public FuelEventArgs ( float oldFuel , float newFuel ) { this.OldFuel = oldFuel ; this.NewFuel = newFuel ; } } public static class EventHandlerExtensions { /// < summary > /// Fires the event . This method is thread safe . /// < /summary > /// < param name= '' handler '' > The handler . < /param > /// < param name= '' sender '' > Source of the event . < /param > /// < param name= '' args '' > The < see cref= '' EventArgs '' / > instance containing the event data . < /param > public static void FireEvent ( this EventHandler handler , object sender , EventArgs args ) { var handlerCopy = handler ; if ( handlerCopy ! = null ) { handlerCopy ( sender , args ) ; } } /// < summary > /// Fires the event . This method is thread safe . /// < /summary > /// < typeparam name= '' T '' > The type of event args this handler has . < /typeparam > /// < param name= '' handler '' > The handler . < /param > /// < param name= '' sender '' > Source of the event . < /param > /// < param name= '' args '' > The < see cref= '' EventArgs '' / > instance containing the event data . < /param > public static void FireEvent < T > ( this EventHandler < T > handler , object sender , T args ) where T : EventArgs { var handlerCopy = handler ; if ( handlerCopy ! = null ) { handlerCopy ( sender , args ) ; } } } | Test helper for expected events sequence reporting duplicate events |
C_sharp : I have a simple class that is defined as below.In Main methodIs garbage collector supposed to main reference for Person.p and when exactly will the destructor be called ? <code> public class Person { public Person ( ) { } public override string ToString ( ) { return `` I Still Exist ! `` ; } ~Person ( ) { p = this ; } public static Person p ; } public static void Main ( string [ ] args ) { var x = new Person ( ) ; x = null ; GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ; Console.WriteLine ( Person.p == null ) ; } | Garbage Collector Behavior for Destructor |
C_sharp : I have a string `` THURSDAY 26th JANUARY 2011 '' .When I format this using CultureInfo.ToTitleCase ( ) : It is displayed like this : `` Thursday 26Th January 2011 '' . This is exactly what I need ... except the T in 26Th has been capitalised . Is there any way to stop this from happening as it is a date and looks wrong ? I.e only title-casing characters that do n't have a number directly before them ? <code> var dateString = `` THURSDAY 26th JANUARY 2011 '' ; var titleString = myCultureInfoObject.TextInfo.ToTitleCase ( dateString ) ; | C # ToTitleCase and text-formatted dates/times |
C_sharp : I am writing a c # console client to connect to SignalR service of a server . Using a bit of Wiresharking , Firebugging and examining the ... /signalr/hubs document on the server , I was able to connect on the default `` /signalr '' URL : Now I need to find outWhat hubs are there available on the server to connect to ? ( ask for a list of them ) What methods can I invoke on the hub ? ( ask for a list of them ) What services can I subscribe to ? And what will be the names of the events I will be handling , and the classes of the objects I will be receiving ? The IHubManager interface or HubManagerExtensions class look promising , but I was not even able to find out , what classes implement it and how to use it . Asp.net/signalr offers only basic documentation and tutorials.Thanks in advance for pointing me in the right direction ! <code> var connection = new HubConnection ( `` https : //www.website.com '' ) ; var defaultHub = connection.CreateHubProxy ( `` liveOfferHub '' ) ; connection.Start ( ) .ContinueWith ( task = > { if ( task.IsFaulted ) { Console.WriteLine ( `` Error opening the connection : '' + task.Exception.GetBaseException ( ) ) ; } else { Console.WriteLine ( `` SignalR Connected '' ) ; } } ) .Wait ( ) ; | How to `` get to know '' an undocumented SignalR server ? |
C_sharp : I 'm making an interval collection extension of the famous C # library C5 . The IInterval interface defines an interval with comparable endpoints ( irrelevant members removed ) : This works well in general , since interval endpoints can be anything comparable like integers , dates , or even strings.However , it is sometimes favorable to be able to calculate the duration of an interval . The interval [ 3:5 ) has a duration of 2 , and the interval [ 1PM , 9PM ) has a duration of 8 hours . This is not possible with comparables , since it only gives us the order of elements , not their distance , e.g . it is difficult to give the distance between two strings . The endpoint type basically has to be interval-scaled values.Is there an interface like IComparable < T > , that allows me to compare endpoints in general , but also do stuff like subtracting two endpoints to get a duration , and adding a duration to a low endpoint to get the high endpoint that could be used for an inheriting interface , IDurationInterval < T > : IInterval < T > for instance ? Or more concise : is there an interface for interval-scaled values ? <code> public interface IInterval < T > where T : IComparable < T > { T Low { get ; } T High { get ; } } | Is there an interface in C # for interval-scaled values ? |
C_sharp : I am using EntityFramework to select data from my mssql database . My query looks something like this : This query takes about 10 seconds.This query takes less than 1 second.I just found out that EntityFramework generates two different queries.Query 1 : Query 2 : Is there a way to speed up the first one or another way to do it ? <code> int param = 123456 ; using ( var context = new DatabaseContext ( ) ) { var query = context.Table.AsQueryable ( ) ; var result = query.Where ( o = > o.Id == param ) .ToList ( ) ; } using ( var context = new DatabaseContext ( ) ) { var query = context.Table.AsQueryable ( ) ; var result = query.Where ( o = > o.Id == 123456 ) .ToList ( ) ; } SELECT TOP ( 20 ) [ Project1 ] . [ Id ] AS [ Id ] , [ Project1 ] . [ Name ] AS [ Name ] , FROM ( SELECT [ Project1 ] . [ Id ] AS [ Id ] , [ Project1 ] . [ Name ] AS [ Name ] , row_number ( ) OVER ( ORDER BY [ Project1 ] . [ Id ] DESC ) AS [ row_number ] FROM ( SELECT [ Extent1 ] . [ Id ] AS [ Id ] , [ Extent1 ] . [ Name ] AS [ Name ] FROM [ dbo ] . [ Table ] AS [ Extent1 ] WHERE [ Extent1 ] . [ Id ] = @ p__linq__0 ) AS [ Project1 ] ) AS [ Project1 ] WHERE [ Project1 ] . [ row_number ] > 0ORDER BY [ Project1 ] . [ Id ] DESC -- p__linq__0 : '2932323 ' ( Type = Int32 , IsNullable = false ) SELECT TOP ( 20 ) [ Filter1 ] . [ Id ] AS [ Id ] , [ Filter1 ] . [ Name ] AS [ Name ] FROM ( SELECT [ Extent1 ] . [ Id ] AS [ Id ] , [ Extent1 ] . [ Name ] AS [ Name ] , row_number ( ) OVER ( ORDER BY [ Extent1 ] . [ Id ] DESC ) AS [ row_number ] FROM [ dbo ] . [ Table ] AS [ Extent1 ] WHERE 2932323 = [ Extent1 ] . [ Id ] ) AS [ Filter1 ] WHERE [ Filter1 ] . [ row_number ] > 0ORDER BY [ Filter1 ] . [ Id ] DESC | EntityFramework 6.1.1 with Linq Performance issue |
C_sharp : I am reading the source code of Interactive Extensions and have found a line that I can not understand : I also do not see any relevant remarks in the docs for IsFaulted or Exception properties.Why this line var ignored = t.Exception ; // do n't remove ! is needed in this context ? A related question : I thought that such lines are optimized away in the Release mode , but given the comment and intent here that is not the case ( if the code is correct ) . So why does this line stay in the Release mode ? <code> public static Task < bool > UsingEnumerator ( this Task < bool > task , IDisposable disposable ) { task.ContinueWith ( t = > { if ( t.IsFaulted ) { var ignored = t.Exception ; // do n't remove ! } if ( t.IsFaulted || t.IsCanceled || ! t.Result ) disposable.Dispose ( ) ; } , TaskContinuationOptions.ExecuteSynchronously ) ; return task ; } | C # Tasks - Why a noop line is needed in this case |
C_sharp : About half of the examples I see for Linq queries using the Any method do so by applying it to the results of a Where ( ) call , the other half apply it directly to the collection . Are the two styles always equivalent , or are there cases wheres that they could return different results ? My testing supports the former conclusion ; but edge cases are n't always easy to find . <code> List < MyClass > stuff = GetStuff ( ) ; bool found1 = stuff.Where ( m = > m.parameter == 1 ) .Any ( ) ; bool found2 = stuff.Any ( m = > m.parameter == 1 ) ; | Are Where ( condition ) .Any ( ) and Any ( condition ) equivalent |
C_sharp : I have a rectangle body that is being fired from a canon at a 45degree Angle . The body is also rotated up at a 45 degree angle and I have set the mass to be at the front of the body . The body goes up in the air fine , however , as the body comes back down to earth it does not rotate . Is there a way so that the mass side comes down first ? My real world example is , throwing a tennis ball with a string attached into the air . Currently the string does n't fall behind the ball when gravity comes into affect.Here is my 'ball'Then I do this to fire it : I am guessing there is some setting or calculation I am forgetting . <code> Body = BodyFactory.CreateRectangle ( world , ConvertUnits.ToSimUnits ( texture.Width ) , ConvertUnits.ToSimUnits ( texture.Height ) ,100f , postition , this ) ; Body.Mass = 1 ; Body.LocalCenter = new Vector2 ( ConvertUnits.ToSimUnits ( Texture.Width ) , ConvertUnits.ToSimUnits ( Texture.Height / 2 ) ) ; Body.UserData = this ; Body.BodyType = BodyType.Dynamic ; Body.CollisionCategories = Category.All ; Body.CollidesWith = Category.All ; Body.IgnoreGravity = false ; float ang = BarrelJoint.JointAngle ; Body.Rotation = ang ; Body.ApplyLinearImpulse ( new Vector2 ( ( float ) Math.Cos ( ang ) * 100 , ( float ) Math.Sin ( ang ) * 100 ) ) ; | Body not rotating to face downward with gravity |
C_sharp : I 'm trying to implement a similar method as Tuple < T1 , T2 > .Create < T1 , T2 > ( T1 item1 , T2 item2 ) , but I still have to specify the type parameters whereas Tuple.Create infers them.I think the definition is right . What am I doing wrong ? Here 's my code : <code> public class KeyValuePair < K , V > { public K Key { get ; set ; } public V Value { get ; set ; } public static KeyValuePair < K , V > Create < K , V > ( K key , V value ) { return new KeyValuePair < K , V > { Key = key , Value = value } ; } } | How is Tuple < T1 , T2 > .Create < T1 , T2 > ( T1 item1 , T2 item2 ) implemented ? |
C_sharp : Assuming the following domain entity : I need to know if the user can perform `` Edit '' action . So i 've 2 solutions : Create a CanEdit method inside the User entityCreate a CanEdit Extension Method for User type : Both solution works , but the question is WHEN use standard methods vs using Extensions methods ? <code> public enum Role { User = 0 , Moderator = 1 , Administrator = 2 } public class User { public string FirstName { get ; set ; } public string LastName { get ; set ; } public string Email { get ; set ; } public Role Role { get ; set ; } } public class User { public string FirstName { get ; set ; } public string LastName { get ; set ; } public string Email { get ; set ; } public Role Role { get ; set ; } public bool CanEdit ( ) { return Role == Role.Moderator || Role == Role.Administrator ; } } public static class UserExtensions { public static bool CanEdit ( this User user ) { return user.Role == Role.Moderator || user.Role == Role.Administrator ; } } | Standard Methods vs Extensions Methods |
C_sharp : I 'm having a bit of a problem finding out how to cancel this task in C # . I do n't exactly have a strong understanding of handling threads and I 've tried Googling for some simple code examples to help me out but I 've gotten really no where . Here 's the piece of code I 'm working on : Where `` urls '' is an array of URLs . Is there a simple way to make it so that , when I click a button in my program , the downloading of the URLs is stopped completely ? Also , the code snippet I pasted is in a function which backgroundWorker1 calls , which I suppose might make things a bit more complicated . ( The reason why I have a backgroundWorker is so the UI does n't lock up while it 's downloading URLs . ) If that in any way is a bit confusing , here is an outline of what I was trying to achieve with my code : I have an array of URLs , I 'd like to download every URL asynchronously without locking up the UI.I 'd preferably like the user to stop the program from downloading URLs by clicking a button , pretty much cancelling the thread.When the user clicks the button again , the program downloads the URLs all over again from that array.Thanks in advance . <code> var tasks = urls.Select ( url = > Task.Factory.StartNew ( state = > { using ( var client = new WebClient ( ) ) { lock ( this ) { // code to download stuff from URL } } } , url ) ) .ToArray ( ) ; try { Task.WaitAll ( tasks ) ; } catch ( Exception e ) { textBox2.AppendText ( `` Error : `` + e.ToString ( ) ) ; } | Cancelling a task which retrieves URLs asynchronously |
C_sharp : I ran across this construct in an online tutorial : I had n't seen this syntax before and was n't sure what it meant . I am not even certain that it is valid syntax at all as I ca n't get it to compile on my own . <code> Dictionary < string , / > dictionary = new Dictionary < string , / > ( ) ; | What does Dictionary < string , / > mean ? |
C_sharp : I have two entities : Originally , I defined the relationship between them as one-to-many in the SubscriptionErrorMap as follows : I am using the following code for saving SubscriptionError : where subscriptionError is the entity and I am not explicitly setting the primary key field.This used to work fine . But , when I changed this relationship to one to zero-or-one , it started to throw the following exception on saving : Can not insert explicit value for identity column in table 'SubscriptionError ' when IDENTITY_INSERT is set to OFF.The new mapping is : Is there something wrong with the mapping ? <code> public class Subscription { public int SubscriptionId { get ; set ; } public virtual ICollection < SubscriptionError > SubscriptionErrors { get ; set ; } } public class SubscriptionError { public int SubscriptionErrorId { get ; set ; } public int SubscriptionId { get ; set ; } public virtual Subscription Subscription { get ; set ; } } this.HasRequired ( t = > t.Subscription ) .WithMany ( t = > t.SubscriptionErrors ) .HasForeignKey ( d = > d.SubscriptionId ) .WillCascadeOnDelete ( false ) ; context.SubscriptionErrors.Add ( subscriptionError ) ; this.HasRequired ( t = > t.Subscription ) .WithOptional ( t = > t.SubscriptionError ) .WillCascadeOnDelete ( false ) ; | One to zero-or-one relationship : Can not insert explicit value for identity column in table when IDENTITY_INSERT is OFF |
C_sharp : I just read this post and it makes the case against implicit typing using when starting out with Test driven development/design.His post says that TDD can be `` slowed down '' when using implicit typing for the return type when unit testing a method . Also , he seems to want the return type specified by the test in order to drive development ( which makes sense to me ) .A given unit test with implicit typing might look like this : So my questions are : Does using implicit typing help or hinder writing unit tests for TDD ? Is there anyone out there that can share their experience using this technique when writing unit tests ? I ask this because soon I have not done TDD and want to know if there is a way to write generic or semi-generic unit tests that would work a return type might change . <code> public void Test_SomeMethod ( ) { MyClass myClass = new MyClass ( ) ; var result = myClass.MethodUnderTest ( ) ; Assert.AreEqual ( someCondition , result ) ; } | Implicit typing and TDD |
C_sharp : I 'm trying to find a ToggleButton associated in my CollectionViewGroup , my xaml structure is the following : How you can see I 've a CollectionViewGroup that filter the ObservableCollection binded Matches for Nation and League.For this I 've declared a ListView that have two GroupStyle , one that filter for Country and another for League , in this piece of code I add only the second GroupStyle ( that contains the ToggleButton ) : So , how you can see in the second group style ( Nation - > League ) I 've a ToggleButton.Now the GroupStyle will be repeated based on the items available in the ObservableCollection , so for example : this is the organization , now imagine that for Premier League of England and for Afghan Premier League of Afghanistan there is a ToggleButton that I 've inserted on the right , I need to get all the ToggleButtons of each Group available on the list . I tried this : Essentially I extract the Group of the list and tried to find the ToggleButton on the nester group , but I can not find it . Someone could help me ? <code> < UserControl.Resources > < CollectionViewSource Source= '' { Binding Matches } '' x : Key= '' GroupedItems '' > < CollectionViewSource.GroupDescriptions > < PropertyGroupDescription PropertyName= '' MatchNation '' / > < PropertyGroupDescription PropertyName= '' MatchLeague '' / > < /CollectionViewSource.GroupDescriptions > < /UserControl.Resources > < ListView ItemsSource= '' { Binding Source= { StaticResource GroupedItems } } '' > < ! -- this is the second group style -- > < ListView.GroupStyle > < GroupStyle > < GroupStyle.ContainerStyle > < Style TargetType= '' { x : Type GroupItem } '' > < Setter Property= '' Template '' > < Setter.Value > < ControlTemplate > < Expander IsExpanded= '' True '' Background= '' # 4F4F4F '' > < Expander.Header > < DockPanel Height= '' 16.5 '' > < TextBlock Text= '' { Binding Name } '' FontWeight= '' Bold '' Foreground= '' White '' FontSize= '' 11.5 '' VerticalAlignment= '' Bottom '' / > < ToggleButton Checked= '' { Binding IsFavourite } '' HorizontalAlignment= '' Right '' / > < /DockPanel > < /Expander.Header > < ItemsPresenter / > < /Expander > < /ControlTemplate > < /Setter.Value > < /Setter > < /Style > < /GroupStyle.ContainerStyle > < /GroupStyle > < /ListView.GroupStyle > < /ListView > |England |Premier League 1. item 2. item 3. item |Afghanistan |Afghan Premier League 1. item 2. item var playingListSource = ( ListCollectionView ) .Playing.Items.SourceCollection ; foreach ( var gp in playingListSource.Groups ) { var rootGroup = ( CollectionViewGroup ) gp ; //Convert the nested group var parentGroup = rootGroup.Items ; } | Not able to find ToggleButton in CollectionViewGroup |
C_sharp : I have the following listener setup in my Unity scene : And in my web view I have this log function : When I execute the following code , the only output that shows up in logcat are tests 5 and E : What is causing this and how can it be fixed ? <code> ui.OnMessageReceived += ( view , message ) = > { var path = message.Path ; var action = message.Args [ `` action '' ] ; if ( path == `` app '' ) { if ( action == `` log '' ) { Debug.Log ( `` [ W ] `` + message.Args [ `` text '' ] ) ; } } } ; log : function ( m ) { window.location.href = 'uniwebview : //app ? action=log & text= ' + m ; } app.log ( `` Echo Test ( 1 ) '' ) ; app.log ( `` Echo Test ( 2 ) '' ) ; app.log ( `` Echo Test ( 3 ) '' ) ; app.log ( `` Echo Test ( 4 ) '' ) ; app.log ( `` Echo Test ( 5 ) '' ) ; setTimeout ( function ( ) { app.log ( `` Echo Test ( A ) '' ) ; app.log ( `` Echo Test ( B ) '' ) ; app.log ( `` Echo Test ( C ) '' ) ; app.log ( `` Echo Test ( D ) '' ) ; app.log ( `` Echo Test ( E ) '' ) ; } , 500 ) ; 08-16 13:55:20.229 13860 13881 I Unity : [ W ] Echo Test ( 5 ) 08-16 13:55:20.693 13860 13881 I Unity : [ W ] Echo Test ( E ) | UniWebView message throttling/collision ? |
C_sharp : The line in question is here : where v and b_y1 area double arrays ( double [ ] ) .What exactly is this line doing ? It was generated by converting MatLab to C++ to C # . I can provide the full function below if needed . <code> memcpy ( v [ 0 ] , b_y1 [ 0 ] , 160U * sizeof ( double ) ) ; | In code converted from C++ to C # , what should I use instead of memcpy ? |
C_sharp : Not sure I am asking this right or this even possible.I feel to explain my question it is best to ask right in the code at the relevant places so please see my comments in the snippet below.I wonder how to achieve this without building a new list of values for each I iteration . I feel this should not be necessary.The bigger picture of this loop is to plot individual dimensions of 3D points to three new 2D plots of these . Hope that makes sense . <code> for ( int i = 0 ; i < 3 ; i++ ) // 3 iterations ( X , Y ; Z ) { // what here ? how to make the data component of Vector3D a variable for ( int k = 0 ; k < = Points.Count - 1 ; k++ ) { Vector2D TL = new Vector2D ( ) ; TL.x = ( ( 1 / ( float ) FrameCount.Sum ( ) ) * k ) ; TL.y = Points [ k ] .x ; // on i = 0 want Points [ k ] .x // on i = 1 want Points [ k ] .y // on i = 2 want Points [ k ] .z TimelinePoints.Add ( TL ) ; // just collect to a flat list for now } } | How to make a struct component a variable ? |
C_sharp : If I am exposing a internal member via a Collection property via : When this property is called what happens ? For example what happens when the following lines of code are called : It 's clear that each time this property is called a new reference type is created but what acctually happens ? Does it simply wrap the IList < T > underneath , does it enumerate over the IList < T > and to create a new Collection < T > instance ? I 'm concerned about performance if this property is used in a for loop . <code> public Collection < T > Entries { get { return new Collection < T > ( this.fieldImplimentingIList < T > ) ; } } T test = instanceOfAbove.Entries [ i ] ; instanceOfAbove [ i ] = valueOfTypeT ; | Does a Collection < T > wrap an IList < T > or enumerate over the IList < T > ? |
C_sharp : I want to highlight an object in Vim C # .I do the following in cs.vim : And highlight it in my color themeHowever it paints also the . and the first letter from the next `` word '' .How to highlight only the match before the dot ? EDIT Thanks to the @ romainl answer I found out that \zs sets the start of a match and \za sets the end of a match.That 's allowed me to make the match properly : <code> syn match csObject `` [ A-Z ] [ _a-zA-Z0-9 ] *\ . [ A-Z ] '' hi csObject guifg= # ff0000 syn match csObject `` [ \t\ ( \ ! ] \zs [ A-Z ] [ _a-zA-Z0-9 ] \ { - } \ze\ . [ A-Z ] '' | Vim - How to highlight a part of a pattern |
C_sharp : I just noticed my Excel service running much faster . I 'm not sure if there is an environmental condition going on . I did make a change to the method . Where before it wasNow its attribute is removed and the method moved into another classBut , I did this because the Method is not called or used as a service . Instead it was called viaand inside the same assembly . Now when I call the methodThe response time appears to have gone up . Does the WebMethodAttribute have the potential to slow local calls ? <code> class WebServices { [ WebMethod ( /* ... */ ) ] public string Method ( ) { } } class NotWebService { public string Method ( ) { } } WebServices service = new WebServices ( ) ; service.Method ( ) ; NotWebService notService = new NotWebService ( ) ; notService.Method ( ) ; | C # - Can WebMethodAttribute adversely effect performance ? |
C_sharp : I have a View that displays a Part . All parts contain a list of identifiers . In my View I display Part Properties and a DataGrid with all the Identifiers of that part.Now if I change a value of an identifier , I want another value update to the default . But if I change my identifier value and set the default of the other property - my DataGrid does not update . Only if I click on the cell , then it gets updated after losing focus.How can I update the View automatically ? I guess the problem is that I do not want to update a direct property of the Part , but a Property in a List that is a property of the Part.ViewView Code-BehindViewModel <code> < DataGrid > < DataGridTemplateColumn Header= '' Company '' > < DataGridTemplateColumn.CellEditingTemplate > < DataTemplate > < ComboBox x : Name= '' CompanyEditComboBox '' ItemsSource= '' { Binding RelativeSource= { RelativeSource AncestorType= { x : Type DataGrid } } , Path=DataContext.Companies } '' SelectedItem= '' { Binding Company , Mode=TwoWay , UpdateSourceTrigger=PropertyChanged } '' SelectionChanged = `` CompanyEditComboBox_SelectionChanged '' / > < /DataTemplate > < /DataGridTemplateColumn.CellEditingTemplate > < DataGridTemplateColumn.CellTemplate > < DataTemplate > < TextBlock Text= '' { Binding Company } '' / > < /DataTemplate > < /DataGridTemplateColumn.CellTemplate > < /DataGridTemplateColumn > < DataGridTemplateColumn Header= '' CompanyType '' > < DataGridTemplateColumn.CellEditingTemplate > < DataTemplate > < ComboBox x : Name= '' CompanyTypeEditComboBox '' ItemsSource= '' { Binding RelativeSource= { RelativeSource AncestorType= { x : Type DataGrid } } , Path=DataContext.CompanyTypes } '' SelectedItem= '' { Binding IdentificationCompanyType , Mode=TwoWay , UpdateSourceTrigger=PropertyChanged } '' / > < /DataTemplate > < /DataGridTemplateColumn.CellEditingTemplate > < DataGridTemplateColumn.CellTemplate > < DataTemplate > < TextBlock Text= '' { Binding IdentificationCompanyType , Mode=OneWay , UpdateSourceTrigger=PropertyChanged } '' / > < /DataTemplate > < /DataGridTemplateColumn.CellTemplate > < /DataGridTemplateColumn > < /DataGrid > private void CompanyEditComboBox_SelectionChanged ( object sender , SelectionChangedEventArgs e ) { var vm = ( PartViewModel ) DataContext ; var box = ( ComboBox ) sender ; var c = ( Company ) box.SelectedItem ; vm.SetDefaultCompanyType ( c ) ; } public void SetDefaultCompanyType ( Company c ) { SelectedIdentification.IdentificationCompanyType = c.DefaultCompanyType ; OnPropertyChanged ( `` IdentificationCompanyType '' ) ; } | Update DataGrid cell if other cell changes |
C_sharp : The following C # snippet compiles and runs under my Visual Studio 2010 : Note the trailing comma in the object initializer.Is this legal C # and does it have any useful purpose , or I have just hit a ( benign ) compiler bug ? <code> struct Foo { public int A ; } // ..var foo = new Foo { A = 1 , } ; | new Foo { A = 1 , } Bug or Feature ? |
C_sharp : I am trying to dynamically re-structure some data to be shown in a treeview which will allows the user to select up to three of the following dimensions to group the data by : So for example , if the user were to select that they wanted to group by Company then Site then Division ... the following code would perform the required groupings.This would give a structre like this : However , this only provides me with on of a large number of combinations.How would I go about converting this into something that could create the equivalent expression dynamically based on the three dimensions that the user has chosen and so I do n't have to create one of each of these expressions for each combination ! ! ? Thanks guys . <code> OrganisationCompanySiteDivisionDepartment var entities = orgEntities// Grouping Level 1.GroupBy ( o = > new { o.CompanyID , o.CompanyName } ) .Select ( grp1 = > new TreeViewItem { CompanyID = grp1.Key.CompanyID , DisplayName = grp1.Key.CompanyName , ItemTypeEnum = TreeViewItemType.Company , SubItems = grp1 // Grouping Level 2 .GroupBy ( o = > new { o.SiteID , o.SiteName } ) .Select ( grp2 = > new TreeViewItem { SiteID = grp2.Key.SiteID , DisplayName = grp2.Key.SiteName , ItemTypeEnum = TreeViewItemType.Site , SubItems = grp2 // Grouping Level 3 .GroupBy ( o = > new { o.Division } ) .Select ( grp3 = > new TreeViewItem { DisplayName = grp3.Key.Division , ItemTypeEnum = TreeViewItemType.Division , } ) .ToList ( ) } ) .ToList ( ) } ) .ToList ( ) ; + Company A + Site A + Division 1 + Division 2 + Site B + Division 1+ Company B + Site C + Division 2+ Company C + Site D | Create GroupBy Statements Dynamically |
C_sharp : I do n't understand why the following code produces an error . Normally I can figure things out from the language specification , but in this case I do n't understand the language specification.This is n't causing problems in my code , by the way , I just want to understand the language.Example : This behavior appears to be true of all versions of C # , but the quotes below are from C # Language Specification 5.0.Section 5.3.3.14 Try-finally statements The definite assignment state of v at the beginning of finally-block is the same as the definite assignment state of v at the beginning of stmt.Here `` beginning of stmt '' refers to the beginning of the entire try-finally statement , i.e . just before try.Section 5.3.3.15 Try-catch-finally statements The following example demonstrates how the different blocks of a try statement ( §8.10 ) affect definite assignment.Can anyone explain why success ( in my example ) or i ( in the language spec example ) are not definitely assigned at the beginning of the finally-block ? <code> bool success ; try { success = true ; } catch { success = false ; } finally { Console.WriteLine ( success ) ; // ERROR : Local variable 'success ' might not be initialized before accessing } static void F ( ) { int i , j ; try { goto LABEL ; // neither i nor j definitely assigned i = 1 ; // i definitely assigned } catch { // neither i nor j definitely assigned i = 3 ; // i definitely assigned } finally { // neither i nor j definitely assigned j = 5 ; // j definitely assigned } // i and j definitely assigned LABEL : ; // j definitely assigned } | In C # , why is a variable not definitely assigned at the beginning of a finally block ? |
C_sharp : I 'm trying to investigate whether dictionaries with enum keys still generate garbage in newer versions of .Net ( say > = 4 ) See Shawn Hargreaves blog post here for details on why I 'm even fretting about this ... ( http : //blogs.msdn.com/b/shawnhar/archive/2007/07/02/twin-paths-to-garbage-collector-nirvana.aspx ) Very specific I know but garbage on the xbox is / can be a very really problem.I created a little .Net v4 console application comparing the IL generated for Dictionary and Dicationary and noticed a 'box ' opcode in both sets of code which really confused me.https : //msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.box % 28v=vs.110 % 29.aspx Convert a value type ( of the type specified in valTypeToken ) to a true object reference.Is the box here not a heap allocation ? If not , then how can I tell when there 's heap allocations that might cause the Xbox to struggle ? ( from looking at the IL ) Does it depend on some other context ? Would a memory profiler ( CLR Profiler for example ) be the only way to tell for sure ? <code> .method private hidebysig instance int32 FindEntry ( ! TKey key ) cil managed { // Method begins at RVA 0x61030 // Code size 138 ( 0x8a ) .maxstack 3 .locals init ( [ 0 ] int32 , [ 1 ] int32 ) IL_0000 : ldarg.1 IL_0001 : box ! TKey < -- -- Hmmmm ! IL_0006 : brtrue.s IL_000e IL_0008 : ldc.i4.5 IL_0009 : call void System.ThrowHelper : :ThrowArgumentNullException ( valuetype System.ExceptionArgument ) IL_000e : ldarg.0 IL_000f : ldfld int32 [ ] class System.Collections.Generic.Dictionary ` 2 < ! TKey , ! TValue > : :buckets IL_0014 : brfalse.s IL_0088 | .Net Framework 4.0 - Opcodes.Box present in Dictionary with int key |
C_sharp : In a previous question one of the comments from Dr. Herbie on the accepted answer was that my method was performing two responsibilities..that of changing data and saving data.What I 'm trying to figure out is the best way to separate these concerns in my situation.Carrying on with my example of having a Policy object which is retrieved via NHibernate ... .The way I 'm currently setting the policy to inactive is as follows : If I were to separate the responsibility of data access and data update what would be the best way to go about it ? Is it better to have the PolicyManager ( which acts as the gateway to the dao ) manage the state of the Policy object : Or to have the Policy object maintain it 's own state and then use the manager class to save the information to the database : <code> Policy policy = new Policy ( ) ; policy.Status = Active ; policyManager.Inactivate ( policy ) ; //method in PolicyManager which has data access and update responsibilitypublic void Inactivate ( Policy policy ) { policy.Status = Inactive ; Update ( policy ) ; } Policy policy = new Policy ( ) ; policy.Status = Active ; policyManager.Inactivate ( policy ) ; policyManager.Update ( policy ) ; //method in PolicyManagerpublic void Inactivate ( Policy policy ) { policy.Status = Inactive ; } Policy policy = new Policy ( ) ; policy.Status = Active ; policy.Inactivate ( ) ; policyManager.Update ( policy ) ; //method in Policypublic void Inactivate ( ) { this.Status = Inactive ; } | What 's the best way to separate concerns for this code ? |
C_sharp : I have view model with 2 properties : A and B and I want to validate that A < B.Below is my simplified implementation where I use custom validation rule . Since each property is validated independently , it lead to an anoying issue : if entered A value is invalid , than it stay so even after changing B , since validation of B does n't know anything about A.This can be seen on this demo : A is invalid after entering 11 , that 's correct since 11 > 2 . Changing B to 22 does n't re-evalute A , I have to edit A to have validation passed.What I want ? I want that after enering 22 into B the red border ( validation error ) disappears and A = 11 , B = 22 would be source values in view model.How can I in B validation somehow force A validation after new B value is synchronized with source ? View model : View : View code : Binding : Validation rule : <code> public class ViewModel : INotifyPropertyChanged { int _a ; public int A { get = > _a ; set { _a = value ; OnPropertyChanged ( ) ; } } int _b ; public int B { get = > _b ; set { _b = value ; OnPropertyChanged ( ) ; } } public event PropertyChangedEventHandler PropertyChanged ; public virtual void OnPropertyChanged ( [ CallerMemberName ] string property = `` '' ) = > PropertyChanged ? .Invoke ( this , new PropertyChangedEventArgs ( property ) ) ; } < StackPanel > < TextBox Margin= '' 10 '' Text= '' { local : MyBinding A } '' / > < TextBox Margin= '' 10 '' Text= '' { local : MyBinding B } '' / > < /StackPanel > public MainWindow ( ) { InitializeComponent ( ) ; DataContext = new ViewModel { A = 1 , B = 2 } ; } public class MyBinding : Binding { public MyBinding ( string path ) : base ( path ) { UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged ; ValidationRules.Add ( new MyValidationRule ( ) ) ; } } public class MyValidationRule : ValidationRule { public MyValidationRule ( ) : base ( ValidationStep.ConvertedProposedValue , false ) { } public override ValidationResult Validate ( object value , CultureInfo cultureInfo ) = > ValidationResult.ValidResult ; // not used public override ValidationResult Validate ( object value , CultureInfo cultureInfo , BindingExpressionBase owner ) { var binding = owner as BindingExpression ; var vm = binding ? .DataItem as ViewModel ; switch ( binding.ResolvedSourcePropertyName ) { case nameof ( vm.A ) : if ( ( int ) value > = vm.B ) return new ValidationResult ( false , `` A should be smaller than B '' ) ; break ; case nameof ( vm.B ) : if ( ( int ) value < = vm.A ) return new ValidationResult ( false , `` B should be bigger than A '' ) ; break ; } return base.Validate ( value , cultureInfo , owner ) ; } } | How to validate two properties which depend on each other ? |
C_sharp : Today I found something that I do n't quite understand . I got the following code in LinqPad ( version 5 ) : It appears that second loop takes twice as long as the first one . Why would this simple cast cause such an effect ? I 'm sure that there 's something simple happening under the hood that I am somehow missing . <code> void Main ( ) { const int size = 5000000 ; List < Thing > things = Enumerable.Range ( 1 , 5000000 ) .Select ( x = > new Thing { Id = x } ) .ToList ( ) ; var sw1 = Stopwatch.StartNew ( ) ; foreach ( var t in things ) if ( t.Id == size ) break ; sw1.ElapsedMilliseconds.Dump ( ) ; var sw2 = Stopwatch.StartNew ( ) ; IEnumerable < Thing > ienThings = things ; foreach ( var t in ienThings ) if ( t.Id == size ) break ; sw2.ElapsedMilliseconds.Dump ( ) ; } class Thing { public long Id { get ; set ; } } | Foreach on collection cast to IEnumerable work slower than without cast ? |
C_sharp : I 'm trying to tackle the classic handwritten digit recognition problem with a feed forward neural network and backpropagation , using the MNIST dataset . I 'm using Michael Nielsen 's book to learn the essentials and 3Blue1Brown 's youtube video for the backpropagation algorithm.I finished writing it some time ago and been debugging since , because the results are quite bad . At its best the network can recognize ~4000/10000 samples after 1 epoch and that number only drops on the following epochs , which lead me to believe there 's some issue with the backpropagation algorithm . I 've been drowning in index hell trying to debug this for the last few days and ca n't figure out where the issue is , I 'd appreciate any help in pointing it out.A bit of background : 1 ) I 'm not using any matrix multiplication and no external frameworks , but doing everything with for loops because that 's how I learned it from the video . 2 ) Unlike the book , I 'm storing both weights and biases in the same array . The biases for every layer are a column at the end of the weight matrix for that layer.And finally for the code , this is the Backpropagate method of the NeuralNetwork class , which is called in UpdateMiniBatch , which itself is called in SGD : GetWeightedInputsAndActivations : The entire NeuralNetwork as well as everything else can be found here.EDIT : after many significant changes to the repo the above link might no longer be functional , but should hopefully be irrelevant considering the answer . For completeness ' sake this is a functional link to the changed repository . <code> /// < summary > /// Returns the partial derivative of the cost function on one sample with respect to every weight in the network./// < /summary > public List < double [ , ] > Backpropagate ( ITrainingSample sample ) { // Forwards pass var ( weightedInputs , activations ) = GetWeightedInputsAndActivations ( sample.Input ) ; // The derivative with respect to the activation of the last layer is simple to compute : activation - expectedActivation var errors = activations.Last ( ) .Select ( ( a , i ) = > a - sample.Output [ i ] ) .ToArray ( ) ; // Backwards pass List < double [ , ] > delCostOverDelWeights = Weights.Select ( x = > new double [ x.GetLength ( 0 ) , x.GetLength ( 1 ) ] ) .ToList ( ) ; List < double [ ] > delCostOverDelActivations = Weights.Select ( x = > new double [ x.GetLength ( 0 ) ] ) .ToList ( ) ; delCostOverDelActivations [ delCostOverDelActivations.Count - 1 ] = errors ; // Comment notation : // Cost function : C // Weight connecting the i-th neuron on the ( l + 1 ) -th layer to the j-th neuron on the l-th layer : w [ l ] [ i , j ] // Bias of the i-th neuron on the ( l + 1 ) -th layer : b [ l ] [ i ] // Activation of the i-th neuon on the l-th layer : a [ l ] [ i ] // Weighted input of the i-th neuron on the l-th layer : z [ l ] [ i ] // which does n't make sense on layer 0 , but is left for index convenience // Notice that weights , biases , delCostOverDelWeights and delCostOverDelActivation all start at layer 1 ( the 0-th layer is irrelevant to their meanings ) while activations and weightedInputs strat at the 0-th layer for ( int l = Weights.Count - 1 ; l > = 0 ; l -- ) { //Calculate ∂C/∂w for the current layer : for ( int i = 0 ; i < Weights [ l ] .GetLength ( 0 ) ; i++ ) for ( int j = 0 ; j < Weights [ l ] .GetLength ( 1 ) ; j++ ) delCostOverDelWeights [ l ] [ i , j ] = // ∂C/∂w [ l ] [ i , j ] delCostOverDelActivations [ l ] [ i ] * // ∂C/∂a [ l + 1 ] [ i ] SigmoidPrime ( weightedInputs [ l + 1 ] [ i ] ) * // ∂a [ l + 1 ] [ i ] /∂z [ l + 1 ] [ i ] = ∂ ( σ ( z [ l + 1 ] [ i ] ) ) /∂z [ l + 1 ] [ i ] = σ′ ( z [ l + 1 ] [ i ] ) ( j < Weights [ l ] .GetLength ( 1 ) - 1 ? activations [ l ] [ j ] : 1 ) ; // ∂z [ l + 1 ] [ i ] /∂w [ l ] [ i , j ] = a [ l ] [ j ] ||OR|| ∂z [ l + 1 ] [ i ] /∂b [ l ] [ i ] = 1 // Calculate ∂C/∂a for the previous layer ( a [ l ] ) : if ( l ! = 0 ) for ( int i = 0 ; i < Weights [ l - 1 ] .GetLength ( 0 ) ; i++ ) for ( int j = 0 ; j < Weights [ l ] .GetLength ( 0 ) ; j++ ) delCostOverDelActivations [ l - 1 ] [ i ] += // ∂C/∂a [ l ] [ i ] = sum over j : delCostOverDelActivations [ l ] [ j ] * // ∂C/∂a [ l + 1 ] [ j ] SigmoidPrime ( weightedInputs [ l + 1 ] [ j ] ) * // ∂a [ l + 1 ] [ j ] /∂z [ l + 1 ] [ j ] = ∂ ( σ ( z [ l + 1 ] [ j ] ) ) /∂z [ l + 1 ] [ j ] = σ′ ( z [ l + 1 ] [ j ] ) Weights [ l ] [ j , i ] ; // ∂z [ l + 1 ] [ j ] /∂a [ l ] [ i ] = w [ l ] [ j , i ] } return delCostOverDelWeights ; } public ( List < double [ ] > , List < double [ ] > ) GetWeightedInputsAndActivations ( double [ ] input ) { List < double [ ] > activations = new List < double [ ] > ( ) { input } .Concat ( Weights.Select ( x = > new double [ x.GetLength ( 0 ) ] ) ) .ToList ( ) ; List < double [ ] > weightedInputs = activations.Select ( x = > new double [ x.Length ] ) .ToList ( ) ; for ( int l = 0 ; l < Weights.Count ; l++ ) for ( int i = 0 ; i < Weights [ l ] .GetLength ( 0 ) ; i++ ) { double value = 0 ; for ( int j = 0 ; j < Weights [ l ] .GetLength ( 1 ) - 1 ; j++ ) value += Weights [ l ] [ i , j ] * activations [ l ] [ j ] ; // weights weightedInputs [ l + 1 ] [ i ] = value + Weights [ l ] [ i , Weights [ l ] .GetLength ( 1 ) - 1 ] ; // bias activations [ l + 1 ] [ i ] = Sigmoid ( weightedInputs [ l + 1 ] [ i ] ) ; } return ( weightedInputs , activations ) ; } | Backpropagation algorithm giving bad results |
C_sharp : I am looking at the Roslyn ObjectPool implementation ( https : //github.com/dotnet/roslyn/blob/master/src/Compilers/Core/SharedCollections/ObjectPool % 601.cs ) and I do n't get why they did not simply choose to have an array of T but instead wrap T inside a struct ? What is the purpose of this ? <code> [ DebuggerDisplay ( `` { Value , nq } '' ) ] private struct Element { internal T Value ; } ... private readonly Element [ ] _items ; | Roslyn ObjectPool struct wrapper |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.