text
stringlengths
46
37.3k
title
stringlengths
12
162
C_sharp : I 'm refactoring a little bit of C # data access code from a previous developer and am curious about a pattern he used.The code initially exposed collections ( arrays ) of a variety of ActiveRecord-style business objects - essentially objects wrapping database fields . I 'm changing the arrays to generic lists , but the aspect of the code I 'm curious about is that the previous developer had Get methods for each type of object he was wrapping , thusly : There are several of these methods , and I can not for the life of me think of any possible advantage of using that mechanism over simply referring to things [ i ] directly . Let 's assume , for argument 's sake , that things is a public property , not a public field ( in this case it 's actually an auto-implemented property , so that assumption is actually true ) .Am I missing something obvious ? Or even something esoteric ? UPDATEI should probably clarify that these collections are currently accessed from within for loops : which I am refactoring to : and perhaps even to use things.foreach ( ) . <code> public Thing GetThing ( int i ) { return things [ i ] ; } for ( int i = 0 ; i < thingsCount ; i== ) { dosomthing ( GetThing ( i ) ) ; dosomethingelse ( GetThing ( i ) ) ; } for ( int i = 0 ; i < thingsCount ; i== ) { Thing thing = things [ i ] ; dosomthing ( thing ) ; dosomethingelse ( thing ) ; }
Any advantage to objects.GetObject ( i ) over objects [ i ] ?
C_sharp : As a learning exercise , I 'm trying to reproduce an async/await deadlock that occurs in a normal windows form , but using a console app . I was hoping the code below would cause this to happen , and indeed it does . But the deadlock also happens unexpectedly when using await.I 'm mostly curious if anyone knows why this is happening ? <code> using System ; using System.Threading ; using System.Threading.Tasks ; using System.Windows.Forms ; static class Program { static async Task Main ( string [ ] args ) { // no deadlocks when this line is commented out ( as expected ) SynchronizationContext.SetSynchronizationContext ( new WindowsFormsSynchronizationContext ( ) ) ; Console.WriteLine ( `` before '' ) ; //DoAsync ( ) .Wait ( ) ; // deadlock expected ... and occurs await DoAsync ( ) ; // deadlock not expected ... but also occurs ? ? ? Console.WriteLine ( `` after '' ) ; } static async Task DoAsync ( ) { await Task.Delay ( 100 ) ; } }
async/await deadlock when using WindowsFormsSynchronizationContext in a console app
C_sharp : If I have a method like thisis f created every time SomeMethod is called ? I mean , does that line take time to compute or does the compiler store the function somewhere on compile time skips it at execution ? <code> void SomeMethod ( ) { Func < A , B > f = a = > /*Some code*/ ; ... b = f ( a ) ; }
Inline lambda function creation behaviour in C #
C_sharp : Consider this simple .js code : // UsageI 'm pretty sure c # support first class function , note that I do n't want to use classes to remake the code above . What is the equivalent closure in c # ? I have made this : <code> const createCounter = ( ) = > { let value = 0 ; return { increment : ( ) = > { value += 1 } , decrement : ( ) = > { value -= 1 } , logValue : ( ) = > { console.log ( value ) ; } } } const { increment , decrement , logValue } = createCounter ( ) ; public Func < WhatType ? > CreateCounter = ( ) = > { var value = 0 ; return what ? }
What is the equivalent javascript closure in c # ?
C_sharp : Firstly , This might seem like a long question . I do n't think it is ... The code is just an overview of what I 'm currently doing . It does n't feel right , so I am looking for constructive criticism and warnings for pitfalls and suggestions of what I can do.I have a database with business objects.I need to access properties of parent objects.I need to maintain some sort of state through business objects.If you look at the classes , I do n't think that the access modifiers are right . I do n't think its structured very well . Most of the relationships are modelled with public properties . SubAccount.Account.User.ID < -- all of those are public..Is there a better way to model a relationship between classes than this so it 's not so `` public '' ? The other part of this question is about resources : If I was to make a User.GetUserList ( ) function that returns a List , and I had 9000 users , when I call the GetUsers method , it will make 9000 User objects and inside that it will make 9000 new AccountCollection objects . What can I do to make this project not so resource hungry ? Please find the code below and rip it to shreds . <code> public class User { public string ID { get ; set ; } public string FirstName { get ; set ; } public string LastName { get ; set ; } public string PhoneNo { get ; set ; } public AccountCollection accounts { get ; set ; } public User { accounts = new AccountCollection ( this ) ; } public static List < Users > GetUsers ( ) { return Data.GetUsers ( ) ; } } public AccountCollection : IEnumerable < Account > { private User user ; public AccountCollection ( User user ) { this.user = user ; } public IEnumerable < Account > GetEnumerator ( ) { return Data.GetAccounts ( user ) ; } } public class Account { public User User { get ; set ; } //This is public so that the subaccount can access its Account 's User 's ID public int ID ; public string Name ; public Account ( User user ) { this.user = user ; } } public SubAccountCollection : IEnumerable < SubAccount > { public Account account { get ; set ; } public SubAccountCollection ( Account account ) { this.account = account ; } public IEnumerable < SubAccount > GetEnumerator ( ) { return Data.GetSubAccounts ( account ) ; } } public class SubAccount { public Account account { get ; set ; } //this is public so that my Data class can access the account , to get the account 's user 's ID . public SubAccount ( Account account ) { this.account = account ; } public Report GenerateReport ( ) { Data.GetReport ( this ) ; } } public static class Data { public static List < Account > GetSubAccounts ( Account account ) { using ( var dc = new databaseDataContext ( ) ) { List < SubAccount > query = ( from a in dc.Accounts where a.UserID == account.User.ID //this is getting the account 's user 's ID select new SubAccount ( account ) { ID = a.ID , Name = a.Name , } ) .ToList ( ) ; } } public static List < Account > GetAccounts ( User user ) { using ( var dc = new databaseDataContext ( ) ) { List < Account > query = ( from a in dc.Accounts where a.UserID == User.ID //this is getting the user 's ID select new Account ( user ) { ID = a.ID , Name = a.Name , } ) .ToList ( ) ; } } public static Report GetReport ( SubAccount subAccount ) { Report report = new Report ( ) ; //database access code here //need to get the user id of the subaccount 's account for data querying . //i 've got the subaccount , but how should i get the user id . //i would imagine something like this : int accountID = subAccount.Account.User.ID ; //but this would require the subaccount 's Account property to be public . //i do not want this to be accessible from my other project ( UI ) . //reading up on internal seems to do the trick , but within my code it still feels //public . I could restrict the property to read , and only private set . return report ; } public static List < User > GetUsers ( ) { using ( var dc = new databaseDataContext ( ) ) { var query = ( from u in dc.Users select new User { ID = u.ID , FirstName = u.FirstName , LastName = u.LastName , PhoneNo = u.PhoneNo } ) .ToList ( ) ; return query ; } } }
Overly accessible and incredibly resource hungry relationships between business objects . How can I fix this ?
C_sharp : I have the following two button click methods that create an array from three TextBoxes , order the values , insert them into a database and then select the values in the same order . The only difference between the two buttons is that one orders the values in ascending order and the other in descending order.I 'm not used to working with C # . Can anybody suggest the best way to structure my code so I 'm not repeating it for each button ? Normally I 'd write a function and have each button pass it arguments . Is that the right way to go here ? Thanks in advance.Button1 ... Button2 ... <code> protected void Button1_Click ( object sender , EventArgs e ) { var list = new string [ ] { TextBox1.Text , TextBox2.Text , TextBox3.Text } ; var orderedlist = list.OrderBy ( x = > ( x ) ) .ToArray ( ) ; SqlCommand cmd = new SqlCommand ( `` Select * from lists order by values asc '' , conn ) ; protected void Button2_Click ( object sender , EventArgs e ) { var list = new string [ ] { TextBox1.Text , TextBox2.Text , TextBox3.Text } ; var orderedlist = list.OrderByDescending ( x = > ( x ) ) .ToArray ( ) ; SqlCommand cmd = new SqlCommand ( `` Select * from lists order by values desc '' , conn ) ;
Structuring button click methods to avoid code repetition
C_sharp : Possible Duplicates : What does placing a @ in front of a C # variable name do ? What ’ s the use/meaning of the @ character in variable names in C # ? As you can imagine , Googling or Binging for any phrase containing an ' @ ' is difficult.In creating a new web service , one of the members of the imported C # proxy class is prefixed with the @ . For example : I assume that it is Visual Studio 's way resolving potential conflicts with reserved words because 'event ' is a reserved word . Changing the property in the web service interface to something other than 'event ' ( i.e . 'healthevent ' ) removes the @ from the property . Is this a correct assumption ? <code> plan . @ event = new Insurance.Event ( ) ;
What is the purpose of @ as part of a member name in C # ?
C_sharp : On the internet I see a lot of code which uses this . to access local members of a class , like this : ( do n't expect the code to do something sensible . I just wanted to show a few different uses for `` this . `` ) I wonder why to do this ? To add more clarity to the source ? Or is it just a waste of space ? <code> private String _whatever ; public String Whatever { get { return this._whatever ; } set { this._whatever = value ; } } public void DoSomething ( ) { String s = this.Whatever ; this.DoSomething ( ) ; }
Use this . to access internal class members ?
C_sharp : I 'm gettin an error pointing to in in the foreach loop ! ? Has never happens before . What could be the reason for this ? Have I missed something ? Error message : An exception of type 'System.NotSupportedException ' occurred in EntityFramework.SqlServer.dll but was not handled in user code Additional information : Unable to create a constant value of type 'System.Object ' . Only primitive types or enumeration types are supported in this context.My code : <code> List < int > WeeksInProject = new List < int > ( ) ; var w = from x in db.Activities where x.ProjectID.Equals ( 1 ) select x ; foreach ( var wNum in w ) { WeeksInProject.Add ( wNum.WeekNumber ) ; }
Foreach loop error
C_sharp : Similar to how lambda expressions with free variables work I would like to implement my own closure class that captures some method parameter.Then I have some class that works with DateTime instances . One of the methods that should use this closure class is this : I would like to convert it to use Closure class . The problem is that I would like to reuse ( performance reasons ) my Closure class instance : In order for me to reuse the same Closure instance I would have to not store the value of the parameter ( into closure 's Variable field ) but rather method parameter 's reference pointer . So the next time this method gets called closure 's Variable would actually point to the correct value to be used.How am I supposed to do this ? A similar thing is done when compiler generates classes that capture lambda expression free variables . I 've been looking at decompiled code ( using Reflector ) , but I do n't seem to understand how that 's done ... <code> public class Closure < TObject , TVariable > { public TVariable Variable { get ; set ; } public Func < TObject , bool > Predicate { get ; set ; } } // Original Versionpublic IEnumerable < Item > GetDayData ( DateTime day ) { this.items.Where ( i = > i.IsValidForDay ( day ) ) ; } private Closure < Item , DateTime > closure = null ; public IEnumerable < Item > GetDayData ( DateTime day ) { if ( closure == null ) { this.closure = new Closure < Item , DateTime > ( ) { Variable = reference of `` day '' param , < === HOW ? ? ? ? ? ? ? ? Predicate = i = > i.IsValidForDay ( this.closure.Variable ) } } this.items.Where ( this.closure.Predicate ) ; }
Storing pointer to method parameter for later reuse
C_sharp : I 've seen this piece of code from one of the jetbrain 's team : Looking at this code : Question : What is the scope of the lock ? <code> object myLock = new object ( ) public IEnumerable < int > Values ( ) { lock ( myLock ) { for ( var i=0 ; i < 10 ; i++ ) yield return i ; } } public void Test ( ) { foreach ( var value in Values ( ) ) { DoHugeJob ( value ) ; } } void Main ( ) { Test ( ) ; }
What is the scope of the lock ?
C_sharp : How can I have a type reference that refers to any object that implements a set of interfaces ? For example , I can have a generic type like this : Java : C # That 's how to have a class-wide generic type . However , I 'd like to simply have a data member which references any object that extends a given set of interfaces.Example : If it 's possible to have this sort of type syntax , how could I do it in both Java and C # ? I realize I can just create another interface that extends all desired interfaces . However , I do n't see this as optimal , as it needlessly adds another type whose sole purpose is to get around syntax . Granted this is a very minor issue , but in terms of elegance it 's a bit galling . <code> public class Foo < T extends A & B > { } public class Foo < T > where T : A , B { } public class Foo { protected < ? extends A , B > object ; public void setObject ( < ? extends A , B > object ) { this.object = object ; } }
C # - How can I have an type that references any object which implements a set of Interfaces ?
C_sharp : So I 'm making a tile based game and I 'd like to add some fake shadows to the tiles . It 's kinda hard to explain so I 'll do it with pictures : Let 's say this is my tile world : And I want it to have shadows like this : Because the world is tile based , I can split all the shadow parts into separate images : But now I have no idea how I would bring this to code . Well , actually I do have ideas , but they 're incredible tedious and they do n't work optimally.I 've tried a massive if-statement ... And a massive lookup table ... But either I 'm doing something wrong or they just refuse to work at all . Any ideas ? <code> bool ul = adjacentBlocks [ 0 , 0 ] == Block.Type.Rock ; //Upper Leftbool um = adjacentBlocks [ 1 , 0 ] == Block.Type.Rock ; //Upper Middlebool ur = adjacentBlocks [ 2 , 0 ] == Block.Type.Rock ; //Upper Rightbool ml = adjacentBlocks [ 0 , 1 ] == Block.Type.Rock ; //Center Left//bool cm = adjacentBlocks [ 1 , 1 ] == Block.Type.Rock ; //CURRENT BLOCK - NOT NEEDEDbool mr = adjacentBlocks [ 2 , 1 ] == Block.Type.Rock ; //Center Rightbool ll = adjacentBlocks [ 0 , 2 ] == Block.Type.Rock ; //Lower Leftbool lm = adjacentBlocks [ 1 , 2 ] == Block.Type.Rock ; //Lower Middlebool lr = adjacentBlocks [ 2 , 2 ] == Block.Type.Rock ; //Lower Rightif ( ml ) { texture = `` Horizontal '' ; flipX = false ; flipY = false ; } if ( mr ) { texture = `` Horizontal '' ; flipX = true ; flipY = false ; } if ( um ) { texture = `` Vertical '' ; flipX = false ; flipY = false ; } if ( lm ) { texture = `` Vertical '' ; flipX = false ; flipY = true ; } if ( ml & & ul & & um ) texture = `` HorizontalVertical '' ; //More if statements I ca n't be bothered to writeif ( ul & & um & & ur & & ml & & mr & & ll & & lm & lr ) texture = `` Full '' ; var table = new List < TextureBlockLayout > { new TextureBlockLayout ( `` Horizontal '' , false , false , new [ , ] { { true , true , false } , { true , true , false } , { true , true , false } } ) , new TextureBlockLayout ( `` Horizontal '' , true , false , new [ , ] { { false , true , true } , { false , true , true } , { false , true , true } } ) , new TextureBlockLayout ( `` Full '' , false , false , new [ , ] { { true , true , true } , { true , true , true } , { true , true , true } } ) } ;
How would I efficiently make fake tile shadows ?
C_sharp : Code : Two identical blocks in identical usings . Output : Second block takes 2.2 seconds ! But if to get rid of usings , durations became same ( ~0.3s , like first one ) .I 've tried with .net framework 4.5 and .net core 1.1 , in release , results are same.Can anybody explain that behavior ? <code> internal class Program { private static void Main ( string [ ] args ) { const int iterCount = 999999999 ; var sum1 = 0 ; var sum2 = 0 ; using ( new Dis ( ) ) { var sw = DateTime.Now ; for ( var i = 0 ; i < iterCount ; i++ ) sum1 += i ; Console.WriteLine ( sum1 ) ; Console.WriteLine ( DateTime.Now - sw ) ; } using ( new Dis ( ) ) { var sw = DateTime.Now ; for ( var i = 0 ; i < iterCount ; i++ ) sum2 += i ; Console.WriteLine ( sum2 ) ; Console.WriteLine ( DateTime.Now - sw ) ; } Console.ReadLine ( ) ; } private class Dis : IDisposable { public void Dispose ( ) { } } } 205165798500:00:00.3690996205165798500:00:02.2640266
What is the reason of so different durations of same code blocks execution ?
C_sharp : I 'm struggling with implementing the IEquatable < > interface for a class . The class has a Parameter property that uses a generic type . Basically the class definition is like this : In the Equals ( ) method I 'm using EqualityComparer < T > .Default.Equals ( Parameter , other.Parameter ) to compare the property . Generally , this works fine – as long as the property is not a collection , for example an IEnumerable < T > . The problem is that the default equality comparer for IEnumerable < T > is checking reference equality.Obviously , you 'd want to use SequenceEqual ( ) to compare the IEnumerable < T > . But to get this running , you need to specify the generic type of the SequenceEqual ( ) method . This is the closest I could get : But this does not work because Convert.ChangeType ( ) returns an object . And of course object does not implement SequenceEqual ( ) .How do I get this working ? Thanks for any tipps ! Best regards , Oliver <code> public class MyClass < T > : IEquatable < MyClass < T > > { public T Parameter { get ; } ... } var parameterType = typeof ( T ) ; var enumerableType = parameterType.GetInterfaces ( ) .Where ( type = > type.IsGenericType & & type.GetGenericTypeDefinition ( ) == typeof ( IEnumerable < > ) ) .Select ( type = > type.GetGenericArguments ( ) .First ( ) ) .FirstOrDefault ( ) ; if ( enumerableType ! = null ) { var castedThis = Convert.ChangeType ( Parameter , enumerableType ) ; var castedOther = Convert.ChangeType ( other.Parameter , enumerableType ) ; var isEqual = castedThis.SequenceEqual ( castedOther ) ; }
How to compare two IEnumerable < T > in C # if I do n't know the actual object type ?
C_sharp : This loads a set of values from an XML file and places them into a class for storage . I 'm trying to figure out how to output the values as a list so I can place them into a Listbox.I thought there would be an easy way like a .ToList ( ) method or to be able to foreach through the strings in the class ( no public GetEnumerator ) . I 've been able to find out that Foreach hides some of the complexity but not away to do what I want.I 've been searching online with no avail ( lacking the correct terminology maybe ) , unfortunately I left my C # reference books at work : /Would much appreciate a pointer in the right direction , Thanks . <code> using System ; using System.Collections.Generic ; using System.ComponentModel ; using System.Data ; using System.Drawing ; using System.Linq ; using System.Text ; using System.Windows.Forms ; using System.IO ; using System.Xml ; namespace ThereIsOnlyRules { public partial class Form1 : Form { public Form1 ( ) { InitializeComponent ( ) ; } private void Form1_Load ( object sender , EventArgs e ) { try { listBox1.Items.Clear ( ) ; string path = `` characterXML.xml '' ; FileStream fs = new FileStream ( path , FileMode.Open , FileAccess.Read , FileShare.ReadWrite ) ; System.Xml.XmlDocument CXML = new System.Xml.XmlDocument ( ) ; CXML.Load ( fs ) ; //Get the number of elements XmlNodeList elemList = CXML.GetElementsByTagName ( `` unit '' ) ; //foreach ( var element in elemList ) // { // listBox1.Items.Add ( element ) ; // } for ( int i = 0 ; i < elemList.Count ; i++ ) { UnitAttributes attributes = new UnitAttributes ( ) ; attributes.army = elemList [ i ] .Attributes [ `` army '' ] .Value ; attributes.category = elemList [ i ] .Attributes [ `` category '' ] .Value ; attributes.type = elemList [ i ] .Attributes [ `` type '' ] .Value ; attributes.composition = elemList [ i ] .Attributes [ `` composition '' ] .Value ; attributes.WS = elemList [ i ] .Attributes [ `` WS '' ] .Value ; attributes.BS = elemList [ i ] .Attributes [ `` BS '' ] .Value ; attributes.T = elemList [ i ] .Attributes [ `` T '' ] .Value ; attributes.W = elemList [ i ] .Attributes [ `` W '' ] .Value ; attributes.I = elemList [ i ] .Attributes [ `` I '' ] .Value ; attributes.A = elemList [ i ] .Attributes [ `` A '' ] .Value ; attributes.LD = elemList [ i ] .Attributes [ `` LD '' ] .Value ; attributes.save = elemList [ i ] .Attributes [ `` Save '' ] .Value ; attributes.armour = elemList [ i ] .Attributes [ `` armour '' ] .Value ; attributes.weapons = elemList [ i ] .Attributes [ `` weapons '' ] .Value ; attributes.specialrules = elemList [ i ] .Attributes [ `` specialrules '' ] .Value ; attributes.transport = elemList [ i ] .Attributes [ `` transport '' ] .Value ; attributes.options = elemList [ i ] .Attributes [ `` options '' ] .Value ; //foreach ( string item in attributes ) // { //unit.Add ( item ) ; // } //listBox1.Items.AddRange ( attributes ) } //Close the filestream fs.Close ( ) ; } catch ( Exception ex ) { } } } } using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; namespace ThereIsOnlyRules { class UnitAttributes { public string army { get ; set ; } public string category { get ; set ; } public string type { get ; set ; } public string composition { get ; set ; } public string WS { get ; set ; } public string BS { get ; set ; } public string T { get ; set ; } public string W { get ; set ; } public string I { get ; set ; } public string A { get ; set ; } public string LD { get ; set ; } public string save { get ; set ; } public string armour { get ; set ; } public string weapons { get ; set ; } public string specialrules { get ; set ; } public string transport { get ; set ; } public string options { get ; set ; } } } < ? xml version= '' 1.0 '' ? > < config > < unitarmy= '' Tyranids '' category= '' Troops '' type= '' Infantry '' composition= '' 10-30 '' WS= '' 3 '' BS= '' 3 '' T= '' 3 '' W= '' 1 '' I= '' 4 '' A= '' 1 '' LD= '' 6 '' Save= '' 6+ '' armour= '' Chitin '' weapons= '' Claws and Teeth , Fleshborer '' specialrules= '' Instictive Behaviour - Lurk , Move Through Cover '' transport= '' If the brood consists of 20 models or less , it may take a Mycetic Spore . `` options= '' Strangleweb , Spinefists , Spike rifle , Devourer , Adrenal Glands , Toxin Sacs '' > Termagant Brood < /unit > < unitarmy= '' Tyranids '' category= '' Troops '' type= '' Infantry '' composition= '' 10-30 '' WS= '' 3 '' BS= '' 3 '' T= '' 3 '' W= '' 1 '' I= '' 5 '' A= '' 2 '' LD= '' 6 '' Save= '' 6+ '' armour= '' Chitin '' weapons= '' Scything Talons '' specialrules= '' Instictive Behaviour - Feed , Bounding Leap , Fleet , Move Through Cover '' transport= '' If the brood consists of 20 models or less , it may take a Mycetic Spore . `` options= '' Adrenal Glands , Toxin Sacs '' > Hormagaunt Brood < /unit > < /config >
Outputting Class Of Stored Values To List
C_sharp : My understanding is that x is not actually declared as a variable eg . var x = 3 . Instead , it 's passed into the outer function , which returns a function that returns the original value . At the time it is returning this , it creates a closure around x to remember its value . Then later on , if you alter s , it has no effect.Is this right ? ( Output is 3 by the way , which I 'd expect ) .Edit : here 's a diagram as to why I think it isx=3 is passed into the func , and it returns a function that simply returns x . But x does n't exist in the inner function , only its parent , and its parent no longer exists after I make it null . Where is x stored , when the inner function is ran ? It must create a closure from the parent.Further clarification : Output is 0 , 1 , 2 , 3 , 4However with your example : The output is 5 5 5 5 5 , which is n't what you want . It has n't captured the value of the variable , it 's merely retained a reference to the original s.Closures are created in javascript precisely to avoid this problem . <code> static void Main ( string [ ] args ) { var s = 3 ; Func < int , Func < int > > func = x = > ( ) = > { return x ; } ; var result1 = func ( s ) ; func = null ; s = 5 ; var result2 = result1 ( ) ; Console.WriteLine ( result2 ) ; Console.ReadKey ( ) ; } int s = 0 ; Func < int , Func < int > > func = x = > ( ) = > { return x ; } ; for ( s = 0 ; s < 5 ; s++ ) { var result1 = func ( s ) ; var result2 = result1 ( ) ; Console.WriteLine ( result2 ) ; } ; static void Main ( string [ ] args ) { int s = 0 ; Func < int , Func < int > > func = x = > ( ) = > { return s ; } ; List < Func < int > > results = new List < Func < int > > ( ) ; for ( s = 0 ; s < 5 ; s++ ) { results.Add ( func ( s ) ) ; } ; foreach ( var b in results ) { Console.WriteLine ( b ( ) ) ; } Console.ReadKey ( ) ; }
Is this an example of a closure in C # ?
C_sharp : There are two ways to implement overloads . The first one is to do everything in one method/constructor and call it from other overloads , which leads to longer method bodies . The second one is to do the minimum in each overload , thus having a code sometimes difficult to navigate and to understand which overload does what.For example , if two overloads of a class Cat are : there are two ways to implement this : First typeSecond typeQuestionsHow those two types of overloads are called ( to be able to look for further information on internet or in books ) ? What must be the major concerns/factors to take in account when choosing between those types ? Note : since C # 4.0 let you specify optional parameters , to avoid ambiguity , let 's say I 'm talking about C # 3.0 only . <code> public Cat ( string name , int ? weight , Color mainColor ) ; public Cat ( string name ) ; public Cat ( string name , int ? weight , Color mainColor ) { // Initialize everything . this.name = name ; if ( weight.HasValue ) this.weight = weight.Value ; // There is a bug here ( see the anwer of @ Timwi ) : mainColor can be null . this.colors = new List < Colors > ( new [ ] { mainColor } ) ; } public Cat ( string name ) : this ( name , null , null ) { // Nothing else to do : everything is done in the overload . } public Cat ( string name ) { // Initialize the minimum . this.name = name ; this.colors = new List < Colors > ( ) ; } public Cat ( string name , int ? weight , Color mainColor ) : this ( name ) { // Do the remaining work , not done in the overload . if ( weight.HasValue ) this.weight = weight.Value ; this.colors.Add ( mainColor ) ; }
How to choose between one big method with passive overloads and a bunch of small overloads , each one doing a small amount of work ?
C_sharp : Is this possible in C # ? The following code produces a compiler error.The C # compiler complains , `` Error CS0149 : Method name expected . '' It 's unable to infer the lambda method 's return type.Note my technique of invoking the lambda method immediately via the ( ) after the the lambda block is closed { } . This ensures a Task is returned , not a Func.The VB.NET compiler understands this syntax . I am stunned to find an example of the VB.NET compiler outsmarting the C # compiler . See my An Async Lambda Compiler Error Where VB Outsmarts C # blog post for the full story.The VB.NET compiler understands the End Function ( ) technique . It correctly infers the lambda method 's return type is Function ( ) As Task ( Of ( Value As String , ToNodeId As Integer ) ) and therefore invoking it returns a Task ( Of ( Value As String , ToNodeId As Integer ) ) . This is assignable to the regionTasks variable.C # requires me to cast the lambda method 's return value as a Func , which produces horribly illegible code.Terrible . Too many parentheses ! The best I can do in C # is explicitly declare a Func , then invoke it immediately.Has anyone found a more elegant solution ? <code> HashSet < Task < ( string Value , int ToNodeId ) > > regionTasks = new HashSet < Task < ( string Value , int ToNodeId ) > > ( ) ; foreach ( Connection connection in Connections [ RegionName ] ) { regionTasks.Add ( async ( ) = > { string value = await connection.GetValueAsync ( Key ) ; return ( value , connection.ToNode.Id ) ; } ( ) ) ; } Dim regionTasks = New HashSet ( Of Task ( Of ( Value As String , ToNodeId As Integer ) ) ) For Each connection In Connections ( RegionName ) regionTasks.Add ( Async Function ( ) Dim value = Await connection.GetValueAsync ( Key ) Return ( value , connection.ToNode.Id ) End Function ( ) ) Next regionTasks.Add ( ( ( Func < Task < ( string Values , int ToNodeId ) > > ) ( async ( ) = > { string value = await connection.GetValueAsync ( Key ) ; return ( value , connection.ToNode.Id ) ; } ) ) ( ) ) ; Func < Task < ( string Value , int ToNodeId ) > > getValueAndToNodeIdAsync = async ( ) = > { string value = await connection.GetValueAsync ( Key ) ; return ( value , connection.ToNode.Id ) ; } ; regionTasks.Add ( getValueAndToNodeIdAsync ( ) ) ;
Assign C # Async Lambda Method to Variable Typed as a Task
C_sharp : When I run my C # application , Visual Studio reports that it has loaded a managed binary with ( what looks like ) a randomly generated name . For example : or : What is this , and why is its name ( seemingly ) randomly generated ? <code> 'WindowsFormsApplication1.vshost.exe ' ( Managed ) : Loaded 'ehmgcsw7 ' 'WindowsFormsApplication1.vshost.exe ' ( Managed ) : Loaded 'jvo4sksu '
When I run my C # application , Visual Studio reports that it has loaded a managed binary with ( what looks like ) a randomly generated name
C_sharp : I 'm using string.Join to be able to show what values an array contains . I have stumbled upon a strange behavior when using a byte array and startIndex and count.gives this resultWhole byteArr : 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8Whole stringArr : 1 , 2 , 3 , 4 , 5 , 6 , 7 , 80 - 5 byteArr : System.Byte [ ] , 0 , 50 - 5 stringArr : 1 , 2 , 3 , 4 , 5Why do string.Join ( `` , `` , byteArr,0,5 ) return the string System.Byte [ ] , 0 , 5 <code> byte [ ] byteArr = new byte [ ] { 1,2,3,4,5,6,7,8 } ; string [ ] stringArr = new string [ ] { `` 1 '' , '' 2 '' , '' 3 '' , '' 4 '' , '' 5 '' , '' 6 '' , '' 7 '' , '' 8 '' } ; Console.WriteLine ( string.Format ( `` Whole byteArr : { 0 } '' , string.Join ( `` , `` , byteArr ) ) ) ; Console.WriteLine ( string.Format ( `` Whole stringArr : { 0 } '' , string.Join ( `` , `` , stringArr ) ) ) ; Console.WriteLine ( string.Format ( `` 0 - 5 byteArr : { 0 } '' , string.Join ( `` , `` , byteArr,0,5 ) ) ) ; Console.WriteLine ( string.Format ( `` 0 - 5 stringArr : { 0 } '' , string.Join ( `` , `` , stringArr,0,5 ) ) ) ;
Strange behavior of string.Join on byte array and startIndex , count
C_sharp : I 'm making a WPF text-editor using TextFormatter . I need to justify the last line in each paragraph . Something like that : how to make this happen ? Thanks in advance ! ! <code> I need to justify the last line in eachparagraph I need to justify the last line in each paragraph I need to justify the last line in each paragraph I need to justify the last line in
Full justify of last line in WPF TextFormatter
C_sharp : is that an `` ok '' code ? I need to do complex operation in the finally and it might crash since it 's connecting to the a DBthis look weird to me , so . is this the proper way ? <code> try { /*stuff*/ } catch ( Exception e ) { /*stuff*/ } finally { try { /*stuff*/ } catch { /*empty*/ } }
is it ok to have a try/catch in a finally ?
C_sharp : Currently , I have a bunch of classes of this form that I 'd like to create at runtime using Reflection.Emit . However , I 'm running into an issue when I attempt to add the parent - since the TestAdmin class does n't exist before runtime , I do n't know how to create Any ideas ? <code> [ Name ( `` Admin '' ) ] public class TestAdmin : TestUserBase < TestAdmin > { public TestAdmin ( Type webDriverType ) : base ( webDriverType ) { } } TestUserBase < TestAdmin >
Using emitted type as type parameter in Reflection.Emit
C_sharp : I have a few days looking at RX , and I have read a lot ; I have read IntroToRx ; I have also looked at 101 RX Samples , and many other places , but I ca n't figure this out . It sounds so simple , but I ca n't get what I need : I need to know which `` ID '' has been `` stuck '' in state 'STARTED ' for at least 30 minutes.I have a class MyInfo that looks like this : And I have coded a Subject to help me test like this : My query and subscription looks like this so far : ( I 'm using seconds in the sample ) Now I can get an output that tells me ID and what states that ID has seen in the period of time.What I wanted to do next is first , discard those that have seen more than 1 state in the interval ( So IDs 2 and 4 would get eliminated ) , and of the ones left over , discard those that have a status that is n't `` STARTED '' ( that would eliminate ID 3 ) . And ID 1 is the record I 'm looking for.Is that the best approach at the problem ? And how do I achieve that query ? Also , how can I have my subject send the messages in different intervals , so I can test the windowing.Thanks ! <code> public class MyInfo { public string ID { get ; set ; } public string Status { get ; set ; } } var subject = new Subject < MyInfo > ( ) ; subject.OnNext ( new MyInfo ( ) { ID = `` 1 '' , Status = `` STARTED '' } ) ; subject.OnNext ( new MyInfo ( ) { ID = `` 2 '' , Status = `` PHASE1 '' } ) ; subject.OnNext ( new MyInfo ( ) { ID = `` 3 '' , Status = `` STOPPED '' } ) ; subject.OnNext ( new MyInfo ( ) { ID = `` 4 '' , Status = `` STARTED '' } ) ; subject.OnNext ( new MyInfo ( ) { ID = `` 1 '' , Status = `` STARTED '' } ) ; subject.OnNext ( new MyInfo ( ) { ID = `` 2 '' , Status = `` PHASE1 '' } ) ; subject.OnNext ( new MyInfo ( ) { ID = `` 3 '' , Status = `` STOPPED '' } ) ; subject.OnNext ( new MyInfo ( ) { ID = `` 4 '' , Status = `` PHASE2 '' } ) ; subject.OnNext ( new MyInfo ( ) { ID = `` 1 '' , Status = `` STARTED '' } ) ; subject.OnNext ( new MyInfo ( ) { ID = `` 2 '' , Status = `` STOPPED '' } ) ; subject.OnNext ( new MyInfo ( ) { ID = `` 3 '' , Status = `` STOPPED '' } ) ; subject.OnNext ( new MyInfo ( ) { ID = `` 4 '' , Status = `` STARTED '' } ) ; subject.OnCompleted ( ) ; var q8 = from e in subject group e by new { ID = e.ID , Status = e.Status } into g from w in g.Buffer ( timeSpan : TimeSpan.FromSeconds ( 3 ) , timeShift : TimeSpan.FromSeconds ( 1 ) ) select new { ID = g.Key.ID , Status = g.Key.Status , count = w.Count } ; var subsc = q8.Subscribe ( a = > Console.WriteLine ( `` { 0 } { 1 } { 2 } '' , a.ID , a.Status , a.count ) ) ; ID Status Count1 STARTED 32 PHASE1 23 STOPPED 34 STARTED 24 PHASE2 12 STOPPED 1
Using RX queries , how to get which records have same status for a window of 3 seconds every second ?
C_sharp : I 'm writing a translator , not as any serious project , just for fun and to become a bit more familiar with regular expressions . From the code below I think you can work out where I 'm going with this ( cheezburger anyone ? ) .I 'm using a dictionary which uses a list of regular expressions as the keys and the dictionary value is a List < string > which contains a further list of replacement values . If I 'm going to do it this way , in order to work out what the substitute is , I obviously need to know what the key is , how can I work out which pattern triggered the match ? Is what I 'm attempting possible , or is there a better way to achieve this insanity ? <code> var dictionary = new Dictionary < string , List < string > > { { `` ( ? ! e ) ight '' , new List < string > ( ) { `` ite '' } } , { `` ( ? ! ues ) tion '' , new List < string > ( ) { `` shun '' } } , { `` ( ? : god|allah|buddah ? |diety ) '' , new List < string > ( ) { `` ceiling cat '' } } , .. } var regex = `` ( `` + String.Join ( `` ) | ( `` , dictionary.Keys.ToArray ( ) ) + `` ) '' ; foreach ( Match metamatch in Regex.Matches ( input , regex , RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture ) ) { substitute = GetRandomReplacement ( dictionary [ ? ? ? ? ? ] ) ; input = input.Replace ( metamatch.Value , substitute ) ; }
Determining which pattern matched using Regex.Matches
C_sharp : I have created a method for reading inbox new messages by using exchange server like below.How to add these IEnumerable collection to a Queue and Process each List of item inside the queue asynchronously ? The below are the process i need to call asynchronously by using each items in the queue <code> private static IEnumerable < ExchangeEmailInformation > GetInboxItems ( ExchangeService service ) { var emailInformations = new List < ExchangeEmailInformation > ( ) ; try { SearchFilter searchFilter = new SearchFilter.SearchFilterCollection ( LogicalOperator.And , new SearchFilter.IsEqualTo ( EmailMessageSchema.IsRead , false ) ) ; var itemview = new ItemView ( int.MaxValue ) ; FindItemsResults < Item > findResults = service.FindItems ( WellKnownFolderName.Inbox , searchFilter , itemview ) ; Console.WriteLine ( `` \n -- -- -- -- -- -- -Result found : -- -- -- -- -- -- - '' ) ; service.LoadPropertiesForItems ( findResults , PropertySet.FirstClassProperties ) ; foreach ( var item in findResults ) { emailInformations.Add ( new ExchangeEmailInformation { Attachment = item.Attachments ? ? null , Body = item.Body.BodyType == BodyType.HTML ? ConvertHtml.ToText ( item.Body.Text ) : item.Body.Text , Subject = item.Subject , RecievedDate = item.DateTimeReceived } ) ; } } catch ( Exception ee ) { Console.WriteLine ( `` \n -- -- -- -- -- -- -Error occured : -- -- -- -- -- -- - '' ) ; Console.WriteLine ( ee.Message.ToString ( ) ) ; Console.WriteLine ( ee.InnerException.ToString ( ) ) ; Console.ReadKey ( ) ; } return emailInformations ; } static void AddAttachment ( string subject , string docId , string user , string fileName ) { var url = new StringBuilder ( ) ; url.Append ( string.Format ( `` https : //webdemo-t.test.com:8443/Services/Service/MyService.svc/AddAttachment ? User= { 0 } & Engagement= { 1 } & FileName= { 2 } & DocumentTrasferID= { 3 } '' , user , subject , fileName , docId ) ) ; Console.WriteLine ( url.ToString ( ) ) ; WebRequest request = WebRequest.Create ( url.ToString ( ) ) ; var credential = new NetworkCredential ( `` user '' , `` xxxx '' , `` xxxx '' ) ; request.Credentials = credential ; WebResponse ws = request.GetResponse ( ) ; Encoding enc = System.Text.Encoding.GetEncoding ( 1252 ) ; var responseStream = new StreamReader ( ws.GetResponseStream ( ) ) ; string response = responseStream.ReadToEnd ( ) ; responseStream.Close ( ) ; Console.WriteLine ( response ) ; }
How to add an IEumerable Collection to a Queue and Process each item asynchronously in .NET ?
C_sharp : I have a simple .NET application which runs as Windows Service . Say it has one Class I want to create a console application where I would type simple human readable commandslike Pretty much like you do in windows console . I wonder what is the best way to implement this mapping . A straight methods is of course create your own string parser with lots of switch statements but I think if there is better and faster method . <code> MyClass { Run ( Destination d ) Walk ( Destination d ) Wash ( Dishes d ) } run leftwalk right
Scripting .NET objects
C_sharp : I am using string builder to format my string to append and prepend white spaces at the start and end of the stringhere is what I have so far : but I 'm getting the error incorrect format . What am i doing wrong ? <code> private void button1_Click ( object sender , EventArgs e ) { String Word = textBox1.Text ; AppendPrependText ( Word ) ; } private void AppendPrependText ( String Word ) { int count = Convert.ToInt32 ( textBox2.Text ) ; int WordCount = Word.Count ( ) ; int totalChar = count + WordCount ; string format = `` { - '' +totalChar+ `` , '' +totalChar+ `` } '' ; StringBuilder sb = new StringBuilder ( ) ; sb.AppendLine ( string.Format ( format , Word ) ) ; textBox3.Text = sb.ToString ( ) ; }
Inserting user defined number of spaces before and after string using C #
C_sharp : I am currently migrating a project to PostSharp to remove a lot of boilerplate code , most of it is going very smoothly but I 'm left confused about how to force a command to recheck if it CanExecute . I expected PostSharp would inspect the command like it does properties to check for dependencies , here is a minimalist sampleAt start the collection is empty and the button attached to the close command is greyed as expected , however adding a document through the button attached to AddDocument does n't activate the close document button , what is the appropriate way to accomplish what I need ? Is PostSharp only considering assignments and not method calls as changes or is it something else entirely ? <code> [ NotifyPropertyChanged ] public class MyWindowViewModel { /// Anything bound to this refreshes just fine as expected public ObservableCollection < SomeType > Documents = new ObservableCollection < SomeType > ( ) ; [ Command ] public ICommand AddDocumentCommand { get ; set ; } public void ExecuteAddDocument ( ) { Documents.Add ( new SomeType ( ) ) ; } [ Command ] public ICommand CloseDocumentCommand { get ; set ; } public bool CanExecuteCloseDocument ( ) = > Documents.Any ( ) ; public void ExecuteCloseDocument ( ) { Documents.Remove ( Documents.Last ( ) ) ; } }
Triggering `` CanExecute '' on postsharp [ Command ] when a document changes ?
C_sharp : I work an an automation team designing tests for electronic components . One thing our framework sorely needs is a single source point for our driver objects for the various pieces of test equipment at a workbench ( right now , driver object creation is very wild-west ) . Basically , the idea would be there would be one object , constructed based on a configuration file ( s ) , which is the single place all other test code looks to to get the driver objects , based on a name string . I 'll call it a `` DriverSource '' here.The problem is , these drivers do not present similar interfaces at all . One might be a power supply ( with methods like `` SetVoltage '' and `` SetCurrentLimit '' ) , while another might be a digital multimeter ( with methods like `` ReadVoltage '' or `` ReadCurrent '' ) .The best solution I 've come up with is to have a method with the following declaration : Then , the test code using my `` DriverSource '' object would call that method , and then cast the System.Object to the correct driver type ( or more accurately , the correct driver interface , like IPowerSupply ) . I think casting like that is acceptable because whatever test code is about to use this driver had better know what the interface is . But I was hoping to get some input on whether or not this is an anti-pattern waiting to bite me . Any better pattern for solving this issue would also be greatly appreciated.A final note : I think this is obvious , but performance is essentially a non-issue for this problem . Fetching the drivers is something will happen less than 100 times in a test run that can last hours . <code> public object GetDriver ( string name ) ;
Is this method returning a System.Object class an anti-pattern ?
C_sharp : I have the following class : When I try to find out size of this class on a 64 bit system by using WinDbg I get the size 40which I am not able to understand , as far as I have read MyClass should haveI do n't have 10 reputation that 's why i am not able to post image.Anyone has any idea why WinDbg is showing 4 extra bytes ? <code> public class MyClass { public string Name { get ; set ; } public int Age { get ; set ; } public double Amount { get ; set ; } } 8 bytes for SyncBlock8 bytes for TypeHandle8 bytes for string reference4 bytes for Int328 bytes for double= 36 bytes
How to determine size of an object , c # ?
C_sharp : Short Question : Provided I have given an implicit conversion mechanism for my object to convert its values from a plain string , can it be made to auto-bind to ViewModel 's property ? Details : I have a complex object like so ( simplified for brevity and clarity ) I am using the above object in my view model as below : And the Action in my Controller is set asMy issue is in the Action , even though I have given an implicit casting from string to DataScope class it fails to properly bind during execution.I have tested the casting with the value that is being passed ( Pivot1 here ) separately and the casting works fine.Is there a way to make this casting happen implicitly or should I change the view models Scope variable to plain string and then do a manual casting . <code> public enum PrimaryScopeEnum { Pivot1 , Pivot2 } public enum SecondaryScopeEnum { Entity1 , Entity2 , Entity3 , Entity4 } public class DataScope { public PrimaryScopeEnum PrimaryScope { get ; set ; } public SecondaryScopeEnum SecondaryScope { get ; set ; } public static implicit operator DataScope ( string combinedScope ) { DataScope ds = new DataScope ( ) ; // Logic for populating Primary and Secondary Scope enums return ds ; } } public enum PageModeEnum { View , Add , Edit } public class DisplayInfoViewModel { public string SetID { get ; set ; } public PageModeEnum PageMode { get ; set ; } public DataScope Scope { get ; set ; } } // Accessed with /MyController/DisplayInfo ? SetID=22 & PageMode=View & Scope=Pivot1public virtual ActionResult DisplayInfo ( DisplayInfoViewModel vm ) { // vm.SetID is 22 // vm.PageMode is PageModeEnum.View // vm.Scope is null return View ( vm ) ; }
Can a QueryString parameter be bound to a complex object if the complex object has implicit casting from string
C_sharp : I 'm looking to add a `` recently opened '' functionality to my application , and was wondering if there was a simple built in way to do lists that `` overflow '' . By this I mean , when you add an element beyond the capacity of the list , all the items are shifted.Code example of desired functionality ( obviously its not true , the list would actually contain A , B , C ) : Sorry for the simple question . The problem itself is obvious to solve ( intail plan was to inherit from List ) , I just do n't like having to re-invent the wheel and confuse future programmers with custom objects when the language or framework has that functionality . <code> List < string > list = new List < string > ( ) ; //if Overflow was 2list.Add ( `` A '' ) ; list.Add ( `` B '' ) ; //List now contains A , Blist.Add ( `` C '' ) ; //List now contains B , C
Does .NET have a simple way to do overflow lists ?
C_sharp : I have a database table that looks like this : Now . This is a Status History indicator for DetectorID 1541.I only want to show 1 row at my website . To do this i excecute the following query.So what it does , it grabs the newest row ( Based on TimeStamp ) , and shows it.This will give me the results of ScannerStatusHistoryID 61 . But , what i would like to have , is the row of the last time a value got changed . As you can see on ScannerStatusHistoryID 54 , RC3 had a value of 4 . Then on ScannerStatusHistoryID 57 , it changed back to 3.Since then , the values did not change.What i would like to have then , is the query to grab the ScannerStatusHistoryID 57 . Untill the value changes again , then i want it to grab the first of that one.How do i achieve this ? i was thinking about counting the results where it matched the last query . However , in this example , it will return 7 results ( Since the first 4 are the same as the last 3 ) . And so it wont give you the right result . <code> [ Query ] public IQueryable < ScannerStatusHistory > GetScannerStatusHistoryy ( int detectorID ) { return ObjectContext.ScannerStatusHistories.Where ( t = > t.DetectorID == detectorID ) .OrderByDescending ( d = > d.TimeStamp ) .Take ( 1 ) ; ; }
C # Query Select first since value changed
C_sharp : I have to deserialize a response from an api which has the following structure : Some insights : The JSON is an array of objectsEvery object inside the array will ALWAYS have the properties `` starttime '' and `` endtime '' Objects `` var1 '' , `` var2 '' , `` var3 '' will ALWAYS have the same properties inside them ... but the problem is that the object keys ( var1 , var2 or var3 ) are dynamic . It can be any string , and also the amount of this kind of objects is dynamic ( I could have 3 , or zero `` var '' objects ) .I was thinking something like this , to deserialize the JSON string into a List of objects with properties `` starttime '' , `` endtime '' and a dictionary with all the `` var '' objects.But the VarData property is always null.Has anyone tried something like this ? <code> [ { `` starttime '' : `` ... '' , `` endtime '' : `` ... . '' , `` var1 '' : { } , `` var2 '' : { } } , { `` starttime '' : `` ... '' , `` endtime '' : `` ... . '' , `` var1 '' : { } , `` var3 '' : { } } , { `` starttime '' : `` ... '' , `` endtime '' : `` ... . '' , `` var1 '' : { } } ] public class MyResponse { [ JsonProperty ( PropertyName = `` starttime '' ) ] public string StartTime { get ; set ; } [ JsonProperty ( PropertyName = `` endtime '' ) ] public string EndTime { get ; set ; } public Dictionary < string , VarObject > VarData { get ; set ; } }
How to deserialize JSON with dynamic and static key names in C #
C_sharp : I 'm inheriting from TextBox and overriding OnInit . I have MyBase.OnInit ( e ) in the example above , but I 've been using my control for a while without it , as I forgot to put it in there . This is something I usually do out of habit , so I never gave its purpose much thought : When overriding OnInit in a derived class , be sure to call the base class ’ s OnInit method so that registered delegates receive the event.Slightly embarrassing that this is n't clear to me , but my control works fine , so I was just hoping someone could give an example of what could create an issue . <code> Protected Overrides Sub OnInit ( e As EventArgs ) MyBase.OnInit ( e ) ' I 'm adding a dynamic control to go along with my textbox here ... Controls.Add ( Something ) End Sub
What 's the impact of not using MyBase.OnInit ( e ) when overriding it in a derived class ?
C_sharp : I have an MVC application which has a restful service that updates latitude and longitude to the database . I am sending the values to the API as string and its converted to Double before it is stored in database as Double . Here is the code I am using to convert string to double : When its stored in database I am missing decimal points . For example : 53.345634 is stored as 53345634I have this working on development environment running on Windows 2012 . But when its moved to Windows 2008 production server I am seeing this issue . <code> Double _latitude , _longitude ; try { Double.TryParse ( lattitude , NumberStyles.Any , CultureInfo.CurrentCulture , out _latitude ) ; Double.TryParse ( Longtitude , NumberStyles.Any , CultureInfo.CurrentCulture , out _longitude ) ; } catch ( Exception e ) { _latitude = 0 ; _longitude = 0 ; }
Double is not stored correctly in MySQL database
C_sharp : I 'm trying to figure out how to define if string contains/does not contains list value and if contains but with other value . If I have input string : and I want find specific value for condition : But not sure what is a proper way if I want to know also about third condition , if string contains value but also contains other words.For string : inputString = `` it was one '' ; desired result should be : for string : inputString = `` one '' ; and for : inputString = `` it was '' ; <code> string inputString = `` it was one '' ; var numbList = new List < string > { `` zero '' , `` one '' , `` two '' } ; if ( ! numbList.Any ( inputString.Contains ) ) { Console.WriteLine ( `` string does not contains list value '' ) ; } else { Console.WriteLine ( `` string contains list value '' ) ; } Console.WriteLine ( `` string contains list value and other words '' ) ; Console.WriteLine ( `` string contains list value '' ) ; Console.WriteLine ( `` string does not contains list value '' ) ;
How to check if string contains list value and separately if contains but with other value
C_sharp : I 'm inheriting the code someone else wrote at work and found that there are a lot of `` new '' instantiating without actually assigning to a variable : I 'm just wondering if anyone has any experience with this and if this is anti-pattern or not . <code> new MyCoolClass ( ) .MyCoolMethod ( ) ;
Instantiating without assigning to a variable
C_sharp : What is the difference in autofac between these two registrations : andwhere Instance is a ( non-static ) property of an autofac module in which the registration occurs , set by object initializer.My reason for asking is that the former has been done in a piece of code I 'm debugging and I 'm getting some strange behavior as though there are two instances of ISomeInterface floating around . The functional need is for the Instance to live for the life of the container ( = life of application ) .Please do n't tell me that I should not do the first -- it 's been done and I 'm trying to understand what could go wrong/behave strangely as a result . <code> builder.Register ( c = > Instance ) .As < ISomeInterface > ( ) ; builder.RegisterInstance ( Instance ) .As < ISomeInterface > ( ) .SingleInstance ( ) .ExternallyOwned ( ) ;
What is the difference between these two ways of registering an instance in autofac
C_sharp : Given the following LinqPad example : Why can EnumerableMethod take the list directly while ListMethod needs a cast first ? I get that an cast is happening from DbItem to IDbItem , but what is different about the IEnumerable that allows it to make the cast without an express request ? I imagine the answer involves the word Covariance , but I do n't know enough about that to just figure it out myself . <code> void Main ( ) { List < DbItem > dbItems = new List < DbItem > { new DbItem { Id = 4 , SomeValue = `` Value For 4 '' , OtherValue = 1 } , new DbItem { Id = 19 , SomeValue = `` Value For 19 '' , OtherValue = 2 } } ; ListMethod ( dbItems.Cast < IDbItem > ( ) .ToList ( ) ) ; < -+ EnumerableMethod ( dbItems ) ; < -+ } | |// These are the methods are I asking about -- -- -- -+public void ListMethod ( List < IDbItem > dbItems ) { Console.WriteLine ( dbItems ) ; } public void EnumerableMethod ( IEnumerable < IDbItem > dbItems ) { Console.WriteLine ( dbItems ) ; } public class DbItem : IDbItem { public int Id { get ; set ; } public string SomeValue { get ; set ; } public int OtherValue { get ; set ; } } public interface IDbItem { int Id { get ; set ; } string SomeValue { get ; set ; } }
Why does IEnumerable not need a cast but a List does ?
C_sharp : So here is my problem , I have an API setup that returns results from Azure Storage Table in JSON string format : And I am trying to convert it back to Project object : I keep getting `` Error converting value from 'string ' to 'object'.I have tried : this , this , this , this , this , this and this and it wo n't work . Always the same error . It 's obvious I am missing something , but it has been two days and I ca n't seem to figure it out . Have tried modifying the object class to include all fields , tried adding another class that has list property , even tried passing it as Array.At this point , I would be grateful of any kind of help . <code> [ { `` CustID '' : `` f3b6 ... ..0768bec '' , `` Title '' : `` Timesheet '' , `` CalendarID '' : `` AAMkADE5ZDViNmIyLWU3N2 ... ..pVolcdmAABY3IuJAAA= '' , `` PartitionKey '' : `` Project '' , `` RowKey '' : `` 94a6 ... ..29a4f34 '' , `` Timestamp '' : `` 2018-09-02T11:24:57.1838388+03:00 '' , `` ETag '' : `` W/\ '' datetime'2018-09-02T08 % 3A24 % 3A57.1838388Z'\ '' '' } , { `` CustID '' : `` 5479b ... ..176643c '' , `` Title '' : `` Galaxy '' , `` CalendarID '' : `` AAMkADE5Z ... ... .boA_pVolcdmAABZ8biCAAA= '' , `` PartitionKey '' : `` Project '' , `` RowKey '' : `` f5cc ... .86a4b '' , `` Timestamp '' : `` 2018-09-03T13:02:27.642082+03:00 '' , `` ETag '' : `` W/\ '' datetime'2018-09-03T10 % 3A02 % 3A27.642082Z'\ '' '' } ] public class Project : TableEntity { public Project ( ) { } public Project ( string rKey , string pKey = `` Project '' ) { this.PartitionKey = pKey ; this.RowKey = rKey ; } public Guid CustID { get ; set ; } public string Title { get ; set ; } public string CalendarID { get ; set ; } }
Converting from json to List < object > causing exception
C_sharp : Assuming we have the following model : And the following implementation : Now my question : Is codesnippet # 1 equivalent to codesnippet # 2 ? Or does it take longer to run codesnippet # 1 ? CodeSnippet # 1 : CodeSnippet # 2 : <code> public class Father { public Child Child { get ; set ; } public string Name { get ; set ; } public Father ( ) { } } public class Child { public Father Father ; public string Name { get ; set ; } } var father = new Father ( ) ; father.Name = `` Brad '' ; var child = new Child ( ) ; child.Father = father ; child.Name = `` Brian '' ; father.Child = child ; var fatherName = father.Child.Father.Child.Father.Child.Name ; var fatherName = father.Name ;
Is the C # or JIT compiler smart enough to handle this ?
C_sharp : I have a FlipView in my MainPage . It 's ItemTemplate binded to a UserControl called landscapeControl . It 's ItemsSource is binded to a List of a class called MyLandscape . landscapeControl : MyLandscape class : My images are showing perfectly . All I want is 3 things:1 ) I want to access my Canvas from my MainPage . I am trying to do this in flipView_SelectionChanged event : But the pc variable is always null ! I want to bind my Canvas , so I have a Canvas for every two images ? Is that possible ? <code> < Grid > < ScrollViewer x : Name= '' LScrollViewer '' MaxZoomFactor= '' 2.0 '' MinZoomFactor= '' 1.0 '' HorizontalScrollBarVisibility= '' Hidden '' VerticalScrollBarVisibility= '' Hidden '' DoubleTapped= '' LScrollViewer_DoubleTapped '' > < Canvas x : Name= '' inkCanvas '' Background= '' Transparent '' > < StackPanel x : Name= '' LStackPanel '' Orientation= '' Horizontal '' Margin= '' 0,0,0,0 '' > < Image x : Name= '' LImage0 '' HorizontalAlignment= '' Right '' Source= '' { Binding firstImage } '' Width= '' 570 '' / > < Image x : Name= '' LImage1 '' HorizontalAlignment= '' Left '' Source= '' { Binding nextImage } '' Width= '' 570 '' / > < /StackPanel > < /Canvas > < /ScrollViewer > < /Grid > public class MyLandscape { public ImageSource firstImage { get ; set ; } public ImageSource nextImage { get ; set ; } public Canvas inkCanvas { get ; set ; } } landscapeControl pc = flipView1.SelectedItem as landscapeControl ; if ( flipView1.Items.Count > 0 ) { var myCanvas = pc.getCanvas ( ) ; m_CanvasManager = new CanvasManager ( myCanvas ) ; }
Access a Canvas inside an ItemsSource in a UserControl , from the MainPage
C_sharp : There 's a subtle point about assembly dependencies I would like to understand . I have a project which uses SharpDX through a custom wrapper like so : SharpDX.dll < - Wrapper.dll < - Project.dllIn Wrapper.dll is a type such as : In this class , if I uncomment the commented constructor , then Project.dll must reference SharpDX.dll , even if it does n't use the constructor.However , I also have another wrapper type like so : And here , as long as I do n't actually use the GetDevice method that returns a SharpDX object , Project.dll does n't need to reference SharpDX.dll.Why is it that even an unused constructor that takes a parameter of a SharpDX type causes a dependency on SharpDX , whereas an unused method that returns a parameter of a SharpDX type does n't ? <code> public class D3DWrapperTypeA { //public D3DWrapperTypeA ( SharpDX.Device device ) { // // } public D3DWrapperTypeA ( IntPtr devicePointer ) { SharpDX.Device device = new SharpDX.Device ( devicePointer ) ; // etc } } public class WrapperTypeB { public SharpDX.Device GetDevice ( int adapter ) { // etc } public IntPtr GetDevicePointer ( int adapter ) { return GetDevice ( adapter ) .NativePointer ; } }
Why does an unused constructor cause an assembly dependency in this case ?
C_sharp : In my form I have four RadioButtons , based on user selection , this code is executed : The code seems very redundant and repeated , but also I ca n't find a way to handle all 4 RadioButtons in a single line that has only one variable linked to user choice.myList is a List of a class I created that has 4 string properties ( Name , Age , Gender , Occu ) <code> private void button1_Click ( object sender , EventArgs e ) { listBox1.Items.Clear ( ) ; if ( radioButtonName.Checked ) { var Qr = from n in mylist where n.Name == textBoxSearch.Text select new { n.Name , n.Age , n.Occu , n.Gender } ; foreach ( var item in Qr ) { listBox1.Items.Add ( `` Name : `` + item.Name + `` `` + `` Age : `` + item.Age + `` `` + `` Occupation : `` + item.Occu + `` `` + `` Gender : `` + item.Gender ) ; } } if ( radioButtonAge.Checked ) { var Qr = from n in mylist where n.Age == textBoxSearch.Text select new { n.Name , n.Age , n.Occu , n.Gender } ; foreach ( var item in Qr ) { listBox1.Items.Add ( `` Name : `` + item.Name + `` `` + `` Age : `` + item.Age + `` `` + `` Occupation : `` + item.Occu + `` `` + `` Gender : `` + item.Gender ) ; } } if ( radioButtonGender.Checked ) { var Qr = from n in mylist where n.Gender == textBoxSearch.Text select new { n.Name , n.Age , n.Occu , n.Gender } ; foreach ( var item in Qr ) { listBox1.Items.Add ( `` Name : `` + item.Name + `` `` + `` Age : `` + item.Age + `` `` + `` Occupation : `` + item.Occu + `` `` + `` Gender : `` + item.Gender ) ; } } if ( radioButtonOccupation.Checked ) { var Qr = from n in mylist where n.Occu == textBoxSearch.Text select new { n.Name , n.Age , n.Occu , n.Gender } ; foreach ( var item in Qr ) { listBox1.Items.Add ( `` Name : `` + item.Name + `` `` + `` Age : `` + item.Age + `` `` + `` Occupation : `` + item.Occu + `` `` + `` Gender : `` + item.Gender ) ; } } }
Best way to handle redundant code that has repeated logic ?
C_sharp : I do n't understand why code first does not add a new item to the collection until after calling savechanges . I installed EF4.1 from NuGet ( 4.1.10331.0 ) . I created the following example : First I added one record to the database . Then I ran this and these are the results : My questions are : - Why does the first call to ctx.Items.Local give my zero items ? - Why does the list of ctx.Items not contain the just added item before I called SaveChanges ? <code> public class TinyItem { public int Id { get ; set ; } public string Name { get ; set ; } } public class TinyContext : DbContext { public virtual DbSet < TinyItem > Items { get ; set ; } } class Program { static void Main ( string [ ] args ) { using ( var ctx1 = new TinyContext ( ) ) { ListItems ( ctx1 , `` Start '' ) ; ctx1.Items.Add ( new TinyItem { Name = `` Test1 '' } ) ; ListItems ( ctx1 , `` After add '' ) ; ctx1.SaveChanges ( ) ; ListItems ( ctx1 , `` After commit '' ) ; } Console.ReadKey ( ) ; } public static void ListItems ( TinyContext ctx , string label= '' '' ) { Console.WriteLine ( `` ========================================= '' ) ; Console.WriteLine ( label ) ; Console.WriteLine ( string.Format ( `` Items.Local : { 0 } '' , ctx.Items.Local.Count ) ) ; foreach ( var item in ctx.Items.Local ) { Console.WriteLine ( string.Format ( `` { 0 } = { 1 } '' , item.Id , item.Name ) ) ; } Console.WriteLine ( string.Format ( `` Items : { 0 } '' , ctx.Items.Count ( ) ) ) ; foreach ( var item in ctx.Items ) { Console.WriteLine ( string.Format ( `` { 0 } = { 1 } '' , item.Id , item.Name ) ) ; } Console.WriteLine ( `` ========================================= '' ) ; } ========================================= Start Items.Local : 0 Items : 1 4 = Test1 ========================================= ========================================= After add Items.Local : 2 4 = Test1 0 = Test1 Items : 1 4 = Test1 ========================================= ========================================= After commit Items.Local : 2 4 = Test1 5 = Test1 Items : 2 4 = Test1 5 = Test1 =========================================
EF4 code first adding items not very clear to me
C_sharp : Just ca n't get it with datepicker validation.I have datepicker From and datepicker To , so I want to prevent the user from doing some kung fu and seting datepicker From to be bigger than datepicker To , I 've bumped across some questions but could n't find the answer , so I 've tried doing the easiest way I could think of : Set MaxDate property for datepicker from in form_load eventThen do the same for value_changed event This was easy and fine , only few lines of code , and I 've only needed datepickerFrom_ValueChanged event , but recently I 've tried typing date into datepicker insted of selecting it , and then all hell broke loose.So I came to some solution for validation , instead of setting MaxDate property , I 've tried this.This works fine , but feels like bit of headache , and I have to do this for datepickerTO_ValueChanged event also , sure I could make one method and call it two times , but still feels like there is a batter way for this , so any suggestions ? Thank you for your time <code> private void Form1_Load ( object sender , EventArgs e ) { datepickerFrom.MaxDate = datepickerFrom.Value ; } private void datepickerFrom_ValueChanged ( object sender , EventArgs e ) { datepickerFrom.MaxDate = datepickerFrom.Value ; } private void dtFrom_ValueChanged ( object sender , EventArgs e ) { DateTime from = datepickerFrom.Value ; DateTime to = datepickerTo.Value ; int year= from.Year > to.Year ? to.Year : from.Year ; int month = from.Month > to.Month ? to.Month : from.Month ; int day = from.Day > to.Day ? to.Day : from.Day ; int hour = from.Hour > to.Hour ? to.Hour : from.Hour ; int minute = from.Minute > to.Minute ? to.Minute : from.Minute ; int second = from.Second > to.Second ? to.Second : from.Second ; //setting datepicker value datepickerFrom.Value = new DateTime ( year , month , day , hour , minute , second ) ; }
Proper way for datepickers validaton in c # ? ( windows forms )
C_sharp : AKA why does this test fail ? <code> [ TestFixture ] public class Tests { [ Test ] public void InnerClassShouldBePublic ( ) { Assert.IsTrue ( typeof ( InnerClass ) .IsPublic ) ; } public class InnerClass { } }
Why are inner class not public when viewed in reflection ?
C_sharp : Why , when I turn INT value to bytes and to ASCII and back , I get another value ? Example : <code> var asciiStr = new string ( Encoding.ASCII.GetChars ( BitConverter.GetBytes ( 2000 ) ) ) ; var intVal = BitConverter.ToInt32 ( Encoding.ASCII.GetBytes ( asciiStr ) , 0 ) ; Console.WriteLine ( intVal ) ; // Result : 1855
Why do I get a different value after turning an integer into ASCII and then back to an integer ?
C_sharp : I 'm writing code that calls the following method that exists in Windows.Networking.PushNotificationsI want to be sure to cover all cases where exceptions can be thrown and deal with each appropriately . Is it possible for me to get a list of the different types of exceptions this can throw and different circumstances which could cause them ? I do n't want to just have a catch-all This MSDN article states that `` An exception is thrown if you attempt to register a WNS push notification channel when there is no data connection '' . However it does n't state what type of exception or if there are other cases when an exception can be thrown.How can I find out if there are other possible exception types ? <code> // Summary : // Creates objects that you use to retrieve push notification channels from// the Windows Push Notification Services ( WNS ) . These channels are bound to// an app or secondary tile . [ Threading ( ThreadingModel.MTA ) ] [ Version ( 100794368 ) ] public static class PushNotificationChannelManager { // Summary : // Creates an object , bound to the calling app , through which you retrieve a // push notification channel from Windows Push Notification Services ( WNS ) . // // Returns : // The object , bound to the calling app , that is used to request a PushNotificationChannel // from the Windows Push Notification Services ( WNS ) . [ Overload ( `` CreatePushNotificationChannelForApplicationAsync '' ) ] public static IAsyncOperation < PushNotificationChannel > CreatePushNotificationChannelForApplicationAsync ( ) ; } catch ( Exception ex ) { }
How can I find out what kind of exceptions can be thrown by a method ?
C_sharp : I would like to write custom SQL code for mysql and mssql ( perhaps more later ) .The Problem starts here . I would like to declare the connection via an interface or abstract-class before the if-statement . But it seems not possible , because the command-classes demand explicitly the specific SqlConnection or MySqlConnection.The problem get 's worse if you would like to execute a simple command like SELECT c1 form t1 where c2 = @ value . Because you have to do the same as above.Is there an API which serves a workflow like this : Problem : System.Data.Common.DbCommand is an abstract classSqlDbCommand ( MySqlDbCommand , etc . ) demand there specific connectionDbCommand.Properties does not support `` Add '' with two Parameters ( `` @ placeholer '' , value ) like the Properties of SqlDbCommandi do n't need/want a full blown ORM ; just an interface/abstraction-layer over the existing heterogeneous API <code> var dbSystem = `` mssql '' ; if ( `` mssql '' == dbSystem ) { var mssqlConn = new SqlConnection ( mssqlConnString ) ; new SqlCommand ( `` CREATE TABLE t1 ( c1 in NOT NULL PRIMARY KEY IDENTITY ( 1,1 ) , c2 int ) '' , mssqlConn ) .ExecuteNonQuery ( ) ; } else { var mysqlConn = new MySqlConnection ( mysqlConnString ) ; new SqlCommand ( `` CREATE TABLE t1 ( c1 in NOT NULL AUTO_INCREMENT PRIMARY KEY , c2 int ) '' , mssqlConn ) .ExecuteNonQuery ( ) ; } IDbConnection conn ; // initialized by SqlConnection or MySqlConnection , etc.IDbCommand cmd = new DbCommand ( `` SELECT c1 form t1 where c2 = @ value '' , conn ) ; cmd.Parameters.Add ( `` @ value '' , Type.Int ) ;
Abstractionlayer for Database-Access
C_sharp : Initializing a class like this : I am getting an InvalidCastException on one of the assignments . There are quite a lot of them and the exception occurs on the whole expression even if I run the debugger line-by-line . The exception does n't give any clue either what it 's trying to cast to what.Is there a way to debug each assignment individually ? I 've seen the debugger separately stops 3 times on expressions like foreach ( x in y ) so it seems a little strange it is n't doing that here , and detracts from the attraction of using this handy initialization syntax . Maybe there is a more fine-grained debug step I can use ? <code> var x = new Item ( ) { ID = ( int ) ... , Name = ( string ) ... , .. } ;
Is it possible to debug a struct/class initialization member by member ?
C_sharp : I 'm a bit puzzled here ... I have a test method which does a call to an async method and I changed the signature to async Task . Works.Now I read all over the web that support for async is required in unit tests and is now also in NUnit . But why is that so important ? I can write the test like this , using the Result property which will wait for Task completion : <code> [ TestMethod ] public async Task TestIt ( ) { bool result = await service.SomethingAsync ( ) ; Assert ( result ) ; } [ TestMethod ] public void TestIt ( ) { bool result = service.SomethingAsync ( ) .Result ; Assert ( result ) ; }
Why would one need `` async '' support for MS Unit Test if Task.Result can be used ?
C_sharp : Ok so I am trying to get all the Companies assigned to BOTH courses that exist in a course mapping table.The course mapping table has 2 FK CourseIDs , that point to two different courses in the same table.Each course has a bundle , and the companies are assigned to bundles.I am trying to select all the companies that are assigned to both bundles from both courses.I have been able to do this ( Edit : apparently not , because of the OR , can anyone fix this too ? ) using 3 different LINQ queries , but I am hoping there is a way to reduce it into one for both brevity and performance : <code> Bundle vegasBundle = ( from cm in db.VegasToPegasusCourseMaps join c in db.Courses on cm.VegasCourseID equals c.CourseID join b in db.Bundles on c.BundleID equals b.BundleID where cm.VPCMapID == CourseMapID select b ) .FirstOrDefault ( ) ; Bundle pegasusBundle = ( from cm in db.VegasToPegasusCourseMaps join c in db.Courses on cm.PegasusCourseID equals c.CourseID join b in db.Bundles on c.BundleID equals b.BundleID where cm.VPCMapID == CourseMapID select b ) .FirstOrDefault ( ) ; IQueryable < Company > companyAssigned = from cb in db.CompanyBundles join c in db.Companies on cb.CompanyID equals c.CompanyID where cb.BundleID == vegasBundle.BundleID || cb.BundleID == pegasusBundle.BundleID select c ; return companyAssigned.ToList ( ) ;
Can anyone reduce these 3 LINQ to SQL statements into one ?
C_sharp : I 'm reading Jon Skeet 's C # in Depth.On page 156 he has an example , Listing 5.13 `` Capturing multiple variable instantiations with multiple delegates '' .In the explanation after this listing , he says `` each of the delegate instances has captured a different variable in this case . `` I understand this well enough because I understand that each time you close over a variable the compiler generates IL that encapsulates it in a new class made specifically to allow that variable to be captured ( essentially making it a reference type so that the value it is referring to does n't get destroyed with the stack frame of the currently executing scope ) .But then he talks about what would have happened had we captured index directly instead of creating the counter variable - `` all the delegates would have shared the same variable '' .This I do n't understand . Is n't index in the same scope as counter ? Why would the compiler not also create a new instance of index for each delegate ? Note : I think I figured it out as I typed this question , but I will leave the question up here for posterity . I think the answer is that index is actually in a different scope as counter . Index is essentially declared `` outside '' the for loop ... it is the same variable every time.Taking a look at the IL generated for a for loop , it proves the variables are declared outside the loop ( length and i were variables declared in the for loop declaration ) .One thing I think the book might have done better regarding this subject is really explain what the compiler is doing , because all this `` magic '' makes sense if you understand that the compiler is wrapping the closed over variable in a new class.Please correct any misconceptions or misunderstandings I might have . Also , feel free to elaborate on and/or add to my explanation . <code> List < ThreadStart > list = new List < ThreadStart > ( ) ; for ( int index=0 ; index < 5 ; index++ ; ) { int counter = index*10 ; list.Add ( delegate { Console.WriteLine ( counter ) ; counter++ ; } ) ; } foreach ( ThreadStart t in list ) { t ( ) ; } list [ 0 ] ( ) ; list [ 0 ] ( ) ; list [ 0 ] ( ) ; list [ 1 ] ( ) ; .locals init ( [ 0 ] int32 length , [ 1 ] int32 i , [ 2 ] bool CS $ 4 $ 0000 ) IL_0000 : nopIL_0001 : ldc.i4.s 10IL_0003 : stloc.0IL_0004 : ldc.i4.0IL_0005 : stloc.1IL_0006 : br.s IL_001b// loop start ( head : IL_001b ) IL_0008 : nop IL_0009 : ldloca.s i IL_000b : call instance string [ mscorlib ] System.Int32 : :ToString ( ) IL_0010 : call void [ mscorlib ] System.Console : :WriteLine ( string ) IL_0015 : nop IL_0016 : nop IL_0017 : ldloc.1 IL_0018 : ldc.i4.1 IL_0019 : add IL_001a : stloc.1 IL_001b : ldloc.1 IL_001c : ldloc.0 IL_001d : clt IL_001f : stloc.2 IL_0020 : ldloc.2 IL_0021 : brtrue.s IL_0008// end loop
In closure , what triggers a new instance of the captured variable ?
C_sharp : So , I am writing this school project that should be some basic chat program that consists of a client and a server . I am trying to handle either the server or the client programs being closed.So when you press the big red X in the Client window , this is what happens : It sends a message to the server informing it that someone is logging out , so it can remove the user from the user list , etc.The problem occurs when the server is being closed , and it tries to send a message to the clients informing them that the server has shut down , so the clients can inform the users and then close.So the server 's message arrives , and the client program is about to close , but the code above will try to inform the server falsely about the logout , but the server is already down by this time , so there will be a whole lot of error messages.I guess I would need some kind of an 'if ' statement in the procedure above which could decide whether the code should run , but I have no idea what it should be . Ideas ? <code> private void Window_Closing ( object sender , CancelEventArgs e ) { Data msgToSend = new Data ( ) ; msgToSend.cmdCommand = Command.Logout ; msgToSend.strName = LoginName ; byte [ ] b = msgToSend.ToByte ( ) ; ClientSocket.Send ( b ) ; }
C # Socket programming , closing windows
C_sharp : I was trying to understand the answer for this question Why am I getting wrong results when calling Func < int > ? I wrote some sample code . The following code produces After reading the explanation by Jon Skeet and Eric Lippert I thought I will get Here both v and i are loop variables , while the value of i is picked up at that instant v is not why is this ? . I do n't understand the behavior . <code> public static void Main ( string [ ] args ) { var funcs = new List < Func < string > > ( ) ; for ( int v=0 , i=0 ; v < 3 ; v++ , i++ ) { funcs.Add ( new Func < string > ( delegate ( ) { return `` Hello `` + i++ + '' `` +v ; } ) ) ; } foreach ( var f in funcs ) Console.WriteLine ( f ( ) ) ; } Hello 3 3Hello 4 3Hello 5 3 Hello 3 3Hello 3 3Hello 3 3
why this C # program outputs such a result ? How do I understand closure ?
C_sharp : I want to make a list of pointers to locations that contains a certain value in the process memory of another process . The value can be a short , int , long , string , bool or something else . My idea is to use Generics for this . I have one problem with making it , how can I tell the compiler to what type he needs to convert the byte array ? This is what I made : How can I tell the compiler that he needs to convert the byte [ ] to type T ? <code> public List < IntPtr > ScanProccessFor < T > ( T ItemToScanFor ) { List < IntPtr > Output = new List < IntPtr > ( ) ; IntPtr StartOffset = SelectedProcess.MainModule.BaseAddress ; int ScanSize = SelectedProcess.MainModule.ModuleMemorySize ; for ( int i = 0 ; i < ScanSize ; i++ ) if ( ReadMemory ( SelectedProcess , StartOffset + i , ( UInt16 ) Marshal.SizeOf ( ItemToScanFor ) ) == ItemToScanFor ) Output.Insert ( Output.Count , StartOffset + i ) ; return Output ; }
Compare byte [ ] to T
C_sharp : I have a many-to-many relationship between tables of Games and Genres . During an analysis , i need to get items from Games that match specific criteria.The problem is , to check for this criteria , i need to analyse genres of this specific game . And linq wo n't let me do it.My request now looks like this : When I execute it , I receive SQL exception Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.Is there a workaround ? How can i perform such Select inside of Where ? EDIT : weights is a Dictionary < string , double > .EDIT : I was playing with lambdas , and found out a strange thing in their behaviour : this code wo n't work , throwing nvarchar to float conversion exception : but this one will work nicely : This leads me to conclusion that linq lambdas are not usual lambdas . What 's wrong with them , then ? What are their limitations ? What i can and what i ca n't do inside of them ? Why is it ok for me to place a .select call inside of lambda , but not my own call of getW ? RESOLVED . See the answer below . Long story short , C # ca n't into clojures unless explicitly told so . If anyone knows better answer , i am still confused . <code> var result = GDB.Games.Where ( ( g ) = > g.GamesToGenres.Select ( ( gtg ) = > ( weights.ContainsKey ( gtg.Genre.Name ) ? weights [ gtg.Genre.Name ] :0.0 ) ) .Sum ( ) > Threshhold ) .ToArray ( ) ; Func < string , double > getW = ( name ) = > 1 ; var t = GDB.Games.Where ( ( g ) = > g.GamesToGenres.Select ( ( gtg ) = > getW ( gtg.Genre.Name ) ) .Sum ( ) > Threshhold ) .ToArray ( ) ; var t = GDB.Games.Where ( ( g ) = > g.GamesToGenres.Select ( ( gtg ) = > 1 ) .Sum ( ) > Threshhold ) .ToArray ( ) ;
Nested .Select ( ) inside of .Where ( )
C_sharp : I have a struct that holds a single object field to make working with the object easier . I wanted to test the performance ( I expected some degradation ) , but I get very surprising results . The version with the struct actually is faster : Without box : 8.08 sWith box : 7.76 sHow is this possible ? Below is the complete test code to reproduce the results.EDIT : I 've changed the IsDouble and IsObject tests to have the same statements as the other test . I 've re-executed the application and the resulting times are exactly the same.EDIT2 : This code was tested using a Release build compiling at 32-bit without the debugger attached ; .NET 4.5 and Visual Studio 2012 . Compiling it against 64-bit gives drastically different results ; on my machine : Without box : 8.23 sWith box : 16.99 s <code> using System ; using System.Collections.Generic ; using System.Diagnostics ; using System.Linq ; using System.Runtime.CompilerServices ; using System.Text ; using System.Threading.Tasks ; namespace ConsoleApplication68 { partial class Program { private const int Iterations = 100000000 ; static void Main ( string [ ] args ) { // Force JIT compilation . TimeWithoutBox ( new MyObject ( ) ) ; TimeWithoutBox ( 7 ) ; TimeBox ( new MyObject ( ) ) ; TimeBox ( 7 ) ; // The tests . var withoutBox = new TimeSpan ( ) ; var box = new TimeSpan ( ) ; for ( int i = 0 ; i < 10 ; i++ ) { withoutBox += TimeWithoutBox ( new MyObject ( ) ) ; withoutBox += TimeWithoutBox ( 7 ) ; box += TimeBox ( new MyObject ( ) ) ; box += TimeBox ( 7 ) ; } Console.WriteLine ( `` Without box : `` + withoutBox ) ; Console.WriteLine ( `` With box : `` + box ) ; Console.ReadLine ( ) ; } private static TimeSpan TimeBox ( object value ) { var box = new MyBox ( value ) ; var stopwatch = Stopwatch.StartNew ( ) ; for ( int i = 0 ; i < Iterations ; i++ ) { TestBox ( box ) ; } return stopwatch.Elapsed ; } private static TimeSpan TimeWithoutBox ( object value ) { var stopwatch = Stopwatch.StartNew ( ) ; for ( int i = 0 ; i < Iterations ; i++ ) { TestWithoutBox ( value ) ; } return stopwatch.Elapsed ; } [ MethodImpl ( MethodImplOptions.NoInlining ) ] private static void TestBox ( MyBox box ) { if ( box.IsDouble ) TakeDouble ( ( double ) box.Value ) ; else if ( box.IsObject ) TakeObject ( ( MyObject ) box.Value ) ; } [ MethodImpl ( MethodImplOptions.NoInlining ) ] private static void TestWithoutBox ( object box ) { if ( box.GetType ( ) == typeof ( double ) ) TakeDouble ( ( double ) box ) ; else if ( box.GetType ( ) == typeof ( MyObject ) ) TakeObject ( ( MyObject ) box ) ; } [ MethodImpl ( MethodImplOptions.NoInlining ) ] private static void TakeDouble ( double value ) { // Empty method to force consuming the cast . } [ MethodImpl ( MethodImplOptions.NoInlining ) ] private static void TakeObject ( MyObject value ) { // Empty method to force consuming the cast . } } struct MyBox { private readonly object _value ; public object Value { get { return _value ; } } public MyBox ( object value ) { _value = value ; } public bool IsDouble { get { return _value.GetType ( ) == typeof ( double ) ; } } public bool IsObject { get { return _value.GetType ( ) == typeof ( MyObject ) ; } } } class MyObject { } }
How can a struct with a single object field be faster than a raw object ?
C_sharp : I 'm trying to create a string extension method with the following signature : I 'm getting a compiler error : Default parameter value for 'provider ' must be a compile-time constantCould n't find anything on google and my only work around is to do this : Anyone know how I can set the default value of IFormatProvider in the signature ? Is it even possible ? IFormatProvider is an interface so I 'm assuming that 's where the issue lies . <code> public static DateTime ? TryParseExact ( this string src , string format , IFormatProvider provider = DateTimeFormatInfo.CurrentInfo , DateTimeStyles style = DateTimeStyles.None ) { } public static DateTime ? TryParseExact ( this string src , string format , IFormatProvider provider = null , DateTimeStyles style = DateTimeStyles.None ) { if ( provider == null ) provider = DateTimeFormatInfo.CurrentInfo ; }
Provide compile-time constant for IFormatProvider
C_sharp : I have a line of code that is giving me an warning message ( CS0675 ) in VS2015 , but not in 2013 . Warning CS0675 Bitwise-or operator used on a sign-extended operand ; consider casting to a smaller unsigned type first . The compiler implicitly widened and sign-extended a variable , and then used the resulting value in a bitwise OR operation . This can result in unexpected behavior.Obviously what is happening is the enum and the short are being extended to an int , the or operator applied , and then the result assigned the result to the short.If I change the code to shortValue = shortValue | ( short ) anEnum ; I get a compiler error CS0266 . But the bitwise OR should be valid for shorts ( in both cases I believe ) . If I hover the mouse over the | it shows as an int operator , am I missing something or should I report this as a bug ? PS : I know I can eliminate the warning/error by using = instead of |= and casting the result to a short . <code> shortValue |= ( short ) anEnum ;
Bug in compiler or misunderstanding ? Or operator on shorts
C_sharp : I have a similar problem to the post Accessing a static property of a child in a parent method . The preferred answer hints that the design of the classes is faulty and more information is needed to discuss the problem . Here is the situation I want to discuss with you.I want to implement some unit aware datatypes like length , mass , current , ... There should be an implicit cast to create the instances from a given string . As example `` 1.5 m '' should give the same as `` 150 cm '' , or `` 20 in '' should be treated correctly . To be able to convert between different units , I need quantity specific conversion constants . My idea was to create an abstract base class with some static translation methods.Those should use class specific statically defined dictionary to do their job . So have a look at the example.I think this gives a rather intuitive usage and keeps the code compact and quite readable and extendable . But of course I ran into the same problems the referenced post describes.Now my question is : How can I avoid this problems by design ? <code> public class PhysicalQuantities { protected static Dictionary < string , double > myConvertableUnits ; public static double getConversionFactorToSI ( String baseUnit_in ) { return myConvertableUnits [ baseUnit_in ] ; } } public class Length : PhysicalQuantities { protected static Dictionary < string , double > myConvertableUnits = new Dictionary < string , double > ( ) { { `` in '' , 0.0254 } , { `` ft '' , 0.3048 } } ; } class Program { static void Main ( string [ ] args ) { Length.getConversionFactorToSI ( `` in '' ) ; } }
Accessing a static property of a child in a parent method - Design considerations
C_sharp : I 'm refactoring a number of classes in an application to use interfaces instead of base classes . Here 's the interfaces I created so far : ICarryable implemented by all Item objects IActable implemented by all Actor objectsIUseable implemented by some Item sub-classesIWieldable implemented by some Item sub-classesYou can see the major base-classes are still Item and Actor . These have a common interface in that they both are located on a Map , so they have a Location property . The Map should n't care whether the object is an Actor or an Item , so I want to create an interface for it . Here 's what the interface would look likeThat 's no problem , but I ca n't think of what to call this interface . IMappable comes to mind by seems a bit lame . Any ideas ? <code> public interface IUnnameable { event EventHandler < LocationChangedEventArgs > LocationChanged ; Location Location { get ; set ; } }
Need help choosing a name for an interface
C_sharp : Is there a difference betweenAND ? If so , what ? Are n't they both just pointers to methods ? <code> Object.Event += new System.EventHandler ( EventHandler ) ; Object.Event -= new System.EventHandler ( EventHandler ) ; Object.Event += EventHandler ; Object.Event -= EventHandler ;
Wiring EventHandlers
C_sharp : I have the following code that attempts to catch a null reference . It then throws an exception with a clearer reason for the error specified in the message property . What type of exception should it throw ? An IndexOutOfRangeException ? or a NullReferenceException ? or , should we have just let the exception run its course ? The reason we tend not to do this last option , is that the default NullReferenceException is light on detail and just states Object reference not set to an instance of an object.Which , to be honest , could quite well be the most unhelpful error message in C # . <code> var existing = this.GetByItemId ( entity.ItemId ) ; // int or longif ( existing == null ) { throw new IndexOutOfRangeException ( `` The specified item does not exist . `` ) ; } var price = existing.Price ; var existing = this.GetByItemId ( entity.ItemId ) ; if ( existing == null ) { throw new NullReferenceException ( `` The specified item does not exist . `` ) ; } var price = existing.Price ; var existing = this.GetByItemId ( entity.ItemId ) ; var price = existing.Price ; // NullReferenceException coming your way
IndexNotFoundException versus NullReferenceException
C_sharp : I 'm developing an app that connects with WCF service to load data . I added a Web Service Reference directly from Visual Studio , and runs very well.But , my problem now is this : I have to connect with different WCF services depending the user who login app.Exists any way to doing this by code ? ? I 'm using a Xamarin Forms Portable app.SOLVED : Finally , I change the url of the service by code : <code> service = new ServicioWebClient ( binding , new EndpointAddress ( `` http : //myurl/wsdl '' ) ) ;
Multiple WCF connections in Xamarin Forms
C_sharp : I have an MVC application with EF6 . Is there a way to automatically set all properties of a model to [ Required ] ? Some of our models are large with all required fields . Any way to save lines of code or make this cleaner ? Thanks <code> public class Employee { [ Required ] public string Name { get ; set ; } [ Required ] public string Address 1 { get ; set ; } [ Required ] public string Address 2 { get ; set ; } [ Required ] public int SSN { get ; set ; } [ Required ] public double PayRate { get ; set ; } [ Required ] public int PayType { get ; set ; } [ Required ] public string JobTitle { get ; set ; } [ Required ] public bool FullTime { get ; set ; } [ Required ] public string Sex { get ; set ; } [ Required ] public string Name { get ; set ; } [ Required ] public string Name { get ; set ; } }
MVC model require all fields
C_sharp : I know we can escape curly bracket in C # using { { and } } . But they do n't seem to work well if they are right after a format modifier ( like { 0 : F6 } ) . <code> string str ; // Prints `` { 3.14 } '' as expectedstr = string.Format ( `` { { { 0 } } } '' , 3.14 ) ; Console.WriteLine ( str ) ; // Expected `` { 3.140000 } '' , found `` { F6 } '' str = string.Format ( `` { { { 0 : F6 } } } '' , 3.14 ) ; Console.WriteLine ( str ) ;
C # escape curly bracket not working with format modifier ?
C_sharp : I 'm looking for a way to implement something like this : Of course , I could define a conditional compilation symbol by myself , but it is n't suitable.Is there any built-in constant ? The questions I found are rather old . Maybe , the things were changed to the best ? <code> # if CSHARP_COMPILER_IS_FOR_CSHARP_6_OR_HIGHER foo ? .Bar ( ) ; # else if ( foo ! = null ) { foo.Bar ( ) ; } # endif
Conditional compilation depending on compiler version
C_sharp : I have Kendo charts drawn on a page and I am posting their image data to an action to save this base64 encoded data to a ( SQL Server ) database . Here is the exportImage call in which I first split the base64 data from the dataURL : My Export_TargetPrice method is essentially just a call to Convert.FromBase64String and then writing to the database : I am using base64decode.org to see if I can successfully decode the base64 from the database data ( also use freeformatter.com ) . It is often failing , but with no discernible reason or pattern . It is failing for one company but if I try tomorrow it will probably work.Earlier I generated 10 charts ( there are 50 on a page and I can generate whichever ones I need ) , and half of them failed . They are the same charts - same design , from a partial - with only the data differing.In the browser I can copy the received base64 variable/data and successfully create a chart from it via freeformatter.com but the database data can fail.Why is this process failing ? ( Why does it only fail some of the time ? ) I also tried the following to no effect : checking for a FormatException ( if the data is not a multiple of 4 ) , then actually trying to make it a multiple of 4 by padding equal signs.I also checked that the base64 data received does not contain any unexpected characters . <code> chart.exportImage ( { width : 727 , height : 262 } ) .done ( function ( data ) { // split 'image/png , xxxyyy= ' into two var dataParts = data.split ( ' , ' , 2 ) ; // TODO : need to strip from 'data : image/png ; base64 ' dataParts [ 0 ] = 'image/png ' ; $ .ajax ( { url : `` @ Url.Action ( `` Export_TargetPrice `` , `` Charts `` ) '' , type : 'POST ' , data : { contentType : dataParts [ 0 ] , base64 : dataParts [ 1 ] , companyID : companyId } } ) .done ( function ( ) { } ) ; } ) ; /// < summary > /// Export TargetPrice chart image for company ( without download ) ./// < /summary > [ HttpPost ] public ActionResult Export_TargetPrice ( string contentType , string base64 , int companyID ) { var fileContents = Convert.FromBase64String ( base64 ) ; ChartTargetPriceImage chartImage = new ChartTargetPriceImage { CompanyID = companyID , Data = fileContents , Extension = contentType , CreateDate = DateTime.Now } ; db.ChartTargetPriceImage.Add ( chartImage ) ; db.SaveChanges ( ) ; return new HttpStatusCodeResult ( HttpStatusCode.OK ) ; // 200 } byte [ ] fileContents ; // check if multiple of 4int overFour = base64.Replace ( `` `` , `` '' ) .Length % 4 ; if ( overFour > 0 ) { // add trailing padding '= ' base64 += new string ( '= ' , 4 - overFour ) ; } try { fileContents = Convert.FromBase64String ( base64 ) ; } catch ( FormatException ex ) { return new HttpStatusCodeResult ( HttpStatusCode.ExpectationFailed , base64.Length.ToString ( ) ) ; }
FromBase64String fails with Kendo charts
C_sharp : I came across this code in which a variable is assigned to itself for no good reason.It is not making much sense to me . Is there a reason behind this ? <code> double x = x = ( a - b ) / ( c - 1 ) ;
What is the purpose of this : `` double x = x = ( a - b ) / ( c - 1 ) ; ''
C_sharp : I wonder if there is a way of writing a method or a class that would add to any method some code that is shared between many methods . The methods return different things and some of them are just void.Below is a part of the code that is duplicated in the methods.Any help would be greatly appreciated.Nix solution applied to the code above <code> StartTimer ( MethodBase.GetCurrentMethod ( ) .Name ) ; try { // Actual method body } catch ( Exception ex ) { bool rethrow = ExceptionPolicy.HandleException ( ex , `` DALPolicy '' ) ; if ( rethrow ) { throw ; } } finally { StopTimer ( MethodBase.GetCurrentMethod ( ) .Name ) ; } public T WrapMethod < T > ( Func < T > func ) { StartTimer ( func.Method.Name ) ; try { return func ( ) ; } catch ( Exception ex ) { bool rethrow = ExceptionPolicy.HandleException ( ex , `` DALPolicy '' ) ; if ( rethrow ) { throw ; } } finally { StopTimer ( func.Method.Name ) ; } return default ( T ) ; }
Is there a way of using one method to handle others to avoid code duplication ?
C_sharp : I have the controller method GetLayer2 ( ) . It is extremely similar to GetLayer0 ( ) and GetLayer1 ( ) The code can be summed up as : Get the OrgCodeGet and parse the datePassedIn to the processDateUrlDecode the driverIdExecute a stored proc , putting the output in resultsConvert results to Json ( This was added to aid in troubleshooting ) return the converted resultsOriginally it was return Json ( results ) ; When debugging the jr value has the correct Value resultsWhen viewed in the browser ( Chrome ) in the network tab , I get the correct count of objects , but they are all empty.How do I get my results ? Edit - added class definition . Although these are EF classes , they are being filled by stored procedures . <code> [ HttpGet ] public async Task < JsonResult > GetLayer2 ( string datePassedIn , string eventType , string driverId ) { string orgCode = `` HVO '' ; //User.Identity.GetOrgCode ( ) ; DateTime ? processDate ; DateTime defaultDate = DateTime.Today.AddDays ( -1 ) ; //default yesterday if ( String.IsNullOrEmpty ( datePassedIn ) ) { _logger.LogError ( String.Format ( `` Date passed in was NULL or empty . Using default date { 0 } '' , defaultDate.ToString ( inputDateFormat ) ) , null ) ; processDate = defaultDate ; } else { try { processDate = DateTime.ParseExact ( datePassedIn , inputDateFormat , cultureProvider ) ; } catch ( FormatException ex ) { _logger.LogError ( ex , `` Error formatting date { datePassedIn } did not match { inputDateFormat } . using default date { defaultDate } '' , null ) ; processDate = defaultDate ; } } driverId = HttpUtility.UrlDecode ( driverId ) ; IEnumerable < EventTypeLayer2 > results = await _context.EventTypeLayer2Results .FromSql ( $ '' usp_dd_EventType_2 @ p0 , @ p1 , @ p2 , @ p3 '' , orgCode , processDate , eventType , driverId ) .ToListAsync ( ) ; JsonResult jr = Json ( results ) ; return jr ; } [ DataContract ] public class EventTypeLayer2 { [ IgnoreDataMember ] [ Key ] public Int64 RowId { get ; set ; } [ Column ( TypeName = `` varchar ( 50 ) '' ) ] public string EventTypeDisplay { get ; set ; } [ Column ( TypeName = `` varchar ( 50 ) '' ) ] public string EventTypeId { get ; set ; } [ Column ( TypeName = `` varchar ( 20 ) '' ) ] public string Colour { get ; set ; } [ Required ] public int Value { get ; set ; } [ Column ( TypeName = `` varchar ( 100 ) '' ) ] public string DriverId { get ; set ; } public int NodeId { get ; set ; } [ DataType ( DataType.DateTime ) ] public DateTime StartTime { get ; set ; } [ DataType ( DataType.DateTime ) ] public DateTime EndTime { get ; set ; } public int FirstLogId { get ; set ; } public int LastLogId { get ; set ; } public int MinSpeed { get ; set ; } public int MaxSpeed { get ; set ; } public int AvgSpeed { get ; set ; } public int CalcSummOdo { get ; set ; } }
MVC JsonResult has data , but browser has none
C_sharp : In .Net , is there a way to convert , say , ' 2:45 ' to the decimal 2.75 ? ex : It should throw an exception if invalid data , ex , minutes < 0 < 60 or not in the h : m format.Thanks <code> decimal d = TimeToDecimal ( `` 2:45 '' ) ; Console.WriteLine ( d ) ; //output is 2.75
Parse time string to decimal ?
C_sharp : These two statements look the same logically to me , but they 're resulting in different SQL being generated : Example # 1 does n't work , but example # 2 does.The generated SQL for the var people query is identical for both , but the SQL in the final query differs like this : Why is there this difference ? Edit : Up until now all I 've done to get the SQL generated is to inspect the queryable in the debugger . However , after setting up a logger as Jon suggested , it seems that the real sql executed is different . <code> # 1 var people = _DB.People.Where ( p = > p.Status == MyPersonEnum.STUDENT.ToString ( ) ) ; var ids = people.Select ( p = > p.Id ) ; var cars = _DB.Cars.Where ( c = > ids.Contains ( c.PersonId ) ) ; # 2 string s = MyPersonEnum.STUDENT.ToString ( ) ; var people = _DB.People.Where ( p = > p.Status == s ) ; var ids = people.Select ( p = > p.Id ) ; var cars = _DB.Cars.Where ( c = > ids.Contains ( c.PersonId ) ) ; # 1SELECT [ t0 ] . [ PersonId ] , [ t0 ] . [ etc ] ... ..FROM [ Cars ] AS [ t0 ] WHERE EXISTS ( SELECT NULL AS [ EMPTY ] FROM [ People ] AS [ t1 ] WHERE ( [ t1 ] . [ Id ] = [ t0 ] . [ PersonId ] ) AND ( [ t1 ] . [ Status ] = ( CONVERT ( NVarChar , @ p0 ) ) ) ) # 2SELECT [ t0 ] . [ PersonId ] , [ t0 ] . [ etc ] ... ..FROM [ Cars ] AS [ t0 ] WHERE EXISTS ( SELECT NULL AS [ EMPTY ] FROM [ People ] AS [ t1 ] WHERE ( [ t1 ] . [ Id ] = [ t0 ] . [ PersonId ] ) AND ( [ t1 ] . [ Status ] = @ p0 ) ) # 1 SELECT [ t1 ] . [ Id ] , [ t1 ] .etc ... [ t0 ] .Id , [ t1 ] .etc ... FROM [ Cars ] AS [ t0 ] , [ People ] AS [ t1 ] WHERE ( [ t1 ] . [ Id ] = [ t0 ] . [ PersonId ] ) AND ( EXISTS ( SELECT NULL AS [ EMPTY ] FROM [ People ] AS [ t2 ] WHERE ( [ t2 ] . [ Id ] = [ t0 ] . [ PersonId ] ) AND ( [ t2 ] . [ Status ] = ( CONVERT ( NVarChar , @ p0 ) ) ) ) ) AND ( [ t1 ] . [ Status ] = @ p1 ) -- @ p0 : Input Int ( Size = 0 ; Prec = 0 ; Scale = 0 ) [ 2 ] -- @ p1 : Input NVarChar ( Size = 7 ; Prec = 0 ; Scale = 0 ) [ STUDENT ] # 2SELECT [ t1 ] . [ Id ] , [ t1 ] .etc ... [ t0 ] .Id , [ t1 ] .etc ... FROM [ Cars ] AS [ t0 ] , [ People ] AS [ t1 ] WHERE ( [ t1 ] . [ Id ] = [ t0 ] . [ PersonId ] ) AND ( EXISTS ( SELECT NULL AS [ EMPTY ] FROM [ People ] AS [ t2 ] WHERE ( [ t2 ] . [ Id ] = [ t0 ] . [ PersonId ] ) AND ( [ t2 ] . [ Status ] = @ p0 ) ) ) AND ( [ t1 ] . [ Status ] = @ p1 ) -- @ p0 : Input NVarChar ( Size = 7 ; Prec = 0 ; Scale = 0 ) [ STUDENT ] -- @ p1 : Input NVarChar ( Size = 7 ; Prec = 0 ; Scale = 0 ) [ STUDENT ]
What 's the difference between these two LINQtoSQL statements ?
C_sharp : I 'm interpreting an exception report from a C # Windows Phone app . A method throws a NullReferenceException . The method goes : It 's consistent with m_Field being null - there 's simply nothing else there that can possibly be null . But here 's the mysterious part.The GetILOffset ( ) from the StackFrame from the StackTrace for the exception object returns 0x13 . The MSIL for the method , as shown by ILDASM , goes : Here 's what I do n't understand . If the offset is indeed 0x13 , that means the ldarg line causes the exception . But the command is documented as not throwing any exceptions . It 's callvirt that should throw , is n't it ? Or is the offset relative to something other than the method beginning ? ldfld can also throw , but only if the this object is null ; that 's not possible in C # AFAIK.The docs mention that debug info might get in the way of the offset , but it 's a release build.The DLL that I 'm examining with ILDASM is exactly the one that I 've shipped to the Windows Phone Store as a part of my XAP . <code> public void OnDelete ( object o , EventArgs a ) { if ( MessageBox.Show ( Res.IDS_AREYOUSURE , Res.IDS_APPTITLE , MessageBoxButton.OKCancel ) == MessageBoxResult.OK ) m_Field.RequestDelete ( ) ; } IL_0000 : call string App.Res : :get_IDS_AREYOUSURE ( ) IL_0005 : call string App.Res : :get_IDS_APPTITLE ( ) IL_000a : ldc.i4.1IL_000b : call valuetype ( ... ) System.Windows.MessageBox : :Show ( ... ) IL_0010 : ldc.i4.1IL_0011 : bne.un.s IL_001eIL_0013 : ldarg.0IL_0014 : ldfld class App.Class2 App.Class1 : :m_FieldIL_0019 : callvirt instance void App.Class2 : :RequestDelete ( ) IL_001e : ret
NullReferenceException vs. MSIL
C_sharp : Trying to follow the hints laid out here , but she does n't mention how to handle it when your collection needs to return a value , like so : This obviously wo n't work , because dispatcher.BeginInvoke does n't return anything . What am I supposed to do ? <code> private delegate TValue DequeueDelegate ( ) ; public virtual TValue Dequeue ( ) { if ( dispatcher.CheckAccess ( ) ) { -- count ; var pair = dict.First ( ) ; var queue = pair.Value ; var val = queue.Dequeue ( ) ; if ( queue.Count == 0 ) dict.Remove ( pair.Key ) ; OnCollectionChanged ( new NotifyCollectionChangedEventArgs ( NotifyCollectionChangedAction.Remove , val ) ) ; return val ; } else { dispatcher.BeginInvoke ( new DequeueDelegate ( Dequeue ) ) ; } }
Returning objects from another thread ?
C_sharp : Can we make a property of a class visible to public , but can only be modified by some specific classes ? for example , Child is a data class , Parent is a class that can modify data , Cat is a class that can only read data.Is there any way to implement such access control using Property in C # ? <code> // this is the property holderpublic class Child { public bool IsBeaten { get ; set ; } } // this is the modifier which can set the property of Child instancepublic class Father { public void BeatChild ( Child c ) { c.IsBeaten = true ; // should be no exception } } // this is the observer which can get the property but can not set.public class Cat { // I want this method always return false . public bool TryBeatChild ( Child c ) { try { c.IsBeaten = true ; return true ; } catch ( Exception ) { return false ; } } // shoud be ok public void WatchChild ( Child c ) { if ( c.IsBeaten ) { this.Laugh ( ) ; } } private void Laugh ( ) { } }
how to implement selective property-visibility in c # ?
C_sharp : Suppose I want to write an extension method to dump some data from a T [ , ] to a CSV : which I could call withbut suppose myData is a Complex [ , ] and I want to write the magnitude of the complex number , not the full value . It would be handy if I could write : but I 'm not sure how to implement that in the extension method or if it 's even possible . <code> public static void WriteCSVData < T > ( this T [ , ] data , StreamWriter sw ) { for ( int row = 0 ; row < data.GetLength ( 0 ) ; row++ ) for ( int col = 0 ; col < data.GetLength ( 1 ) ; col++ ) { string s = data [ row , col ] .ToString ( ) ; if ( s.Contains ( `` , '' ) ) sw.Write ( `` \ '' '' + s + `` \ '' '' ) ; else sw.Write ( s ) ; if ( col < data.GetLength ( 1 ) - 1 ) sw.Write ( `` , '' ) ; else sw.WriteLine ( ) ; } } using ( StreamWriter sw = new StreamWriter ( `` data.csv '' ) ) myData.WriteCSVData ( sw ) ; using ( StreamWriter sw = new StreamWriter ( `` data.csv '' ) ) myData.WriteCSVData ( sw , d = > d.Magnitude ) ;
Lambda in C # extension method
C_sharp : How is the below code is printing true ? I expected this to print False , because I expected two separate objects to be constructed and then their references compared . <code> string x = new string ( new char [ 0 ] ) ; string y = new string ( new char [ 0 ] ) ; Console.WriteLine ( object.ReferenceEquals ( x , y ) ) ;
Object.ReferenceEquals prints true for two different objects
C_sharp : I 'd like to know how best to program three different editions of my C # ASP.NET 3.5 application in VS2008 Professional ( which includes a web deployment project ) .I have a Light , Pro and Ultimate edition ( or version ) of my application.At the moment I 've put all in one solution with three build versions in configuration manager and I use preprocessor directives all over the code ( there are around 20 such constructs in some ten thousand lines of code , so it 's overseeable ) : I 've read in stackoverflow for hours and thought to encounter how e.g . Microsoft does this with its different Windows editions , but did not find what I expected.Somewhere there is a heavy discussion about if preprocessor directives are evil.What I like with those # if-directives is : the side-by-side code of differences , so I will understand the code for thedifferent editions after six monthsand the special benefit to NOT giveout compiled code of other versionsto the customer.OK , long explication , repeated question : What 's the best way to go ? <code> # if light//light code # endif # if pro//pro code # endif //etc ...
How to program three editions Light , Pro , Ultimate in one solution
C_sharp : After migrating to ASP.NET Core 2.1 we have realized that some consumers of our API are sending GET requests with the Content-Type header set to application/json . Sadly , these requests have not been rejected in the past ( even though they should have ) , nevertheless this still is a breaking change..Since our consumers need to fix this issue on their end , and this will take some time , we would like to temporarily accept these requests so we 're not stuck waiting for this.The framework ( correctly ) rejects the request with the following error message : `` A non-empty request body is required . `` The action looks like this : The code inside the action is n't being reached as the error is already been thrown before it reaches the action ( due to the incorrect request ) . @ Nkosi 's solution resulted in the same response : The ( PHP ) cURL that the consumer uses is this : Removing the `` Content-Type : application/json '' , line turns the request into a valid requests , so we 're 99.9 % sure that the addition of this header is the evildoer . <code> [ Route ( `` api/file/ { id : guid } '' ) ] public async Task < IActionResult > Get ( Guid id ) { // Some simple code here } [ HttpGet ( `` api/file/ { id : guid } '' ) ] public async Task < IActionResult > Get ( [ FromRoute ] Guid id ) { // Some simple code here } $ ch = curl_init ( self : :API_URL . `` /file/ '' . $ id ) ; curl_setopt ( $ ch , CURLOPT_RETURNTRANSFER , 1 ) ; curl_setopt ( $ ch , CURLOPT_FRESH_CONNECT , 1 ) ; curl_setopt ( $ ch , CURLOPT_HTTPHEADER , array ( `` Content-Type : application/json '' , `` Application : APPKey `` . $ this- > AppKey , `` Authorization : APIKey `` . $ this- > ApiKey ) ) ;
How to accept a bodyless GET request with JSON as it 's content type ?
C_sharp : Considering the following : It is clear that you would say BudgetView extends ViewBase , and it implements IView , but what does it to to poor old Export ? Perhaps BudgetView uses Export ? Or BudgetView applies Export ? I need this for my documentation . I 'm need to be very formal and very detailed.Edit : My UML tool is very restrictive about what I can and can not do . I can not make custom stereotypes for instance . <code> [ Export ] public class BudgetView : ViewBase , IView { // Members Galore }
What verb would describe the relationship between a C # class and its Attribute ?
C_sharp : If I have a model with a key of type Guid , is it bad practise to set the ID explicitly in the constructor ? I know it will be set implicitly by Entity Framework , but will anything bad happen ( perhaps performance wise ) from setting it explicitly ? Example : I 'm thinking a Guid is backed up by a sequential ID in SQL server , and if I set a value explicitly , I suppose I will decrease indexing performance because it will no longer be sequential ? I have not been able to find an answer on this and I am highly curious about it . <code> class MyModel { public MyModel ( ) { Id = Guid.NewGuid ( ) ; } [ Key ] public Guid Id { get ; set ; } }
Is instantiating a GUID in Entity Framework Core bad practice ?
C_sharp : I need to create a Type instance for an array of a base type with a specified number of indexes . Essentially I need to method like the following that I can call ... So that calling the function would give the following result ... The only solution I can come up with is the following ... This does work but having to create an instance of the required type in order to then call GetType ( ) does not seem ideal . There must be a way to generate the Type without creating an instance . Or is there ? <code> public Type GetArrayOfType ( Type baseType , int numOfIndexes ) { return /* magic does here */ } GetTypeArray ( typeof ( bool ) , 1 ) == typeof ( bool [ ] ) GetTypeArray ( typeof ( bool ) , 2 ) == typeof ( bool [ , ] ) GetTypeArray ( typeof ( bool ) , 3 ) == typeof ( bool [ , , ] ) public Type GetArrayOfType ( Type baseType , int numOfIndexes ) { List < int > indexes = new List < int > ( ) ; for ( int i=0 ; i < numOfIndexes ; i++ ) indexes.Add ( 1 ) ; return Array.CreateInstance ( baseType , indexes.ToArray ( ) ) .GetType ( ) ; }
How to get the Type that describes an array of a base type ?
C_sharp : I need to distribute a set of data evenly over time based on historical data such that each digit appears an equal ( or close to equal ) number of times in each position over time . The problem is , given a list of orderings used in the past , that look like this ( but could have any number of elements ) : how can I find an ordering of the values that is the least used and will lead to a `` more balanced '' set of orderings . The obvious answer is I could group by and count them and pick the least used one , but the problem is the least used permutation may not have ever been used , for example here , the ordering `` 1,2,3,4,5 '' is a candidate for least used because it does n't appear at all . The simple answer seems to be to identify which position `` 1 '' appears in the least frequent and set that position to `` 1 '' and so on for each digit . I suspect that works , but I feel like there 's a more elegant solution that I have n't considered potentially with cross joins so that all possible combinations are included.any ideas ? <code> 1,2,5,3,44,1,5,2,31,3,5,2,44,1,2,3,52,4,1,3,55,1,4,3,21,5,3,2,45,1,3,2,43,2,5,4,14,3,1,5,2
Finding the least-used permutation
C_sharp : I have a code like this : We can notice some boring repetition in the code.So , it would be nice to write a generic method Update in a way we can afford ourselves to write something like this : Tell me , please , is it possible to write such a method ? Which book can I learn that from ? ( I have found only one close example : http : //msdn.microsoft.com/en-us/library/cc981895.aspx , but it is not clear enough how to derive my Update method from that ) Thank you.UPD.Ok , Jon Skeet tells there 's something wrong in the question , and I agree , that my calls should look different , I think these calls are possible : <code> class PacketDAO { // ... public void UpdatePacketStatus ( Guid packetID , Status status ) { using ( var ctx = new DataContext ( ) ) { var packet = ctx.Packet.SingleOrDefault ( p = > p.PacketID == packetID ) ; packet.Status = status ; ctx.SubmitChanges ( ) ; } } public void UpdatePacketTime ( Guid packetID , DateTime ? time ) { using ( var ctx = new DataContext ( ) ) { var packet = ctx.Packet.SingleOrDefault ( p = > p.PacketID == packetID ) ; packet.Time = time ; ctx.SubmitChanges ( ) ; } } // ... } packet.Update < Guid , Packet > ( guid , p = > p.Time = DateTime.Now ) ; packet.Update < Guid , Packet > ( guid , p = > p.Status = Status.Ok ) ; packet.Update < Packet > ( p = > p.packetID == guid , p = > p.Time = DateTime.Now ) ; packet.Update < Packet > ( p = > p.packetID == guid , p = > p.Status = Status.Ok ) ;
How to define my own LINQ construct in C # ?
C_sharp : suppose I have : processing may take a long time and while it was in the middle another packet has arrived . What happens next : the processing gets done and then another event is fired or perhaps new event is fired immediately but on a new thread ? <code> ethernet_adapter.PacketArrived += ( s , e ) = > { //long processing ... } ;
events and threading
C_sharp : As I am developing my small game , I have made a lot of progress yet frustrated about a lot of things . The latest thing was creating a list of required items and for you to understand that I will provide you with both Explanation as well as Code which I created but obviously does n't work ... I - ExplanationIn order for the player to build a building he must have done some required researches with each research requires more researches for it to be researched ... It is like a tree of researches that the player will go through them by exploring the game and doing some tasks ... So to imagine it more accurately you can look at my small code hereII - CodeSo from the last snippet of code [ which is just to explain ] the player want to research the Steam that for instance needs 3 more researches in order to be researched ... one of which the Iron also needs 1 more research to be researched and so on [ maybe less maybe more or maybe no requirements at all ] ... Concluding that the Question is : How could I create such nesting so that when a player tries to do a research the system quickly looks at the researches he have done and the research he wants to do [ including it 's nested ones ] and If the player did not meet the requirements it just returns a tree with what things he want 's to achieve ? After all , I just want to thank you in advance and I am waiting for your very valuable support ... <code> //Available Main Elements var carbon = new Element { Name = `` Carbon '' } ; var hydrogen = new Element { Name = `` Hydrogen '' } ; var oxygen = new Element { Name = `` Oxygen '' } ; var nitrogen = new Element { Name = `` Nitrogen '' } ; //Example Researchvar steam = new Research ( name : `` Steam '' , requiredElements : null , requiredResearches : /*Fire*/ & /*Water*/ & /*Iron*/ ) ;
Creating a tree of required items
C_sharp : I have function like this : Everything is good , except that it complains about return null ; part Can not convert expression type 'null ' to type 'T'How do I return null from function like this ? <code> private T DeserializeStream < T > ( Stream data ) where T : IExtensible { try { var returnObject = Serializer.Deserialize < T > ( data ) ; return returnObject ; } catch ( Exception ex ) { this.LoggerService.Log ( this.AccountId , ex ) ; } return null ; }
How do I return null from generic function ?
C_sharp : I have a simple ViewComponent works correctly in the browser chrome and Firefox but do not work in a browser Edge \ IE 11.The component shows the time ( just for example ) .Chrome and firefox time is displayed.Edge Browser \ IE 11 , time is displayed only the first time the page is up and remains so , time is `` frozen '' .butWhen I open the browser Edge development tools as well as in IE 11 , the component starts to work properly and current time is displayed ( just like other browsers ) And when I close the F12 development tools , component stops working ( time `` frozen '' ) .And it repeated - F12 open the component works , F12 Close component stops working.Am I missing something here ? Attaching the simple code of the processThank youHomeController : GetTimeViewComponent : Default : <code> public IActionResult GetTime ( ) { return ViewComponent ( `` GetTime '' ) ; //// var time = DateTime.Now.ToString ( `` h : mm : ss '' ) ; //// return Content ( $ '' The current time is { time } '' ) ; } public class GetTimeViewComponent : ViewComponent { public IViewComponentResult Invoke ( ) { var model = new string [ ] { `` Hello '' , DateTime.Now.ToString ( `` h : mm : ss '' ) , `` the '' , `` view '' , `` component . '' } ; return View ( `` Default '' , model ) ; } } @ model string [ ] < ul > @ foreach ( var item in Model ) { < li class= '' text-danger '' > @ item < /li > } < /ul > **Index** < div id= '' myComponentContainer '' > @ await Component.InvokeAsync ( `` GetTime '' ) < /div > **Js / Ajax** $ ( function ( ) { var refreshComponent = function ( ) { $ .get ( `` Home/GetTime '' , function ( data ) { $ ( `` # myComponentContainer '' ) .html ( data ) ; } ) ; } ; $ ( function ( ) { window.setInterval ( refreshComponent , 1000 ) ; } ) ; } ) ;
Rendering ViewComponent with ajax do n't work in Edge/IE11
C_sharp : I am using .net core 3.1 . With the help of docker I uploaded my code to heroku . but when i make a web request I get a 405 error with all my endpoints . ( I cant see more details of the error ) using Get : from visual studio code and also locally from my IIS everything works fine . but the problem occurs when I deploy to my server.What am I doing wrong ? this is the code of my controller : update : this is my DockerfileAt no time have I seen CORS issues or anything like that . just the 405 error . <code> http : //xxxx.herokuapp.com/api/pqrs/test/1315315 using System ; using System.Collections.Generic ; using System.IdentityModel.Tokens.Jwt ; using System.Linq ; using System.Security.Claims ; using System.Text ; using System.Threading.Tasks ; using apiPQR.Contexts ; using apiPQR.Entities ; using apiPQR.Models ; using Microsoft.AspNetCore.Authentication.JwtBearer ; using Microsoft.AspNetCore.Authorization ; using Microsoft.AspNetCore.Mvc ; using Microsoft.Extensions.Configuration ; using Microsoft.IdentityModel.Tokens ; namespace apiPQR.Controllers { [ ApiController ] [ Route ( `` api/ [ controller ] '' ) ] public class Pqrs : Controller { private readonly AppDbContext context ; private readonly IConfiguration configuration ; public Pqrs ( AppDbContext context , IConfiguration configuration ) { this.context = context ; this.configuration = configuration ; } [ HttpGet , Route ( `` test/ { id } '' ) ] public PQRS Get ( int id ) { var num_pqrs = context.PQRS.FirstOrDefault ( p = > p.num_solicitud==id ) ; return num_pqrs ; } } } # See https : //aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS baseWORKDIR /appEXPOSE 80EXPOSE 443FROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS buildWORKDIR /srcCOPY [ `` apiPQR.csproj '' , `` '' ] RUN dotnet restore `` ./apiPQR.csproj '' COPY . .WORKDIR `` /src/ . `` RUN dotnet build `` apiPQR.csproj '' -c Release -o /app/buildFROM build AS publishRUN dotnet publish `` apiPQR.csproj '' -c Release -o /app/publishFROM base AS finalWORKDIR /appCOPY -- from=publish /app/publish .ENTRYPOINT [ `` dotnet '' , `` apiPQR.dll '' ]
Deploy ASP.NET Core Docker project - get a 405 error ( locally in my IIS , web requests works ) . How to fix it ?
C_sharp : The best way I can describe what I 'm trying to do is `` Nested DistinctBy '' .Let 's say I have a collection of objects . Each object contains a collection of nicknames.I want to select all Persons but make sure nobody selected shares a nickname with another . Molly and Steve both share the nickname 'Lefty ' so I want to filter one of them out . Only the one with highest priority should be included . If there is a highest priority tie between 2 or more then just pick the first one of them . So in this example I would want an IEnumerable of all people except Steve.EDIT : Here 's another example using music album instead of person , might make more sense.The idea here is we want to show his discography but we want to skip quasi-duplicates . <code> class Person { public string Name { get ; set ; } public int Priority { get ; set ; } public string [ ] Nicknames { get ; set ; } } public class Program { public static void Main ( ) { var People = new List < Person > { new Person { Name = `` Steve '' , Priority = 4 , Nicknames = new string [ ] { `` Stevo '' , `` Lefty '' , `` Slim '' } } , new Person { Name = `` Karen '' , Priority = 6 , Nicknames = new string [ ] { `` Kary '' , `` Birdie '' , `` Snookie '' } } , new Person { Name = `` Molly '' , Priority = 3 , Nicknames = new string [ ] { `` Mol '' , `` Lefty '' , `` Dixie '' } } , new Person { Name = `` Greg '' , Priority = 5 , Nicknames = new string [ ] { `` G-man '' , `` Chubs '' , `` Skippy '' } } } ; } } class Album { string Name { get ; set ; } int Priority { get ; set ; } string [ ] Aliases { get ; set ; } { class Program { var NeilYoungAlbums = new List < Album > { new Person { Name = `` Harvest ( Remastered ) '' , Priority = 4 , Aliases = new string [ ] { `` Harvest ( 1972 ) '' , `` Harvest ( 2012 ) '' } } , new Person { Name = `` On The Beach '' , Priority = 6 , Aliases = new string [ ] { `` The Beach Album '' , `` On The Beach ( 1974 ) '' } } , new Person { Name = `` Harvest '' , Priority = 3 , Aliases = new string [ ] { `` Harvest ( 1972 ) '' } } , new Person { Name = `` Freedom '' , Priority = 5 , Aliases = new string [ ] { `` Freedom ( 1989 ) '' } } } ; }
How Can I Achieve this Using LINQ ?
C_sharp : I am working on some code which is something like this : Someclass contains the required constructor.The code for this compiles fine without any warning . But I get a code hazard in system : `` The Someclass ctor has been called from static constructor and/or static initialiser '' This code hazard part of system just to make it better by warning about possible flaws in the system or if system can get into bad state because of this . I read somewhere on the web that static constructor/initialiser can get into deadlock in c # if they wait for a thread to finish . Does that have something to do with this ? I need to get rid of this warning how can i do this.I ca n't make the member unstatic as it 's used by a static function.What should I do in this case , Need help . <code> class A { static SomeClass a = new Someclass ( `` asfae '' ) ; }
Static variable initialization using new gives a code hazard
C_sharp : This is a followup to this question : Why does a division result differ based on the cast type ? Quick Summary : The question is : Why are the results different depending on the cast type ? While working out an answer I ran into an issue I was n't able to explain.This outputs the following : Breaking it down in IEEE 754 format : Sign : Exponent : Mantissa : Decimal Representation : This results in exactly 80 . So why does casting the result make a difference ? <code> byte b1 = ( byte ) ( 64 / 0.8f ) ; // b1 is 79int b2 = ( int ) ( 64 / 0.8f ) ; // b2 is 79float fl = ( 64 / 0.8f ) ; // fl is 80 var bytes = BitConverter.GetBytes ( 64 / 0.8f ) .Reverse ( ) ; // Reverse endiannessvar bits = bytes.Select ( b = > Convert.ToString ( b , 2 ) .PadLeft ( 8 , ' 0 ' ) ) ; Console.WriteLine ( string.Join ( `` `` , bits ) ) ; 01000010 10100000 00000000 00000000 0 10000101 01000000000000000000000 0 = > Positive 10000101 = > 133 in base 10 01000000000000000000000 = > 0*2^-1 + 1*2^-2 + 0*2^-3 ... = 1/4 = 0.25 ( 1 + 0.25 ) * 2^ ( 133 - 127 ) ( Subtract single precision bias )
Why does a division result differ based on the cast type ? ( Followup )
C_sharp : I 'm working on a library that simplifies application configuration . Essentially , consumers of the library either decorate their configuration classes with attributes or they initialize the settings declaratively in code . It would be possible to specify 1 or more sources from which to read/write configuration properties ( Accessors ) or inherit a default from the class . For example , the following : would be equivalent toThe Accessors deal with reading & writing from various sources ( AppSettings , registry , .ini , etc. , etc. ) . I want to allow consumers to extend the capabilities to meet their needs . I 'd like to keep it IoC container agnostic . The Type [ ] constraint is given to me because I ca n't specify types in attributes due to compile-time vs. runtime issues.Is there a way to have a default mechanism for instantiating these ( e.g. , something based on Activator.CreateInstance ) but also allow the consuming code to instantiate these accessors at runtime without using the service locator/dependency resolver pattern ? I 've been reading a lot about why the service locator/dependency resolver pattern is an evil anti-pattern , but I ca n't figure out a better tool for the job . I see the MVC framework and SignalR libraries using dependency resolvers . Are they evil 100 % of the time or is this an edge case ? As far as I can tell , the abstract factory pattern wo n't cut it since it does n't like Type parameters.In this particular case , the attribute-based configuration will be more useful than the declarative approach , so I do n't want to abandon my Configuration attributes ( which would allow me to change Type to IConfigurationAccessor and switch to a factory approach ) . <code> [ ConfigurationNamespace ( DefaultAccessors = new Type [ ] { typeof ( AppSettingsAccessor ) } ) ] public class ClientConfiguration : Configuration < IClientConfiguration > { [ ConfigurationItem ( Accessors = new Type [ ] { typeof ( ( RegistryAccessor ) ) } ) ] public bool BypassCertificateVerification { get ; set ; } } var config = new Configuration < IClientConfiguration > ( ) ; config.SetDefaultAccessors ( new [ ] { typeof ( AppSettingsAccessor ) } ) ; config.SetPropertyAccessors ( property : x = > x.BypassCertificateVerification , accessors : new [ ] { typeof ( RegistryAccessor ) } ) ;
Best practices for DI in a library involving Types in attributes
C_sharp : I seem to be getting different results when filtering . I expect the same result from these two pieces of code : I am trying to find items which have the same name as my firstGuess.Method A works as expected , but B seems to give me a odd result in that ! matches2.any ( ) returns false , when I would expect true.Tested with both .Where and .SelectWhy do are these seemingly equivalent methods give me different results ? <code> Sitecore.Data.Items.Item firstGuess = Sitecore.Context.Database.GetItem ( mediaPath ) ; var matches = new List < Item > ( ) ; //Method Aforeach ( var child in firstGuess.Parent.Children.InnerChildren ) { if ( child.DisplayName == firstGuess.DisplayName ) { matches.Add ( child ) ; } } //Matches.count = 2//Method Bvar matches2 = firstGuess.Parent.Children.InnerChildren.Where ( i = > i.DisplayName == firstGuess.DisplayName ) ; //matches2.any = false
Why am I getting different results filtering with foreach vs LINQ .Where ( ) ?