text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
C_sharp : I have the below which calculates the running total for a customer account status , however he first value is always added to itself and I 'm not sure why - though I suspect I 've missed something obvious : Which outputs : Where the 309.60 of the first row should be simply 154.80 What have I done wrong ? EDIT : As per ahruss 's comment below , I was calling Any ( ) on the result in my View , causing the first to be evaluated twice - to resolve I appended ToList ( ) to my query.Thanks all for your suggestions <code> decimal ? runningTotal = 0 ; IEnumerable < StatementModel > statement = sage.Repository < FDSSLTransactionHistory > ( ) .Queryable ( ) .Where ( x = > x.CustomerAccountNumber == sageAccount ) .OrderBy ( x= > x.UniqueReferenceNumber ) .AsEnumerable ( ) .Select ( x = > new StatementModel ( ) { SLAccountId = x.CustomerAccountNumber , TransactionReference = x.TransactionReference , SecondReference = x.SecondReference , Currency = x.CurrencyCode , Value = x.GoodsValueInAccountCurrency , TransactionDate = x.TransactionDate , TransactionType = x.TransactionType , TransactionDescription = x.TransactionTypeName , Status = x.Status , RunningTotal = ( runningTotal += x.GoodsValueInAccountCurrency ) } ) ; 29/02/2012 00:00:00 154.80 309.60 30/04/2012 00:00:00 242.40 552.00 30/04/2012 00:00:00 242.40 794.40 30/04/2012 00:00:00 117.60 912.00 | Linq running total 1st value added to itself |
C_sharp : Why does n't the C # compiler tell me that this piece of code is invalid ? The call to MyMethod fails at runtime because I am trying to call a non-static method from a static method . That is very reasonable , but why does n't the compiler consider this an error at compile time ? The following will not compile so despite the dynamic dispatch , the compiler does check that MyMethod exists . Why does n't it verify the `` staticness '' ? <code> class Program { static void Main ( string [ ] args ) { dynamic d = 1 ; MyMethod ( d ) ; } public void MyMethod ( int i ) { Console.WriteLine ( `` int '' ) ; } } class Program { static void Main ( string [ ] args ) { dynamic d = 1 ; MyMethod ( d ) ; } } | Why does n't the c # compiler check `` staticness '' of the method at call sites with a dynamic argument ? |
C_sharp : I 'm trying to figure out a way to structure my data so that it is model bindable . My Issue is that I have to create a query filter which can represent multiple expressions in data.For example : x = > ( x.someProperty == true & & x.someOtherProperty == false ) || x.UserId == 2x = > ( x.someProperty & & x.anotherProperty ) || ( x.userId == 3 & & x.userIsActive ) I 've created this structure which represents all of the expressions fine my Issue is how can I make this so it 's property Model BindableMy left an right members just need to be able to be resolved to an IResolvable , but the model binder only binds to concrete types . I know I can write a custom model binder but I 'd prefer to just have a structure that works.I know I can pass json as a solutions but as a requirement I can'tIs there a way I can refine this structure so that it can still represent all simple expression while being Model Bindable ? or is there an easy way I can apply this structure so that it works with the model binder ? EDITJust in case anyone is wondering , my expression builder has a whitelist of member expressions that it it filters on . The dynamic filtering work I just looking for a way to bind this structure naturally so that my Controller can take in a QueryTreeBranch or take in a structure which accurately represent the same data.Currently the IFilterResolver has 2 implementations which need to be chosen dynamically based on the data passedI 'm looking for a solution closest to out of the box WebApi / MVC framework . Preferable one that does NOT require me to adapt the input to another structure in order generate my expression <code> public enum FilterCondition { Equals , } public enum ExpressionCombine { And = 0 , Or } public interface IFilterResolver < T > { Expression < Func < T , bool > > ResolveExpression ( ) ; } public class QueryTreeNode < T > : IFilterResolver < T > { public string PropertyName { get ; set ; } public FilterCondition FilterCondition { get ; set ; } public string Value { get ; set ; } public bool isNegated { get ; set ; } public Expression < Func < T , bool > > ResolveExpression ( ) { return this.BuildSimpleFilter ( ) ; } } //TODO : rename this classpublic class QueryTreeBranch < T > : IFilterResolver < T > { public QueryTreeBranch ( IFilterResolver < T > left , IFilterResolver < T > right , ExpressionCombine combinor ) { this.Left = left ; this.Right = right ; this.Combinor = combinor ; } public IFilterResolver < T > Left { get ; set ; } public IFilterResolver < T > Right { get ; set ; } public ExpressionCombine Combinor { get ; set ; } public Expression < Func < T , bool > > ResolveExpression ( ) { var leftExpression = Left.ResolveExpression ( ) ; var rightExpression = Right.ResolveExpression ( ) ; return leftExpression.Combine ( rightExpression , Combinor ) ; } } public class FilterController { [ HttpGet ] [ ReadRoute ( `` '' ) ] public Entity [ ] GetList ( QueryTreeBranch < Entity > queryRoot ) { //queryRoot no bind : / } } | Polymorphic Model Bindable Expression Trees Resolver |
C_sharp : Is there an easy way to find lines that consist of date time.So far I can read the textfile and my next step is to parse it , but before that I think I need some guidance before I proceed . Here is my current read script : Here is the sample text template that I need to parse generated from the tool.And here is my Aim or expected result is to get the line with datetime value : Any suggestion TIA . <code> List < string > Temp = new List < string > ( ) ; string [ ] filePaths = Directory.GetFiles ( @ '' C : \\Temp\\ '' , `` *.txt '' ) ; foreach ( string files in filePaths ) { var fileStream = new FileStream ( files , FileMode.Open , FileAccess.Read ) ; using ( var streamReader = new StreamReader ( fileStream , Encoding.UTF8 ) ) { Temp.Add ( streamReader.ReadToEnd ( ) ) ; } } foreach ( string i in Temp ) { if ( i.Contains ( `` Events '' ) ) { Console.WriteLine ( i ) ; } } `` [ Output ] '' '' [ Events ] '' '' Time '' `` Duration '' `` Severity '' `` Event '' `` Text1 '' `` Text2 '' '' [ Acquisition Settings_1 ] '' '' Data Set '' `` DataSet1 '' '' Data Stream '' `` Data '' '' [ Scan Data ( Pressures in Torr ) ] '' '' Time '' `` Scan '' `` Mass 1 '' `` Mass 2 '' `` Mass 3 '' `` 10/25/2018 4:59:27 PM '' 1 5.5816e-008 1.3141e-008 -1.6109e-010 `` 10/25/2018 4:59:35 PM '' 2 5.5484e-008 1.3403e-008 6.9720e-010 `` 10/25/2018 4:59:41 PM '' 3 5.5633e-008 1.3388e-008 8.8094e-011 `` 10/25/2018 4:59:48 PM '' 4 5.7289e-008 1.2343e-008 1.4095e-010 `` 10/25/2018 4:59:54 PM '' 5 5.2841e-008 1.3219e-008 7.5257e-010 `` 10/25/2018 4:59:57 PM '' `` After Calibration due to marginal data of daily pm3 rga checking '' `` 10/25/2018 5:49:51 PM '' `` RGA Base PressureFlat pallet ( 2018-10-25_011_a1a ) '' `` 10/25/2018 6:21:53 PM '' `` PM3 SiNFILL_27A2018-10-25_011_A4A '' `` 10/25/2018 9:51:29 PM '' `` IBE1 STEPFULL TAPENO PRE-BAKE '' `` 10/25/2018 9:58:48 PM '' `` IBE2 STEP `` 10/25/2018 4:59:27 PM '' 1 5.5816e-008 1.3141e-008 -1.6109e-010 `` 10/25/2018 4:59:35 PM '' 2 5.5484e-008 1.3403e-008 6.9720e-010 `` 10/25/2018 4:59:41 PM '' 3 5.5633e-008 1.3388e-008 8.8094e-011 `` 10/25/2018 4:59:48 PM '' 4 5.7289e-008 1.2343e-008 1.4095e-010 `` 10/25/2018 4:59:54 PM '' 5 5.2841e-008 1.3219e-008 7.5257e-010 | Reading text file and get line with date values |
C_sharp : If I have code like this : Is this any slower than ? If so , why ? In the second example , is the compiler generally making a variable from the GetString ( ) ; method which returns a string ? Also , what is the benefit of declaring variables as late as possible ? Does this benefit the GC ? If so , how ( I 'm assuming in terms of GC gens ) ? Thanks <code> string s = MyClass.GetString ( ) ; // Returns string containing `` hello world '' ; ProcessString ( s ) ; ProcessString ( MyClass.GetString ( ) ) ; | Declaring variables as late as possible and passing returning method as a parameter |
C_sharp : Alright , so I 've done some research into this topic and most of the solutions I 've found claim to fix the problem but I am finding that they are n't quite working right . I 'm in the early stages of implementing just a simple little particle engine , nothing crazy I 'm just doing it out of boredom . I have not done anything like this with WinForms before , I have certainly with C/C++ but this is a new thing for me . The following is the code I am using to draw the particles to the screen , the boiler plate code for the particles is not relevant as it works fine , I am more curious about my actual game loop . Here is the main code for updates and redrawsThe issue I am running into is that anytime the screen is getting cleared and updated , it gets this awful flickering , and not only that but it sometimes wo n't whenever I emit a particle.The form is basically just using labels as invisible locations on the screen to say where to render each particle.Anyway , I 've seen this topic before but nothing has fixed anything , the current implementation is the least flickery/laggy but is not solving the issue . Any help is appreciated , thanks ! EDIT* I realized I was never deallocating the graphics object each loop so I did that and there is no more delay whenever I click the emitter button , however the flicker is still there , I updated the code accordingly . <code> public MainWindow ( ) { this.DoubleBuffered = true ; InitializeComponent ( ) ; Application.Idle += HandleApplicationIdle ; } void HandleApplicationIdle ( object sender , EventArgs e ) { Graphics g = CreateGraphics ( ) ; while ( IsApplicationIdle ( ) ) { UpdateParticles ( ) ; RenderParticles ( g ) ; g.Dispose ( ) ; } } //Variables for drawing the particle Pen pen = new Pen ( Color.Black , 5 ) ; Brush brush = new SolidBrush ( Color.Blue ) ; public bool emmiter = false ; private void EmitterBtn_Click ( object sender , EventArgs e ) { //Determine which emitter to use if ( emmiter == true ) { //Creates a new particle Particle particle = new Particle ( EmitterOne.Left , EmitterOne.Top , .5f , .5f , 20 , 20 ) ; emmiter = false ; } else if ( emmiter == false ) { Particle particle = new Particle ( EmitterTwo.Left , EmitterTwo.Top , -.5f , .5f , 20 , 20 ) ; emmiter = true ; } } public void RenderParticles ( Graphics renderer ) { Invalidate ( ) ; Thread.Sleep ( 0 ) ; //Iterate though the static list of particles for ( int i = 0 ; i < Particle.activeParticles.Count ; i++ ) { //Draw Particles renderer.DrawRectangle ( pen , Particle.activeParticles [ i ] .x , Particle.activeParticles [ i ] .y , Particle.activeParticles [ i ] .w , Particle.activeParticles [ i ] .h ) ; } } public void UpdateParticles ( ) { for ( int i = 0 ; i < Particle.activeParticles.Count ; i++ ) { //Move particles Particle.activeParticles [ i ] .MoveParticle ( ) ; } } | Flicker in C # WinForms program on screen clear |
C_sharp : I 'm trying to diff two strings by phrase , similar to the way that StackOverflow diffs the two strings on the version edits page . What would be an algorithm to do this ? Are there gems , or other standard libraries that accomplish this ? EDIT : I 've seen other diffing algorithms ( Differ with Ruby ) and they seem to result in the following : Note how the words are diffed on a per word basis ? I 'd like some way of diffing more by phrase , so the above code output : Am I hoping for too much ? <code> > > o = 'now is the time when all good men . ' > > p = 'now some time the men time when all good men . ' > > Differ.diff_by_word ( o , p ) .format_as ( : html ) = > `` now < del class=\ '' differ\ '' > some < /del > < ins class=\ '' differ\ '' > is < /ins > < del class=\ '' differ\ '' > time < /del > the < del class=\ '' differ\ '' > men < /del > time when all good men . '' = > `` now < del class=\ '' differ\ '' > some time the men < /del > < ins class=\ '' differ\ '' > is the < /ins > time when all good men . '' | What is an Algorithm to Diff the Two Strings in the Same Way that SO Does on the Version Page ? |
C_sharp : Following the MVVM pattern I 'm trying to wire up the display of a child window by the View in response to a request from the View Model.Using the MVVM-Light Messenger the View will Register for the request to display the child window in the constructor of the View as so : Does subscribing to the ChildWindow Closed event using a Lambda cause problems for garbage collection . Or put it another way , when ( if ever ) will the editWindow become unreferenced and so a candidate for garbage collection . <code> InitializeComponent ( ) ; Messenger.Default.Register < EditorInfo > ( this , ( editorData ) = > { ChildWindow editWindow = new EditWindow ( ) ; editWindow.Closed += ( s , args ) = > { if ( editWindow.DialogResult == true ) // Send data back to VM else // Send 'Cancel ' back to VM } ; editWindow.Show ( ) ; } ) ; | Will this coding style result in a memory leak |
C_sharp : If numeric expression contains operands ( constants and variables ) of different numeric types , are operands promoted to larger types according to the following rules : if operands are of types byte , sbyte , char , short , ushort , they get converted to int typeIf one of the operands is int , then all operands are converted to intif expression also contains operands of types uint and int , then all operands are converted to longIf one of operands is long , then all operands are converted to longif expression contains operands of type ulong and long , then operands are converted to floatIf one of the operands is float , then all operands are converted to floatif one of operands is double , then all operands are converted to doubleAssuming numeric expressions contains operands of different types , will all operands first get converted to a single numeric type , and only then will the runtime try to compute the result ? For example , if variables b1 and b2 are of byte type , while i1 is of int type , will b1 and b2 get converted to int prior to computing ( b1+b2 ) : <code> int i2= ( b1+b2 ) +i1 | Are operands inside an expression promoted to larger types according to the following rules ? |
C_sharp : I have a query that should return a sum of total hours reported for the current week.This code below returns the Correct total of hours but not for a specific user in the database.The first method returns the number 24 , wich is correct but as i said , not for a specific user.I am trying to do this , but it gives me 0 in return . What am i doing wrong ? <code> public int reportedWeekTime ( int currentWeek , string username ) { var totalTime = ( from u in context.Users from r in context.Reports from w in context.Weeks from d in context.Days where u.Id == r.UserId & & r.weekNr.Equals ( currentWeek ) & & r.Id == w.ReportId & & w.DayId == d.Id select d.Hour ) .DefaultIfEmpty ( 0 ) .Sum ( ) ; return totalTime ; } public int reportedWeekTime ( int currentWeek , string username ) { var totalTime = ( from u in context.Users from r in context.Reports from w in context.Weeks from d in context.Days where u.Id == r.UserId & & r.weekNr.Equals ( currentWeek ) & & r.Id == w.ReportId & & w.DayId == d.Id & & u.Username.Contains ( username ) select d.Hour ) .DefaultIfEmpty ( 0 ) .Sum ( ) ; return totalTime ; } | Linq Query , messed up where clause in method |
C_sharp : I 'm currently reading a book on C # programming and it has brief intro to Overflow and Underflow and the writer gives a general idea of what happens when you go over the allowed range of a certain type.Example So the short type only has a range of from -32768 to 32767 and in the book the explanation given by the writer is `` For integer types ( byte , short , int , and long ) , the most significant bits ( which overflowed ) get dropped . This is especially strange , as the computer then interprets it as wrapping around . This is why we end up with a negative value in our example . You can easily see this happening if you start with the maximum value for a particular type ( for example , short.MaxValue ) and adding one to it . '' The C # Players Guide Second edition , chapter 9 , page 58 You 'd end up at the minimum ( -32768 ) . I 'm having a problem understanding this I get confused when the writer talks about `` the computer interprets it as wrapping around '' The way I tried understanding this was that the short type uses 2 bytes ( 16 bits ) So the number 32767 = 0111111111111111if i was to +1 to the binary string I 'd end up with 32768 = 1000000000000000 ( which can not be represented with the short type as max value is 32767 ) so the compiler gives -32768 . Why does it end up as a negative ? I understand the concept of using twos compliment to represent negative numbers and could someone correct my thinking here or elaborate because i do n't fully understand why we only use 15 bits of the 16 bits to represent the positive range and the most significant bit for the negative range <code> short a = 30000 ; short b = 30000 ; short sum = ( short ) ( a + b ) ; // Explicitly cast back into shortConsole.WriteLine ( sum ) ; // This would output the value -5536 | Can someone explain overflow in C # using binary ? |
C_sharp : I tried to use FileInfo.CreationTime , but it does n't represent the copy finish time.I am trying to get a list of files in a directory . The problem is that the call also returns files which are not yet finished copying.If I try to use the file , it returns an error stating that the file is in use.How can you query for files that are fully copied ? As below code . Directory.GetFiles ( ) returns which are not yet finished copying.my test file size is over 200Mb . <code> if ( String.IsNullOrEmpty ( strDirectoryPath ) ) { txtResultPrint.AppendText ( `` ERROR : Wrong Directory Name ! `` ) ; } else { string [ ] newFiles = Directory.GetFiles ( strDirectoryPath , '' *.epk '' ) ; _epkList.PushNewFileList ( newFiles ) ; if ( _epkList.IsNewFileAdded ( ) ) { foreach ( var fileName in _epkList.GetNewlyAddedFile ( ) ) { txtResultPrint.AppendText ( DateTime.Now.Hour + `` : '' + DateTime.Now.Minute + `` : '' + DateTime.Now.Second + `` = > `` ) ; txtResultPrint.AppendText ( fileName + Environment.NewLine ) ; this.Visible = true ; notifyIconMain.Visible = true ; } } else { } } | querying a directory for files that are complete ( not copy-in-progress ) |
C_sharp : MonoDevelop suggests turning this : into this : It also does it when I set anotherBoolVar to false instead : becomes : Can someone explain how these statements are equal ? <code> if ( someBoolVar ) anotherBoolVar = true ; anotherBoolVar |= someBoolVar ; if ( someBoolVar ) anotherBoolVar = false ; anotherBoolVar & = ! someBoolVar ; | MonoDevelop suggests turning if statements into bitwise operations |
C_sharp : I am having a ValueConverter used for binding 'To ' Value in a StoryBoard animation , similar to the answer - WPF animation : binding to the “ To ” attribute of storyboard animation.The problem is I am repeating the below piece of code for MultiBinding ValueConverter in couple of places.I want to remove this duplicate code by storing the result of the ValueConverter to a resource variable so I can bind this local Variable directly to the story board.I am getting the following error : The type 'Double ' does not support direct content. Can not add content to an object of type `` Double '' .I feel this is a common problem but not able to find a solution to remove this redundancy.UpdateThanks Rohit , your answer solved the problem . But I have one more related issue , So updating the question . This variable CalculatedWidth works fine in normal case , but when it is used in RenderTransform it does n't pick up the value . i.e . If I use the normal way to use Converter it works but it does n't pick up the variable.I have kept the variable as part of the local resource . Does this mean the variable does n't get created when Render transform is called ? <code> < MultiBinding Converter= '' { StaticResource multiplyConverter } '' > < Binding Path= '' ActualHeight '' ElementName= '' ExpanderContent '' / > < Binding Path= '' Tag '' RelativeSource= '' { RelativeSource Self } '' / > < /MultiBinding > < system : Double x : Key= '' CalculatedWidth '' > < MultiBinding Converter= '' { StaticResource multiplyConverter } '' > < Binding Path= '' ActualHeight '' ElementName= '' ExpanderContent '' / > < Binding Path= '' Tag '' RelativeSource= '' { RelativeSource Self } '' / > < /MultiBinding > < /system : Double > < StackPanel.RenderTransform > < TranslateTransform x : Name= '' SliderTransform '' > < TranslateTransform.X > < Binding Converter= '' { StaticResource PanelConverter } '' ElementName= '' SliderPanel '' Path= '' ActualWidth '' / > // Works < Binding Path= '' Width '' Source= '' { StaticResource CalculatedWidth } '' / > // Does n't Work < /TranslateTransform.X > < /TranslateTransform > < /StackPanel.RenderTransform > | Storing ValueConverter to variable |
C_sharp : I 'm trying to parse an incoming stream of bytes that represents messages.I need to split the stream and create a message structure for each part.A message always starts with a 0x81 ( BOM ) and ends with a 0x82 ( EOM ) .The data part is escaped using an escape byte 0x1B ( ESC ) : Anytime a byte in the data part contains one of the control bytes { ESC , BOM , EOM } , it is prefixed with ESC.The header part is not escaped , and may contain control bytes.I would like to code this in a functional reactive style using Rx.Net , by consuming an IObservable < byte > and transforming it into an IObservable < Message > .What is the most idiomatic way to do this ? Some examples : Here 's a state machine drawing for this : <code> start : 0x81header : 3 bytesdata : arbitrary lengthstop : 0x82 [ 81 01 02 03 82 ] single message [ 81 82 81 82 82 ] single message , header = [ 82 81 82 ] [ 81 01 02 1B 82 ] single message , header = [ 01 02 1B ] . [ 81 01 02 03 1B 82 82 ] single message , header = [ 01 02 03 ] , ( unescaped ) data = [ 82 ] [ 81 01 02 03 1B 1B 82 82 ] single message + dangling [ 82 ] which should be ignored . header = [ 01 02 03 ] , ( unescaped ) data = [ 1B ] | Rx.Net Message Parser |
C_sharp : Here is how my last interview went : Question : Where are strings stored ? Answer : Heap since it is a reference typeQuestion : Explain me this following code : Answer : Drew two diagrams like below : ( represents the statement , string two = one ; ( represents the statement , one = one + `` string '' ; . A new string is created on heap and assigned ) Question : Correct . Draw similar for the code snippet below : Answer : [ Test two = one ] Question : Ok. You said both strings and classes are reference types . Then why did a new object for string is created and assigned the value whereas for class , the existing string property itself gets modified ? Answer : Because strings are immutable whereas classes are mutable . ( Though I cleared the interview , I still did not understand this behaviour . Why did the designers of class make it mutable while keeping strings immutable ? There are a lot of therotical answers everywhere , but could any one make it simple by explaining this particular behaviour with the above code ? ) <code> static void Main ( string [ ] args ) { string one = `` test '' ; string two = one ; one = one + `` string '' ; Console.WriteLine ( `` One is { 0 } '' , one ) ; Console.WriteLine ( `` Two is { 0 } '' , two ) ; } class Program { static void Main ( string [ ] args ) { Test one = new Test { someString = `` test '' } ; Test two = one ; one.someString = `` test String '' ; Console.WriteLine ( `` One is { 0 } '' , one.someString ) ; Console.WriteLine ( `` Two is { 0 } '' , two.someString ) ; } } class Test { public string someString { get ; set ; } } one.someString = `` test String '' ; | Strings vs classes when both are reference types |
C_sharp : I 've created a custom structure for handling RGBA values that will be marshaled to the GPU.In my type , I am holding individual R , G , B and A components as byte values and am overlapping a 32-bit unsigned integer ( Uint32 ) to easily pass and assign the packed value . I know the concept is obvious but here 's a sample of the struct for good measure : Because of the way c # handles structs , each field must be assigned explicitly in any constructor defined . In my case , that means I have to assign the values twice in any constructors because of the overlapping fields.I could either use : or I could call the base constructor on each constructor first like so : Since this is for use in graphics code , performance is critical and I 'm trying to find the most optimal way to handle constructing in this scenario . Using the first example seems the least overhead of the two examples , since although it involves assigning all fields twice ( once for PackedValue , and once for the R , G , B and A fields ) , the other example involves assigning all values 3 times ( twice in the default constructor and once in the defined constructor ) .Is there a way to make the compiler recognize that these fields overlap and should n't require assigning explicitly R , G , B and A if PackedValue is being assigned and vice-versa ? I 'm assuming this could be done by manually tweaking the IL generated but I 'm wondering if there is a way to handle this more optimally directly in c # .Any ideas ? <code> [ StructLayout ( LayoutKind.Explicit , Size = 4 ) ] public struct RGBA { [ FieldOffset ( 0 ) ] public uint32 PackedValue ; [ FieldOffset ( 0 ) ] public byte R ; [ FieldOffset ( 1 ) ] public byte G ; [ FieldOffset ( 2 ) ] public byte B ; [ FieldOffset ( 3 ) ] public byte A ; } public RGBA ( uint packed value ) { R = G = B = A = 0 ; // initialize all to defaults before assigning packed value PackedValue = packedValue ; } public RGBA ( byte r , byte g , byte b , byte a ) { PackedValue = 0 ; // initialize to default before assigning components R = r ; G = g ; B = b ; A = a ; } public RGBA ( uint packedValue ) : this ( ) { PackedValue = packedValue ; } public RGBA ( byte r , byte g , byte b , byte a ) : this ( ) { R = r ; G = g ; B = b ; A = a ; } | Seeking optimal way to handle constructors of struct with overlapping fields |
C_sharp : Suppose I have the following two classes.How can I know if a specific property is a Father property ( Inherited ) or a Child property ? I tried but seems like Except is not detecting the equality of Father properties and Child inherited properties . <code> public class Father { public int Id { get ; set ; } public int Price { get ; set ; } } public class Child : Father { public string Name { get ; set ; } } var childProperties = typeof ( Child ) .GetProperties ( ) .Except ( typeof ( Father ) .GetProperties ( ) ) ; | How to exclude properties of father class |
C_sharp : I 'm trying to do below where condition is true , I want to execute WHERE else no.Above code giving me error , Type of conditional expression can not be determined because there is no implicit conversion between 'lambda expression ' and 'bool ' <code> var condition = true ; var mast = new List < Master > { new Master { Id = 2 , Prop1 = `` Default '' , Prop2 = `` Data '' , Prop3 = 11 } , new Master { Id = 3 , Prop1 = `` Some '' , Prop2 = `` TestData '' , Prop3 = 11 } , new Master { Id = 4 , Prop1 = `` Some '' , Prop2 = `` MoreData '' , Prop3 = 11 } , } ; var g = mast.Where ( w= > condition ? ( x = > x.Prop1.ToLower ( ) ! = `` default '' || x.Prop2.ToLower ( ) ! = `` data '' ) : true = true ) .ToList ( ) ; | how to put conditional WHERE clause within LINQ query |
C_sharp : Good afternoon , I have been working on a dll that can use CORBA to communicate to an application that is network aware . The code works fine if I run it as a C++ console application . However , I have gotten stuck on exporting the methods as a dll . The methods seems to export fine , and if I call a method with no parameters then it works as expected . I 'm hung up on passing a C # string to a C++ method.My C++ method header looks like this : My C # DLL import code is as follows : I call the method like so : The call to SpiceStart throws the exception `` PInvokeStackImbalance '' , which `` is likely because the managed PInvoke signature does not match the unmanaged target signature . `` Does anyone have any suggestions ? If I remove the char* and string from the parameters , then the method runs just fine . However , I 'd like to be able to pass the installation path of the application to the dll from C # .Thanks in advance , Giawa <code> bool __declspec ( dllexport ) SpiceStart ( char* installPath ) [ DllImportAttribute ( `` SchemSipc.dll '' , CharSet=CharSet.Ansi ) ] private static extern bool SpiceStart ( string installPath ) ; bool success = SpiceStart ( @ '' c : \sedatools '' ) ; | PInvoke Unbalances the stack |
C_sharp : I 'd like to replace the character `` by a space in a string in C # .But I have an issue when writing the function : The first argument seems to be an issue.Any idea <code> myString.Replace ( `` '' '' , '' `` ) | Replace character `` in C # |
C_sharp : I am getting an error when I attempt to display a datetime value in a textbox : My code is : The error message is : ex.Message = `` Unable to cast object of type 'System.DateTime ' to type 'System.String ' . `` Any ideas how I can resolve this ? <code> txtStartDate.Text = rdrGetUserInfo.IsDBNull ( 14 ) ? String.Empty : Convert.ToString ( rdrGetUserInfo.GetString ( 14 ) ) ; | Error converting datetime to string |
C_sharp : When using ReactiveExtension Observer exceptions are not being caught by the onError action . Using the example code below instead of the exception being caught `` An unhandled exception of type 'System.ApplicationException ' occurred in System.Reactive.Core.dll '' and the application terminates . The exception seems to bypass every try/catch in the calling stack.Am I missing how exceptions are supposed to handled by observables ? If I put a try catch in the onNext action then exception is caught and I can log it . What do I need to do to have the exception caught by the onError action ? <code> var source = Observable.Interval ( TimeSpan.FromSeconds ( seconds ) ) ; var observer = Observer.Create < long > ( l = > { //do something throw new ApplicationException ( `` test exception '' ) ; } , ex = > Console.WriteLine ( ex ) ) ; var subscription = source.Subscribe ( observer ) ; var source = Observable.Interval ( TimeSpan.FromSeconds ( seconds ) ) ; var observer = Observer.Create < long > ( l = > { try { //do something throw new ApplicationException ( `` test exception '' ) ; } catch ( Exception ex ) { //exception can be caught here and logged Console.WriteLine ( ex ) ; } } , ex = > Console.WriteLine ( ex ) ) ; var subscription = source.Subscribe ( observer ) ; | .NET ReactiveExtension observer is n't catching errors in OnError |
C_sharp : Given a list of MethodDeclarationSyntax I would like to collect all the methods in a solution that are calling this method transitively.I have been using the following code : The problem is that MethodDeclarationSyntax does n't seem to be a singleton , so this loop is running forever , visiting the same methods again and again.What is the proper way to uniquely identify a MethodDeclarationSyntax in a Dictionary/Hashset ? Edit 1 ) As a workaround , I 'm using the following MethodDeclarationSyntaxComparer to initialize my HashSet , but it looks very fragile : <code> var methods = new Stack < MethodDeclarationSyntax > ( ) ; ... // fill methods with original method to start from var visited = new HashSet < MethodDeclarationSyntax > ( ) ; while ( methods.Count > 0 ) { var method = methods.Pop ( ) ; if ( ! visited.Add ( method ) ) { continue ; } var methodSymbol = ( await solution.GetDocument ( method.SyntaxTree ) .GetSemanticModelAsync ( ) ) .GetDeclaredSymbol ( method ) ; foreach ( var referencer in await SymbolFinder.FindCallersAsync ( methodSymbol , solution ) ) { var callingMethod = ( MethodDeclarationSyntax ) referencer.CallingSymbol.DeclaringSyntaxReferences [ 0 ] .GetSyntax ( ) ; methods.Push ( callingMethod ) ; } } private class MethodDeclarationSyntaxComparer : IEqualityComparer < MethodDeclarationSyntax > { public bool Equals ( MethodDeclarationSyntax x , MethodDeclarationSyntax y ) { var xloc = x.GetLocation ( ) ; var yloc = y.GetLocation ( ) ; return xloc.SourceTree.FilePath == yloc.SourceTree.FilePath & & xloc.SourceSpan == yloc.SourceSpan ; } public int GetHashCode ( MethodDeclarationSyntax obj ) { var loc = obj.GetLocation ( ) ; return ( loc.SourceTree.FilePath.GetHashCode ( ) * 307 ) ^ loc.SourceSpan.GetHashCode ( ) ; } } | How to collect all MethodDeclarationSyntax transitively with Roslyn ? |
C_sharp : I 've tried to set up a small demo , in which an article has multiple comments . The article details view , should render the comments in a partial view . The partialView itself contains another partial view for adding a new comment . When I try to add another comment I receive a InsufficientExecutionStackException , because the action in the controller keeps calling itself . Why does this happen ? ( If somebody has the course material at hand . A similar example should be at module 9 in the 70-486 course from Msft ; that 's what I trying to build . ) Edit : The full code is on githubEdit2 : The sample on Github has been fixed . As Stephen Muecke pointed out , the fact , that both the GET and POST method hat the same names was causing the circular reference . Before any more people point out , that DI and View Models are missing and that re-rendering all comments is sub-optimal : Yes I am aware and no , those things were nothing , that I wanted to accomplish . This was just a quick n dirty demo.Controller : relevant line in the Details.cshtml for Article : _GetCommentsForArticle : _CreateCommentForArticle : <code> [ ChildActionOnly ] public PartialViewResult _GetCommentsForArticle ( int articleId ) { ViewBag.ArticleId = articleId ; var comments = db.Comments.Where ( x = > x.Article.ArticleId == articleId ) .ToList ( ) ; return PartialView ( `` _GetCommentsForArticle '' , comments ) ; } public PartialViewResult _CreateCommentForArticle ( int articleId ) { ViewBag.ArticleId = articleId ; return PartialView ( `` _CreateCommentForArticle '' ) ; } [ HttpPost ] public PartialViewResult _CreateCommentForArticle ( Comment comment , int articleId ) { ViewBag.ArticleId = articleId ; comment.Created = DateTime.Now ; if ( ModelState.IsValid ) { db.Comments.Add ( comment ) ; db.SaveChanges ( ) ; } var comments = db.Comments.Where ( x = > x.Article.ArticleId == articleId ) .ToList ( ) ; return PartialView ( `` _GetCommentsForArticle '' , comments ) ; } @ Html.Action ( `` _GetCommentsForArticle '' , `` Comments '' , new { articleId = Model.ArticleId } ) @ model IEnumerable < Mod9_Ajax.Models.Comment > < div id= '' all-comments '' > < table class= '' table '' > < tr > < th > @ Html.DisplayNameFor ( model = > model.Text ) < /th > < /tr > @ foreach ( var item in Model ) { @ * ... * @ } < /table > < /div > @ Html.Action ( `` _CreateCommentForArticle '' , `` Comments '' , new { articleId = ViewBag.ArticleId } ) @ model Mod9_Ajax.Models.Comment @ using ( Ajax.BeginForm ( `` _CreateCommentForArticle '' , `` Comments '' , new AjaxOptions { HttpMethod = `` POST '' , InsertionMode = InsertionMode.Replace , UpdateTargetId = `` all-comments '' } ) ) { @ * ... * @ < div class= '' form-group '' > < div class= '' col-md-offset-2 col-md-10 '' > < input type= '' submit '' value= '' Create '' class= '' btn btn-default '' / > < /div > < /div > < /div > } | Why does the PartialView keep calling itself ? |
C_sharp : I need to validate that the user entered text in the format : Can I do this using Regex.Match ? <code> # # # # - # # # # # - # # # # - # # # | C # regex help - validating input |
C_sharp : Here it is returning same result . Now when I 'm using StringBuilder it is not returning same value . What is the underneath reason ? Edit1 : My above question answered below . But during this discussion what we find out StringBuilder does n't have any override Equals method in its implementation . So when we call StringBuilder.Equals it actually goes to Object.Equals . So if someone calls StringBuilder.Equals and S1.Equals ( S2 ) the result will be different . <code> string s1 = `` t '' ; string s2 = 't'.ToString ( ) ; Console.WriteLine ( s1.Equals ( s2 ) ) ; // returning true Console.WriteLine ( object.Equals ( s1 , s2 ) ) ; // returning true StringBuilder s1 = new StringBuilder ( ) ; StringBuilder s2 = new StringBuilder ( ) ; Console.WriteLine ( s1.Equals ( s2 ) ) ; // returning true Console.WriteLine ( object.Equals ( s1 , s2 ) ) ; // returning false | Why object.Equals and instanceobject.Equals are not same |
C_sharp : I come from a VB.Net environment , where using Imports System and then IO.Directory.GetFiles ( ... ) works.On the other hand , it seems that using System ; is not sufficient to write use IO.Directory without prefixing it with System.. The only workaround seems to be using IO = System.IO ; Why ? Example code : Edit : My question is not what should I do to get my code working , but specifically `` why cant I write IO.Directory.GetFiles ? ? '' <code> using System ; using System.IO ; namespace Test { class Program { static void Main ( string [ ] args ) { System.Console.WriteLine ( IO.Directory.GetFiles ( System.Environment.CurrentDirectory ) [ 0 ] ) ; } } } | Why ca n't I write IO.Directory.GetFiles ? |
C_sharp : Take this example : Why is the implicit implementation of IFoo Bar ( ) necessary even though Foo converts to IFoo without a cast ? <code> public interface IFoo { IFoo Bar ( ) ; } public class Foo : IFoo { public Foo Bar ( ) { // ... } IFoo IFoo.Bar ( ) { return Bar ( ) ; } //Why is this necessary ? } | In C # , why do interface implementations have to implement a another version of a method explicitly ? |
C_sharp : I want to format a typed in time to a specific standard : When the user types it like : `` 09 00 '' , `` 0900 '' , `` 09:00 '' , `` 9 00 '' , `` 9:00 '' But when the user types it like : `` 900 '' or `` 9 '' the system fails to format it , why ? They are default formats I tought . <code> private String CheckTime ( String value ) { String [ ] formats = { `` HH mm '' , `` HHmm '' , `` HH : mm '' , `` H mm '' , `` Hmm '' , `` H : mm '' , `` H '' } ; DateTime expexteddate ; if ( DateTime.TryParseExact ( value , formats , System.Globalization.CultureInfo.InvariantCulture , System.Globalization.DateTimeStyles.None , out expexteddate ) ) return expexteddate.ToString ( `` HH : mm '' ) ; else throw new Exception ( String.Format ( `` Not valid time inserted , enter time like : { 0 } HHmm '' , Environment.NewLine ) ) ; } string str = CheckTime ( `` 09:00 '' ) ; // worksstr = CheckTime ( `` 900 '' ) ; // FormatException at TryParseExact | FormatException with TryParseExact |
C_sharp : I 'm trying to write an extension method that will convert IDictionary < K , S < V > > holding any type of collection/sequence ( S < V > ) to ILookup < K , V > which is more proper data structure in those cases . This means I 'd like my extension to work on different S types and interfaces : IDictionary < K , IEnumerable < V > > IDictionary < K , ICollection < V > > IDictionary < K , List < V > > etc . Ideally , I do n't want to write separate implementation for each possible collection type AND I want type inference to do its job.What I 've tried is : But it have no TValue in parameters list , so type inference is unable to figure it out - I get `` The type arguments for method ToLookup can not be inferred from the usage '' .Is there a chance it could work somehow in other way than adding fake TValue-typed parameter to the method ? Examples of expected usageI hope all above calls to be possible and result in a call to my single extension method : <code> public static ILookup < TKey , TValue > ToLookup < TKey , TCollection , TValue > ( this IDictionary < TKey , TCollection > dictionary ) where TCollection : IEnumerable < TValue > var dictOfIEnumerables = new Dictionary < int , IEnumerable < int > > ( ) ; var lookupFromIEnumerables = dictOfIEnumerables.ToLookup ( ) ; var dictOfICollections = new Dictionary < int , ICollection < int > > ( ) ; var lookupFromICollections = dictOfICollections.ToLookup ( ) ; var dictOfLists = new Dictionary < int , List < int > > ( ) ; var lookupFromLists = dictOfLists.ToLookup ( ) ; | Single extension method on IDictionary < K , IEnumerable/IList/ICollection < V > > |
C_sharp : Say I have a method like this : and say I need to detect if the type of arguments is actually an enumeration . I would write something like this : Now , let 's say I need to detect if it 's an enumeration of KeyValuePair ( regardless of the type of the key and the type of the value ) . My instinct would be to write something like this : but visual studio complains that Using the generic type 'KeyValuePair < TKey , TValue > ' requires 2 type arguments.I also tried : but it returns false if the key is anything but an object ( such as a string for example ) or if the value is anything but an object ( such as an int for example ) .Does anybody have suggestions how I could determine if an enumeration contains KeyValuePairs regardless of the key type and the value type and if so , how can I loop through these pairs ? <code> public void Foo ( object arguments ) if ( arguments is IEnumerable ) if ( arguments is IEnumerable < KeyValuePair < , > > ) if ( arguments is IEnumerable < KeyValuePair < object , object > > ) | How to iterate through an enumeration of KeyValuePair without knowing the type of the key and the type of the value |
C_sharp : I have problem to convert this VB code into C # BidEventInfo is a name of classC # code : <code> Public Event SendNewBid As EventHandler ( Of BidEventInfo ) Public event SendNewBid ... . ? ? ? ? ? ? | Convert code from VB into C # |
C_sharp : I 'm trying out Ninject and I 'm modifying to code I wrote with Structure Map to see how easy it is . In this base code I have a graph of objects which have different configurations via the Structure Map registries and the one to use is chosen at runtime via a value in the database ( in this case to pull back a wcf service body with some objects injected ) . So for example ( using the Structure Map code ) : Registry 1 sets up all defaults for the IBusinessContext , IRules , and ILogger types . This is just adding the types GenericContext/Logger/Rules along side the interfaces with no other specialisation.Registry 2 sets up IBusinessContext to use the SpecialisedContext class and tells the ctor to use SpecializedLogger . The instance for IBusinessContext is named `` SpecializedContext '' .This all works as expected in Structure Map ( depending on old or new syntax ) . However , when I 've been using Ninject I hit a problem with expecting the unnamed instance to be default ( not how Ninject works , I get that ) . This led to some research which all suggested that using named instances is A Really Bad Idea . I understand that there are better ways to do this using auto registration or attributes to set a name or requesting a certain type , but in the system I 'm describing there needs to be a way at run time to figure out what configuration to ask for at the top of the tree ( and let the IoC framework figure out the rest based on registered types or rules ) . So ... am I just using the IoC concept wrong here by expecting to ask for my top level object by name or is there generally a better way to do what I 'm trying to do ? Should I be using something like MEF instead and treating this all like plug-ins ? I stress I 'm not using this like a dumb factory and asking at each level of the code for a instance of type x from the container , it is the initiating action only . Thanks in advance for your time and help : ) <code> public GenericRegistry ( ) { // Set up some generic bindings here For < ILogger > ( ) .Use < Loggers.GenericLogger > ( ) ; For < IBusinessRule > ( ) .Use < Rules.StandardRule > ( ) ; For < IBusinessContext > ( ) .Use < Contexts.GenericBusinessContext > ( ) ; For < ILoggerContext > ( ) .Use < Loggers.GenericLoggerContext > ( ) ; } public SpecializedRegistry ( ) { // Old style syntax as it affects the default for IBusinessContext // Perhaps a hint at what I 'm doing ? InstanceOf < IBusinessContext > ( ) .Is.OfConcreteType < Contexts.SpecializedBusinessContext > ( ) .Named ( SpecializedInstanceName ) .Ctor < ILogger > ( ) .Is < Loggers.SpecialisedLogger > ( ) ; } | Using names to discriminate instances using IoC |
C_sharp : I have an abstract base class from which many classes are derived . I want derived classes to be able to override a virtual method defined in the base class , but there is complex logic in the base class that determines whether the overridden method is `` enabled '' at any particular moment.Consider this code -- one possible solution -- for example : In the example above , IsMethodEnabled is shorthand for more complex logic that determines whether DerivedMethod should be called -- it 's code that I want encapsulated in the base class so that I do n't have to reproduce it in each derived class.The design works as intended . If I run this sample code : ... I see exactly one call to DerivedMethod , as expected.But something rubs me wrong about this implementation . I feel like there must be a more elegant way to handle this . Is there a better way to selectively call a derived class 's method implementation from its abstract base class ? Is there a design pattern that would better serve me here ? In other words , does the code above `` smell '' ? <code> public abstract class AbstractBaseClass { public bool IsMethodEnabled { get ; set ; } public virtual void DerivedMethod ( ) { } public void Method ( ) { if ( IsMethodEnabled ) DerivedMethod ( ) ; } } public class DerivedClass : AbstractBaseClass { public override void DerivedMethod ( ) { Console.WriteLine ( `` DerivedMethod ( ) was called . `` ) ; } } AbstractBaseClass a1 = new DerivedClass ( ) { IsMethodEnabled = false } ; AbstractBaseClass a2 = new DerivedClass ( ) { IsMethodEnabled = true } ; a1.Method ( ) ; a2.Method ( ) ; | Is there a better way to call a derived class 's overridden method from its abstract base class ? |
C_sharp : I was working with the first method below , but then I found the second and want to know the difference and which is best.What is the difference between : and <code> from a in this.dataContext.reglementsjoin b in this.dataContext.Clients on a.Id_client equals b.Id select ... from a in this.dataContext.reglementsfrom b in this.dataContext.Clientswhere a.Id_client == b.Id select ... | The best way to join in Linq |
C_sharp : Before I started using Code Contracts I sometimes ran into fiddlyness relating to parameter validation when using constructor chaining.This is easiest to explain with a ( contrived ) example : I want the Test ( string ) constructor to chain the Test ( int ) constructor , and to do so I use int.Parse ( ) .Of course , int.Parse ( ) does n't like having a null argument , so if s is null it will throw before I reach the validation lines : which renders that check useless.How to fix that ? Well , I sometimes used to do this : That 's a bit fiddly , and the stack trace is n't ideal when it fails , but it works.Now , along come Code Contracts , so I start using them : All well and good . It works fine . But then I discover that I can do this : And then if I do var test = new Test ( null ) , the Contract.Requires ( s ! = null ) is executed before this ( int.Parse ( s ) ) . This means that I can do away with the convertArg ( ) test altogether ! So , on to my actual questions : Is this behaviour documented anywhere ? Can I rely on this behaviour when writing code contracts for chained constructors like this ? Is there some other way I should be approaching this ? <code> class Test { public Test ( int i ) { if ( i == 0 ) throw new ArgumentOutOfRangeException ( `` i '' , i , `` i ca n't be 0 '' ) ; } public Test ( string s ) : this ( int.Parse ( s ) ) { if ( s == null ) throw new ArgumentNullException ( `` s '' ) ; } } if ( s == null ) throw new ArgumentNullException ( `` s '' ) ; class Test { public Test ( int i ) { if ( i == 0 ) throw new ArgumentOutOfRangeException ( `` i '' , i , `` i ca n't be 0 '' ) ; } public Test ( string s ) : this ( convertArg ( s ) ) { } static int convertArg ( string s ) { if ( s == null ) throw new ArgumentNullException ( `` s '' ) ; return int.Parse ( s ) ; } } class Test { public Test ( int i ) { Contract.Requires ( i ! = 0 ) ; } public Test ( string s ) : this ( convertArg ( s ) ) { } static int convertArg ( string s ) { Contract.Requires ( s ! = null ) ; return int.Parse ( s ) ; } } class Test { public Test ( int i ) { Contract.Requires ( i ! = 0 ) ; } public Test ( string s ) : this ( int.Parse ( s ) ) { // This line is executed before this ( int.Parse ( s ) ) Contract.Requires ( s ! = null ) ; } } | Are code contracts guaranteed to be evaluated before chained constructors are called ? |
C_sharp : This link says that : The @ symbol tells the string constructor to ignore escape characters and line breaks.I try to append contain in StringBuilder like this.But it gives an error in test_all.I got a solution for this using single quotes . ' ' : But I do n't understand as per document why `` `` does not work . Or am I missing something to understand ? <code> StringBuilder sb = new StringBuilder ( ) ; sb.Append ( @ '' < test name= '' test_all '' > '' ) ; sb.Append ( `` < test name='layout_all ' > '' ) ; | Using @ symbol in string |
C_sharp : My WPF project will be organised like this : To show the Screen1 from the Screen2 I 'll use something like this : ScreenManager.Show ( `` Group1.Screen1 '' ) This looks ( using reflection ) in the Screens.Group1.Screen1 namespace for a View and a ViewModel and instantiates them.How can I eliminate the magic string without coupling Screen1 and Screen2 ( I do n't want the classes in Screen2 to use the Screen1 namespace ) . Also I would like some kind of screen discovery ( autocompletion/intellisense ) Or maybe some way ( automate test ) to verify that all calls to ScreenManager.Show are valid.Update : I came up with this : Usage : Not ideal but I suppose violating DRY is still better than magic strings . And I can automatically test ( with reflection ) that all calls are valid . <code> Screens Group1 Screen1 View.xaml ViewModel.cs Group2 Screen2 View.xaml ViewModel.cs public class ScreenNames { public Group1Screens Group1 ; public class Group1Screens { public ScreenName Screen1 ; } } public sealed class ScreenName { private ScreenName ( ) { } } public class ScreenManager : IScreenManager { public void Show ( Expression < Func < ScreenNames , ScreenName > > x ) { } } screenManager.Show ( x= > x.Group1.Screen1 ) ; | Decouple the screens without magic strings |
C_sharp : I 'm currently in the design phase of multiple rather complex systems which share common functionality ( e.g . both have customer-relationship management ( CRM ) and sales functionality ) . Therefore I 'm trying to extract the common part of the domain and reuse it in both applications . Let 's say I have application A and application B , both using CRM functionality . For the most part , the CRM functionality is the same , but both applications like to augment some things related to CRM . I 'd like to create a library implementing a basic version of the CRM system , e.g . a customer is abstracted toand the base library has a basic implementation of ICustomerApplication A can now augment this : Likewise , B has its own variation : For the purpose of abstraction , I never instantiate concrete types in the base library but use a factory or a DI container , e.g . : A and B implement the factory accordingly such that ACustomers or BCustomers are created respectively.Here 's a UML diagram of what I mean ( application B is not shown ) : For persistence I use NHibernate . Both A and B provide their own mapping ( mapping-by-code ) to include the extra properties . In addition , A defines IACustomer to be the proxy type of ACustomer and B defines IBCustomer to be the proxy type of BCustomer.I can now use NHibernate to work with the entities in A and B , e.g . in ANow let 's say I want to do something with customers in the base library ( for example in some kind of service object ) . I 've just prototyped a very simple version and so far this seems to work fine : That is , I can use the base class of the proxy type of a specific entity in QueryOver , and NHibernate creates the correct query , e.g . in A : My questionWill those queries always work as expected ? Can I always safely use a base type of the proxy interface in my queries in the base library ? Will NHibernate always find the `` correct '' entity type and table to retrieve ? Or will there be situations where this affects query efficiency adversely b/c NHibernate needs to do guess work ? Any other pitfalls I should be aware of in this scenario ? I could not find information about this in the documentation . This approach would allow me to neatly move common parts of some domains to their own base libraries , but I want to make sure it works . <code> interface ICustomer { string CustomerNumber { get ; set ; } } class Customer : ICustomer interface IACustomer : ICustomer { bool ReceivesNewsletter { get ; set ; } } class ACustomer : Customer , IACustomer { ... } interface IBCustomer : ICustomer { string NickName { get ; set ; } } class BCustomer : Customer , IBCustomer { ... . } interface ICrmFactory { ICustomer CreateCustomer ( ) ; } session.QueryOver < ACustomer > ( ) .Where ( c= > c.ReceivesNewsletter ) .List ( ) session.QueryOver < ICustomer > ( ) .Where ( c = > c.CustomerNumber == `` 1234ABC '' ) .List ( ) SELECT this_.Id as Id0_0_ , this_.CustomerNumber as Customer2_0_0_ , this_.ReceivesNewsletter as Receives3_0_0_ FROM ACustomer this_ WHERE this_.CustomerNumber = @ p0 ; @ p0 = '1234ABC ' [ Type : String ( 4000 ) ] | Can I safely query using the base type of an entity 's proxy interface in NHibernate ? |
C_sharp : I have an enum with custom value for only part of the listWhen I tried strina name = ( MyEnum ) 2 ; name was ThirdValue.But when I changed the enum toIn strina name = ( MyEnum ) 2 ; name was FifthValue.Does the compiler ( I 'm using Visual Studio 2012 ) initialize custom values only if the first has custom values ? And if ThirdValue got default value 2 in the first example how come there was n't any error in FifthValue = 2 ? <code> public enum MyEnum { FirstValue , SecondValue , ThirdValue , ForthValue = 1 , FifthValue = 2 } public enum MyEnum { FirstValue = 3 , SecondValue , ThirdValue , ForthValue = 1 , FifthValue = 2 } | Enum with specified values for only some of the members |
C_sharp : Consider this program : Here , an exception of type A is thrown for which there is no handler . In the finally block , an exception of type B is thrown for which there is a handler . Normally , exceptions thrown in finally blocks win , but it 's different for unhandled exceptions.When debugging , the debugger stops execution when A is thrown , and does not allow the finally block to be executed.When not debugging ( running it stand-alone from a command prompt ) , a message is shown ( printed , and a crash dialog ) about an unhandled exception , but after that , `` All done ! '' does get printed.When adding a top-level exception handler that does nothing more than rethrow the caught exception , all is well : there are no unexpected messages , and `` All done ! '' is printed.I understand how this is happening : the determination of whether an exception has a handler happens before any finally blocks get executed . This is generally desirable , and the current behaviour makes sense . finally blocks should generally not be throwing exceptions anyway.But this other Stack Overflow question cites the C # language specification and claims that the finally block is required to override the A exception . Reading the specification , I agree that that is exactly what it requires : In the current function member , each try statement that encloses the throw point is examined . For each statement S , starting with the innermost try statement and ending with the outermost try statement , the following steps are evaluated : If the try block of S encloses the throw point and if S has one or more catch clauses , the catch clauses are examined [ ... ] Otherwise , if the try block or a catch block of S encloses the throw point and if S has a finally block , control is transferred to the finally block . If the finally block throws another exception , processing of the current exception is terminated . Otherwise , when control reaches the end point of the finally block , processing of the current exception is continued . If an exception handler was not located in the current function invocation , the function invocation is terminated , and one of the following occurs : [ ... ] If the exception processing terminates all function member invocations in the current thread , indicating that the thread has no handler for the exception , then the thread is itself terminated . The impact of such termination is implementation-defined . An exception is n't considered unhandled , according to my reading of the spec , until after all function invocations have been terminated , and function invocations are n't terminated until the finally handlers have executed.Am I missing something here , or is Microsoft 's implementation of C # inconsistent with their own specification ? <code> using System ; static class Program { static void Main ( string [ ] args ) { try { try { throw new A ( ) ; } finally { throw new B ( ) ; } } catch ( B ) { } Console.WriteLine ( `` All done ! `` ) ; } } class A : Exception { } class B : Exception { } | Changing an unhandled exception to a handled one in a finally block |
C_sharp : One of the nuget dependencies in my project ( Swashbuckle ) requires a version of the System.Web.Http library ( 4.0.0.0 ) that is older than the version required by the rest of the project ( 5.2.3.0 ) .Swashbuckle requires that I write a class implementing a certain interface : The important part above is the apiDescription parameter of Apply . When building the project normally , the above compiles and runs fine . However , when I reflect over the running assembly using assembly.GetTypes ( ) , a ReflectionTypeLoadException is thrown , with the following loader exception details : this question references the above exception , but none of the solutions posed seem to work.I tried to solve the issue by adding a bindingRedirect to Web.config : However , that did n't seem to do anything.How can I get this type to load properly ? EDIT : I 've created a minimal reproduction of the issue . A build task in BuildTask.targets loads the project assembly and then tries to load all the types . The errors are thrown and displayed . <code> public class OperationFilter : Swashbuckle.Swagger.IOperationFilter { public void Apply ( Swashbuckle.Swagger.Operation operation , Swashbuckle.Swagger.SchemaRegistry schemaRegistry , System.Web.Http.Description.ApiDescription apiDescription ) { } } var asm = System.Reflection.Assembly.GetExecutingAssembly ( ) ; var types = asm.GetTypes ( ) Method 'Apply ' in type 'OperationFilter ' from assembly 'MyAssembly , Version=1.0.0.0 , Culture=neutral , PublicKeyToken=null ' does not have an implementation . < dependentAssembly > < assemblyIdentity name= '' System.Web.Http '' publicKeyToken= '' 31bf3856ad364e35 '' culture= '' neutral '' / > < bindingRedirect oldVersion= '' 0.0.0.0-5.2.3.0 '' newVersion= '' 5.2.3.0 '' / > < /dependentAssembly > | C # library which references older version of nuget dependency causes assembly reflection to fail |
C_sharp : I want to be able to match an entire string ( hence the word boundaries ) against a pattern `` ABC '' ( `` ABC '' is just used for convenience , I do n't want to check for equality with a fixed string ) , so newlines are significant to me . However it appears that a single `` \n '' when put at the end of a string is ignored . Is there something wrong with my pattern ? <code> Regex r = new Regex ( @ '' ^ABC $ '' ) ; string [ ] strings = { `` ABC '' , //True `` ABC\n '' , //True : But , I want it to say false . `` ABC\n\n '' , //False `` \nABC '' , //False `` ABC\r '' , //False `` ABC\r\n '' , //False `` ABC\n\r '' //False } ; foreach ( string s in strings ) { Console.WriteLine ( r.IsMatch ( s ) ) ; } | How to match a string , ignoring ending newline ? |
C_sharp : I used the following in my MVC3 ( aspx ) .NETFramework 4.0 works great . view page extension method : Partial model : In the view : When I updated the application to MVC5 .NETFramework 4.5.1 . First I could not resolve GetDropDownListItems , so I copied it from the extension model to the view using @ functions , I get this error.One other thing , the MVC3 solution was one project , while MVC5 is multi layer and I have the models in the Domain layer , while the view extension is the project as the views.My question is why I ca n't resolve the page view extension method ? Would appreciate your suggestions . <code> public static List < SelectListItem > GetDropDownListItems < T > ( this ViewPage < T > viewPage , string listName , int ? currentValue , bool addBlank ) where T : class { List < SelectListItem > list = new List < SelectListItem > ( ) ; IEnumerable < KeyValuePair < int , string > > pairs = viewPage.ViewData [ listName ] as IEnumerable < KeyValuePair < int , string > > ; if ( addBlank ) { SelectListItem emptyItem = new SelectListItem ( ) ; list.Add ( emptyItem ) ; } foreach ( KeyValuePair < int , string > pair in pairs ) { SelectListItem item = new SelectListItem ( ) ; item.Text = pair.Value ; item.Value = pair.Key.ToString ( ) ; item.Selected = pair.Key == currentValue ; list.Add ( item ) ; } return list ; } public static Dictionary < int , string > DoYouSmokeNowValues = new Dictionary < int , string > ( ) { { 1 , `` Yes '' } , { 2 , `` No '' } , { 3 , `` Never '' } } ; public static int MapDoYouSmokeNowValue ( string value ) { return ( from v in DoYouSmokeNowValues where v.Value == value select v.Key ) .FirstOrDefault ( ) ; } public static string MapDoYouSmokeNowValue ( int ? value ) { return ( from v in DoYouSmokeNowValues where v.Key == value select v.Value ) .FirstOrDefault ( ) ; } public string DoYouSmokeNow { get { return MapDoYouSmokeNowValue ( DoYouSmokeNowID ) ; } set { DoYouSmokeNowID = MapDoYouSmokeNowValue ( value ) ; } } @ Html.ExDropDownList ( `` DoYouSmokeNowID '' , this.GetDropDownListItems ( `` DoYouSmokeNowValues '' , this.Model.PersonalSocial.DoYouSmokeNowID , false ) , this.isReadOnly ) The type argument for method 'IEnumerable < SelectedItem > ASP._Page_Views_Visit_PhysicalExam_cshtml.GetDropDownListItems < T > ( ViewPage < T > , string , ,int ? , bool ) ' can not be inferred from the usage . Try specifying the the type arguments explicity . | SelectListItem / updating application form MVC3 4.0 to MVC5 4.5.1 / view extension method |
C_sharp : I am using c # framework 3.5 ..my class hereI have a listList konumlar ; well , I want to get items that equal their enlem and boylam variables each other..As you see on the photo belowI want to compate enlem and boylam and if its the equal I want to get them to different list..I can do that with a loop but want to use LINQ but i couldnt do that . I used groupby but it doesnt wrong..EDITActually I couldnt explain my quesion well..maybe distinct is not right word.. I want to seperate items which are equals each other..such as : I will take pendik items in one listand others will be in konumlar but pendik items will be removed from konumlar listEDIT 2Okay I want to seperate the list like that <code> public class KonumBilgisi { public string Enlem { get ; set ; } public string Boylam { get ; set ; } public string KonumAdi { get ; set ; } public DateTime Tarih { get ; set ; } public byte SucTuruId { get ; set ; } } var distinctList = konumlar.GroupBy ( x = > x.Enlem ) .Select ( g = > g.First ( ) ) .ToList ( ) .GroupBy ( s= > s.Boylam ) .Select ( g = > g.First ( ) ) .ToList ( ) ; | How to get distinct List from a custom list ? |
C_sharp : We are using recursion to find factors and are receiving a StackOverflow exception . We 've read that the C # compiler on x64 computers performs tail call optimizations : JIT definitely does tailcals when running optimized code and not debugging.Running dotnet -- configuration release gets this far in our program : Why is tail call optimization not occuring ? <code> ... 7214 is a factor of 12345678907606 is a factor of 123456789010821 is a factor of 123456789011409 is a factor of 1234567890 Process is terminated due to StackOverflowException . class Program { static void Main ( string [ ] args ) { const long firstCandidate = 1 ; WriteAllFactors ( 1234567890 , firstCandidate ) ; } private static void WriteAllFactors ( long number , long candidate ) { if ( number % candidate == 0 ) { System.Console.WriteLine ( $ '' { candidate } is a factor of { number } '' ) ; } candidate = candidate + 1 ; if ( candidate > number / 2 ) { return ; } WriteAllFactors ( number , candidate ) ; } } | Why is tail call optimization not occurring here ? |
C_sharp : Hi there i am new to the repository pattern . I would like to have feedback on the approach i am following.Requirement : Build the menu for the user that is currently logged in . My Solution : I created a Service , that will be called by the controller to get the menu items.The implementation for the serviceThen the CommonService ( used for common items needed in the Services eg . CurrentUserOn the class the implements the ICommonService , i get the current user using the context , in other words my service layer does not know about the HttpContext , since there is a possibility that this might by used for another type of application in the future . So this way i can handle by Current User differently for all applications , but my Service Layer will not mind.So what you should give feedback on is , is this approach to inject this kind of common service into all services a good approach or is there another way of doing this , the reason i ask , is at a later stage i will need the current user 's details for auditing purposes or whatever reason presents itself.Hope this makes sense to someone . : - ) <code> public interface IApplicationHelperService { List < Menu > GetMenuForRoles ( ) ; } public class ApplicationHelperService : IApplicationHelperService { private readonly IMenuRepository _menuRepository ; //this fecthes the entire menu from the datastore private readonly ICommonService _commonService ; //this is a Service that contained common items eg . UserDetails , ApplicationName etc . public ApplicationHelperService ( IMenuRepository menuRepository , ICommonService commonService ) { this._menuRepository = menuRepository ; this._commonService = commonService ; } public List < Menu > ApplicationMenu { get { return _menuRepository.GetMenu ( _commonService.ApplicationName ) ; } } List < Menu > IApplicationHelperService.GetMenuForRoles ( ) { return ApplicationMenu.Where ( p = > p.ParentID == null & & p.IsInRole ( _commonService.CurrentUser.Roles ) ) .OrderBy ( p = > p.MenuOrder ) .ToList ( ) ; } } public interface ICommonService { IUser CurrentUser { get ; } string ApplicationName { get ; } } | Repository pattern for common items |
C_sharp : I have a `` settings '' class , which has some properties for usability and to restrict set accessor . It seems easy while i had within ten items , but then their count was increased . I need some way to create these properties automatically , something like that : It may have deal with reflection , but i ca n't get to efficient solution.The properties definition : UPDATETo summ up , i wrote the next code : But i have an error on ( ) = > this.GetValueById ( `` cbNextExcCount '' ) ) : argument type 'lambda expression ' is not assignable to parameter type 'object'.I can store Func < bool > , but settings may have other type than bool and if i use Func , it 's get a bit more complicate to call . <code> foreach ( var property in SettingsList ) { _settings.AddAutoProperty ( property ) ; } public bool cbNextExcCount { get { return ( bool ) this.GetValueById ( `` cbNextExcCount '' ) ; } } public bool cbSaveOnChangeExc { get { return ( bool ) this.GetValueById ( `` cbSaveOnChangeExc '' ) ; } } public bool cbAutoIncrement { get { return ( bool ) this.GetValueById ( `` cbAutoIncrement '' ) ; } } public bool cbRememberOnExit { get { return ( bool ) this.GetValueById ( `` cbRememberOnExit '' ) ; } } ... etc . public IDictionary < string , object > Properties = new ExpandoObject ( ) ; private List < string > SettingsList = new List < string > { `` cbNextExcCount '' , `` cbSaveOnChangeExc '' , `` cbAutoIncrement '' , `` cbRememberOnExit '' } ; public void CreateProperties ( ) { foreach ( string SettingName in SettingsList ) { Properties.Add ( SettingName , ( ) = > this.GetValueById ( SettingName ) ) ; } } | How to create properties automatically ? |
C_sharp : I have identified that when the following expression is executed : on mysql the query executed is : Can anyone explain please why this last extra condition is added ? AND ( 52 IS NOT NULL ) ) <code> int aNum = 52 ; var myArtifacts = mydbcontext.artifacts.Where ( a = > a.ParentID == aNum ) .ToList ( ) ; SELECT ` Extent1 ` . ` ID ` , ` Extent1 ` . ` ParentID ` FROM ` artifacts ` AS ` Extent1 ` WHERE ( ( ` Extent1 ` . ` ParentID ` = 52 ) AND ( 52 IS NOT NULL ) ) ; | Entity framework adds an extra condition on where clause |
C_sharp : I have two classes like thisTrying to mock this in a unit test using Moq with this line new Mock < FooWithGoo < Bar > > ( ) gives me this exception.System.ArgumentException : Type to mock must be an interface or an abstract or non-sealed class . -- - > System.TypeLoadException : Method 'Do ' in type 'Castle.Proxies.FooWithGoo `` 1Proxy ' from assembly 'DynamicProxyGenAssembly2 , Version=0.0.0.0 , Culture=neutral , PublicKeyToken=null ' does not have an implementation.Is there something I am doing wrong here ? How can I mock this ? UPDATE : This shows the problem nicely for me.Test1 fails while test 2 passes . The problem is that the generic abstract gets the same signature than the concrete method ... and it gets confused by that I guess . <code> public abstract class Foo < T > where T : Bar { public Bar Do ( Bar obj ) { //I cast to T here and the call the protected one . } ... protected abstract Bar Do ( T obj ) ; } public abstract class FooWithGoo < T > : Foo < T > where T : Bar { ... } using Microsoft.VisualStudio.TestTools.UnitTesting ; using Moq ; namespace UnitTestProject1 { public class Bar { } public class BarSub : Bar { } public abstract class Foo < T > where T : Bar { public Bar Do ( Bar obj ) { return null ; } protected abstract Bar Do ( T obj ) ; } public abstract class FooWithGoo < T > : Foo < T > where T : Bar { public FooWithGoo ( string x ) { } } [ TestClass ] public class UnitTest1 { [ TestMethod ] public void TestMethod1 ( ) { var mock = new Mock < FooWithGoo < Bar > > ( `` abc '' ) ; FooWithGoo < Bar > foo = mock.Object ; } [ TestMethod ] public void TestMethod2 ( ) { var mock = new Mock < FooWithGoo < BarSub > > ( `` abc '' ) ; FooWithGoo < BarSub > foo = mock.Object ; } } } | Mocking an abstract class derived from an abstract class |
C_sharp : Where the _Internal is a Service with a guaranteed 99.99 % up-time and not formalized fault contract interfaces defined . Exceptions which are handled in my application level ( business layer level ) as a BusinessException - root class Where BusinessException is defined as followsAnd the current test Method is To do : Add Exception testexpectedResult==actualResult does not test the exception block of the code . How do I construct a request that makes the service throw the exception other than manually removing the ethernet cable to get this specific type of server error.The best I could come up with was But there is got ta be a better option . <code> [ HttpPost ] [ Route ( `` TnC '' ) ] public IHttpActionResult TnC ( CustomViewModel myViewModel ) { try { return Json ( _Internal.TnC ( myViewModel , LoggedInUser ) ) ; } catch ( BusinessException exception ) { return Json ( BuildErrorModelBase ( exception ) ) ; } } public class BusinessException : Exception { BusinessException ( ) ... BusinessExceptionFoo ( ) ... BusinessExceptionBar ( ) ... // ... } [ TestMethod ] [ ExpectedException ( typeof ( BusinessException ) , `` Not a valid Business Case '' ) ] public void TnCTest ( ) { var bookingService = myContainer.Resolve < mySvc > ( ) ; var controller = new LinkBookingController ( mySvc , myContainer ) ; var expectedResult = controller.TnC ( new myViewModel { ... params } ) ; var actualResult = GetData < Result < myViewModel > > ( expectedResult ) ; Assert.AreEqual ( expectedResult , actualResult ) ; } # if DEBUG & & UnitTestExceptions throw new BusinessException ( ) ; # endif | How to add an exception test for the below Http call that returns a json |
C_sharp : Short VersionFor those who do n't have the time to read my reasoning for this question below : Is there any way to enforce a policy of `` new objects only '' or `` existing objects only '' for a method 's parameters ? Long VersionThere are plenty of methods which take objects as parameters , and it does n't matter whether the method has the object `` all to itself '' or not . For instance : Here the List < Person > .Add method has taken an `` existing '' Person ( Bob ) as well as a `` new '' Person ( Larry ) , and the list contains both items . Bob can be accessed as either bob or people [ 0 ] . Larry can be accessed as people [ 1 ] and , if desired , cached and accessed as larry ( or whatever ) thereafter.OK , fine . But sometimes a method really should n't be passed a new object . Take , for example , Array.Sort < T > . The following does n't make a whole lot of sense : All the above code does is take a new array , sort it , and then forget it ( as its reference count reaches zero after Array.Sort < int > exits and the sorted array will therefore be garbage collected , if I 'm not mistaken ) . So Array.Sort < T > expects an `` existing '' array as its argument.There are conceivably other methods which may expect `` new '' objects ( though I would generally think that to have such an expectation would be a design mistake ) . An imperfect example would be this : As I said , this is n't a great example , since DataRowCollection.Add does n't actually expect a new DataRow , exactly ; but it does expect a DataRow that does n't already belong to a DataTable . So the last line in the code above wo n't work ; it needs to be : Anyway , this is a lot of setup for my question , which is : is there any way to enforce a policy of `` new objects only '' or `` existing objects only '' for a method 's parameters , either in its definition ( perhaps by some custom attributes I 'm not aware of ) or within the method itself ( perhaps by reflection , though I 'd probably shy away from this even if it were available ) ? If not , any interesting ideas as to how to possibly accomplish this would be more than welcome . For instance I suppose if there were some way to get the GC 's reference count for a given object , you could tell right away at the start of a method whether you 've received a new object or not ( assuming you 're dealing with reference types , of course -- which is the only scenario to which this question is relevant anyway ) .EDIT : The longer version gets longer.All right , suppose I have some method that I want to optionally accept a TextWriter to output its progress or what-have-you : Now , let 's consider two different ways I could call this method : OR : Hmm ... it would seem that this poses a problem , does n't it ? I 've constructed a StreamWriter , which implements IDisposable , but TryDoSomething is n't going to presume to know whether it has exclusive access to its output argument or not . So the object either gets disposed prematurely ( in the first case ) , or does n't get disposed at all ( in the second case ) .I 'm not saying this would be a great design , necessarily . Perhaps Josh Stodola is right and this is just a bad idea from the start . Anyway , I asked the question mainly because I was just curious if such a thing were possible . Looks like the answer is : not really . <code> var people = new List < Person > ( ) ; Person bob = new Person ( `` Bob '' ) ; people.Add ( bob ) ; people.Add ( new Person ( `` Larry '' ) ) ; Array.Sort < int > ( new int [ ] { 5 , 6 , 3 , 7 , 2 , 1 } ) ; DataTable firstTable = myDataSet.Tables [ `` FirstTable '' ] ; DataTable secondTable = myDataSet.Tables [ `` SecondTable '' ] ; firstTable.Rows.Add ( secondTable.Rows [ 0 ] ) ; firstTable.ImportRow ( secondTable.Rows [ 0 ] ) ; static void TryDoSomething ( TextWriter output ) { // do something ... if ( output ! = null ) output.WriteLine ( `` Did something ... '' ) ; // do something else ... if ( output ! = null ) output.WriteLine ( `` Did something else ... '' ) ; // etc . etc . if ( output ! = null ) // do I call output.Close ( ) or not ? } static void TryDoSomething ( ) { TryDoSomething ( null ) ; } string path = GetFilePath ( ) ; using ( StreamWriter writer = new StreamWriter ( path ) ) { TryDoSomething ( writer ) ; // do more things with writer } TryDoSomething ( new StreamWriter ( path ) ) ; | Can I detect whether I 've been given a new object as a parameter ? |
C_sharp : I 've been looking quite a bit at Mr. Skeet 's blog on how to re-implement LINQ.In particular , he states that the code : is translated to methods that are extension methods that are provided by the LINQ library : BY THE COMPILER.My question is , how does one impress the bigwigs enough with a library to cause them to allow the language to change to support the library ? Or were those words already reserved before LINQ came along ? <code> var list = ( from person in people where person.FirstName.StartsWith ( `` J '' ) orderby person.Age select person.LastName ) .ToList ( ) ; people.Where ( person = > person.FirstName.StartsWith ( `` J '' ) ) .OrderBy ( person = > person.Age ) .Select ( person = > person.LastName ) | Is it possible to create C # language modifications as did LINQ ? |
C_sharp : I 'm using Simple.Data ORM . I 'm trying to make a query from two joined tables . This query works fine : But when this line is added : I 'm getting this exception : The multi-part identifier \ '' dbo.CandidateProfiles.CandidateId\ '' could not be bound.I was trying explicitly pass 0 , 1 and few other numbers to Skip but I always get the same exception.My test query should return 4 elements and I 'm skipping 0 elements ( it can be more in normal use ) .Additional info : CandidateProfiles has foreign key from Candidates and it 's CandidateId can be null . Edit : We 've done a workaround for this problem , but I 'm really curious why this one wo n't work . Simple.Data looked fun at first , but now I 'm not sure if I will use it in future <code> dynamic alias ; var candidatesRec = db.dbo.Candidates .FindAll ( db.dbo.Candidates.CommonOfferId == commonOfferId & & db.dbo.CandidateProfiles.CandidateId == null ) .LeftJoin ( db.dbo.CandidateProfiles , out alias ) .On ( db.dbo.Candidates.Id == alias.CandidateId ) .Select ( db.dbo.Candidates.Id , db.dbo.Candidates.Email ) .OrderByDescending ( db.dbo.Candidates.ApplicationDate ) .Skip ( ( pageNumber - 1 ) * pageSize ) | Simple.Data ORM . The multi-part identifier could not be bound |
C_sharp : If I implement a generic type that risks being instantiated with lots of type params , should I avoid ( for JIT performance/code size etc . reasons ) having many nested non-generic types ? Example : The alternative which works equally well is to have the non-generic types outside , but then they pollute the namespace . Is there a best practice ? <code> public class MyGenericType < TKey , TValue > { private struct IndexThing { int row ; int col ; } private struct SomeOtherHelper { .. } private struct Enumerator : IEnumerator < KeyValuePair < TKey , TValue > > { } } public class MyGenericType < TKey , TValue > { private struct Enumerator : IEnumerator < KeyValuePair < TKey , TValue > > { } } internal struct IndexThingForMyGenericType { int row ; int col ; } internal struct SomeOtherHelper { ... } | Should I avoid nested types in generic types ? |
C_sharp : I have a column in a table that is full of regular expressions . I have a string in my code , and I want to find out which regular expressions in that column would match that string and return those rows . Aside from pulling each row and matching the regular expression ( which is costly , checking against potentially thousands of records for a single page load ) is there a way I can do this in SQL instead with one ( or a couple ) queries ? Example input : W12ABCExample column dataShould return rows 2 and 4 . <code> 1 ^ [ W11 ] [ \w ] + $ 2 ^ [ W12 ] [ \w ] + $ 3 ^ [ W13 ] [ \w ] + $ 4 ^ [ W1 ] [ \w ] + [ A ] [ \w ] + $ 5 ^ [ W1 ] [ \w ] + [ B ] [ \w ] + $ 6 ^ [ W1 ] [ \w ] + [ C ] [ \w ] + $ | Matching a string against a column full of regular expressions |
C_sharp : I have a variable that indicates the length of time the UI can be idle . I have elected to call this variable UITimer . I want to pass the variable into my classes constructor and then store it off in a local field.What is the proper way to do the casing of this ? We use the common convention of a parameter not being capitalized . So should I do this : or this ? Also , we do an underscore and lowercase first letter for our fields . Should that be declared like this : or like thisI think _uiTimer is the way to go ( the other option seems lame ) but I am interested to see if I am missing something.Best answer would be a link to a doc that says that acronyms should all keep the same case in C # naming ( or something like it ) <code> uITimer uiTimer private int _uITimer private int _uiTimer ? | Capitalization of an acronym that starts a parameter |
C_sharp : I 've seen and used this pattern several times , and it 's very useful for providing common functionality across a series of type-specific subclasses . For instance , this could be a model for Controllers/Presenters specific to a type of domain object that is central to the page ( s ) the class is used to control ; basic operations like retrieval/persistence may use 100 % common functionality , but binding/unbinding may be very specific . Is there a name for this pattern of generic declaration without exposing the generic to the end user ? <code> //this class ( or interface if you like ) is set up as generic ... public abstract class GenericBase < T > { public T PerformBasicTask ( T in ) { ... } } // ... but is intended to be inherited by objects that close the generic ... public class ConcreteForDates : GenericBase < DateTime > { public DateTime PerformSpecificTask ( DateTime in ) { ... } } // ... so that consuming code never knows that a generic is involvedvar myDateConcrete = new ConcreteForDates ( ) ; //look ma , no GTP ! //These two methods look alike , and there is no generic type inference , //even with PerformBasicTask ( ) .var basicResult = myDateConcrete.PerformBasicTask ( DateTime.Now ) ; var specificResult = myDateConcrete.PerformSpecificTask ( DateTime.Today ) ; //does not compile because T is understood by inheritance to be a DateTime , //even though PerformBasicTask ( ) 's implementation may well handle an int.var anotherBasicResult = myDateConcrete.PerformBasicTask ( 1 ) ; | Is there a name for this pattern of using generics ? |
C_sharp : Does code in the constructor add to code in subclass constructors ? Or does the subclass 's constructor override the superclass ? Given this example superclass constructor : ... and this subclass constructor : When an instance of FordCar is created , will this trace `` Car '' and `` Ford '' ? ? Edit : Will arguments also add up ? See updated code above . <code> class Car { function Car ( speed : int ) { trace ( `` CAR speed `` +speed ) } } class FordCar extends Car { function FordCar ( model : string ) { trace ( `` FORD model `` +model ) } } | Does code in the constructor add to code in subclass constructors ? |
C_sharp : I am trying to aggregate several queries together to provide a latest updates display for my users using a common data structure for union support . In my first function I have the following select clause : When called this correctly generates a query that returns 9 fields . The second method 's select is : When this query is run by itself it correctly returns 9 values . However , when I try to doI get a sql exception that the query failed because all the queries do not have the same number of fields . Investigating the generated SQL shows that the first query is correct , but Linq is generating the 2nd ( unioned ) query to only have 7 fields . After testing it appears that Linq seems to be `` optimizing '' out the nulls so it 's only returning one null column instead of 3 , thus causing a mis-match.Why is Linq-to-sql incorrectly generating the union and how can I work around this ? Edit : Ok the issue seems to deal with union chaining in Linq-to-Sql for .Net 3.5 . This does not happen in 4 apparently . With the following code : I then union chain via : var q2 = Test1 ( ) .Union ( Test2 ( ) ) .Union ( Test1 ( ) ) ; In .Net 3.5 I get the following sql , which has a mis-match and failsIn .net 4 the following code is generated : That is valid sql and works . As we are unable to bring our production systems up to .net 4 for various reasons , does anyone know a way I can work around this in .net 3.5 ? <code> .Select ( x = > new PlayerUpdateInfo { FirstName = x.PodOptimizedSearch.FirstName , LastName = x.PodOptimizedSearch.LastName , RecruitId = x.RecruitId , Date = x.Date , UpdateMessage = x.IsAddedAction ? `` Player was added to this recruiting board by `` + x.Person.FirstName + `` `` + x.Person.LastName : `` Player was removed from this recruiting board by `` + x.Person.FirstName + `` `` + x.Person.LastName , // Defaults for union support Team = string.Empty , UpdateComments = x.Comments , TeamId = 0 , State = string.Empty } ) ; select new PlayerUpdateInfo { FirstName = recruit.FirstName , LastName = recruit.LastName , RecruitId = recruit.RecruitId , Date = asset.CreateDate , UpdateMessage = `` New Full Game Added '' , // Defaults for union support Team = null , UpdateComments = null , TeamId = 0 , State = null } ; var query = GetFirstQuery ( ) ; query = query.union ( GetSecondQuery ( ) ) ; protected IQueryable < PlayerUpdateInfo > Test1 ( ) { return PodDataContext.Assets .Select ( x = > new PlayerUpdateInfo { Date = DateTime.Now , FirstName = x.Title , LastName = string.Empty , RecruitId = 0 , State = string.Empty , Team = string.Empty , TeamId = 0 , UpdateComments = string.Empty , UpdateMessage = string.Empty } ) ; } protected IQueryable < PlayerUpdateInfo > Test2 ( ) { return PodDataContext.SportPositions .Select ( x = > new PlayerUpdateInfo { Date = DateTime.Now , FirstName = string.Empty , LastName = x.Abbreviation , RecruitId = 0 , State = string.Empty , Team = string.Empty , TeamId = 0 , UpdateComments = string.Empty , UpdateMessage = string.Empty } ) ; } SELECT [ t4 ] . [ value ] AS [ RecruitId ] , [ t4 ] . [ Title ] AS [ FirstName ] , [ t4 ] . [ value2 ] AS [ LastName ] , [ t4 ] . [ value22 ] AS [ Team ] , [ t4 ] . [ value3 ] AS [ Date ] FROM ( SELECT [ t2 ] . [ value ] , [ t2 ] . [ Title ] , [ t2 ] . [ value2 ] , [ t2 ] . [ value2 ] AS [ value22 ] , [ t2 ] . [ value3 ] FROM ( SELECT @ p0 AS [ value ] , [ t0 ] . [ Title ] , @ p1 AS [ value2 ] , @ p2 AS [ value3 ] FROM [ dbo ] . [ Assets ] AS [ t0 ] UNION SELECT @ p3 AS [ value ] , @ p4 AS [ value2 ] , [ t1 ] . [ Abbreviation ] , @ p5 AS [ value3 ] FROM [ dbo ] . [ SportPositions ] AS [ t1 ] ) AS [ t2 ] UNION SELECT @ p6 AS [ value ] , [ t3 ] . [ Title ] , @ p7 AS [ value2 ] , @ p8 AS [ value3 ] FROM [ dbo ] . [ Assets ] AS [ t3 ] ) AS [ t4 ] SELECT [ t4 ] . [ value ] AS [ RecruitId ] , [ t4 ] . [ Title ] AS [ FirstName ] , [ t4 ] . [ value2 ] AS [ LastName ] , [ t4 ] . [ value3 ] AS [ Team ] , [ t4 ] . [ value4 ] AS [ TeamId ] , [ t4 ] . [ value5 ] AS [ State ] , [ t4 ] . [ value6 ] AS [ UpdateMessage ] , [ t4 ] . [ value7 ] AS [ UpdateComments ] , [ t4 ] . [ value8 ] AS [ Date ] FROM ( SELECT [ t2 ] . [ value ] , [ t2 ] . [ Title ] , [ t2 ] . [ value2 ] , [ t2 ] . [ value3 ] , [ t2 ] . [ value4 ] , [ t2 ] . [ value5 ] , [ t2 ] . [ value6 ] , [ t2 ] . [ value7 ] , [ t2 ] . [ value8 ] FROM ( SELECT @ p0 AS [ value ] , [ t0 ] . [ Title ] , @ p1 AS [ value2 ] , @ p2 AS [ value3 ] , @ p3 AS [ value4 ] , @ p4 AS [ value5 ] , @ p5 AS [ value6 ] , @ p6 AS [ value7 ] , @ p7 AS [ value8 ] FROM [ dbo ] . [ Assets ] AS [ t0 ] UNION SELECT @ p8 AS [ value ] , @ p9 AS [ value2 ] , [ t1 ] . [ Abbreviation ] , @ p10 AS [ value3 ] , @ p11 AS [ value4 ] , @ p12 AS [ value5 ] , @ p13 AS [ value6 ] , @ p14 AS [ value7 ] , @ p15 AS [ value8 ] FROM [ dbo ] . [ SportPositions ] AS [ t1 ] ) AS [ t2 ] UNION SELECT @ p16 AS [ value ] , [ t3 ] . [ Title ] , @ p17 AS [ value2 ] , @ p18 AS [ value3 ] , @ p19 AS [ value4 ] , @ p20 AS [ value5 ] , @ p21 AS [ value6 ] , @ p22 AS [ value7 ] , @ p23 AS [ value8 ] FROM [ dbo ] . [ Assets ] AS [ t3 ] ) AS [ t4 ] | Why is Linq-to-sql incorrectly removing fields in my union ? |
C_sharp : I was wondering why it is possible to do this in C # 7.0 : ..but not this : Can someone explain that ? <code> int ? test = 0 ; int test2 = test ? ? throw new Exception ( `` Error '' ) ; int ? test = 0 ; int test2 = test ? ? return ; | Null coalescing operator ( ? ? ) with return |
C_sharp : I have Net Core 3.1.1000 installed.Now we are trying to run ef migrations with EF Core 2.2.6 database previous Solution , when running the following , receive error below.The application to execute does not exist : .dotnet\tools.store\dotnet-ef\2.2.6-servicing-10079\dotnet-ef\2.2.6-servicing-10079\tools\netcoreapp2.2\any\dotnet-ef.dll'.How can we resolve this ? How Can I point directly to the DLL target directory and execute ? I heard renaming file directory is not good idea.I see the real dll is located here : ... .dotnet\tools.store\dotnet-ef\2.2.6\dotnet-ef\2.2.6\tools\netcoreapp2.2\any\dotnet-ef.dllalready ran this and installed this : dotnet tool install -- global dotnet-ef <code> dotnet ef migrations add InitialCreate | Entity Framework : Run EF Migrations for Previous Version in Net Core |
C_sharp : I need to take an 8 bit number on a 64 bit cpu and shift it to the right 8 times . Each time I shift the number I need to shift the same 8 bit number in behind it so that I end up with the same 8 bit number repeating 8 times . This would end up being shift , add 8 , shift add 8 ... etc . which ends up being 40+ cycles ( correct me if I 'm wrong ) .Is there a way to do this operation ( of shift and copy ) in 1 cycle so that I end up with the same value in the end ? EDIT : I 'm trying to compare a stream of chars to detect keywords . I ca n't use string.contains because the string value may be across the boundary of the buffer . Also , the application has to run on embedded ARM cpus as well as desktop and server CPUs . Memory usage and cpu cycles are very important . <code> long _value = 0 ; byte _number = 7 ; for ( int i = 0 ; i < 8 ; i++ ) { _value = ( _value < < 8 ) + _number ; } | Is there a shift and copy cpu instruction that can be accessed from c # ? |
C_sharp : How can I get this in to one query ? What I want is the Person from the Company that matches the name of the person I 'm searching for.Currently I get the Company and then run basically the same search . <code> var existingCompany = bidInfo.Companies .FirstOrDefault ( c= > c.CompanyDomain ! = null & & c.CompanyDomain.People.FirstOrDefault ( p = > p.Name == bidInfo.ArchitectPerson.Name ) ! = null ) ; Person existingPerson=null ; if ( existingCompany ! =null ) { existingPerson = existingCompany.CompanyDomain.People.FirstOrDefault ( p = > p.Name == bidInfo.ArchitectPerson.Name ) ; } | How do I combine these two linq queries into a single query ? |
C_sharp : When I 'm running this code , I 'm getting error Index was outside the bounds of the array.Can anyone help me out , please ? <code> for ( var i = 9 ; i + 2 < lines.Length ; i += 3 ) { Items.Add ( new ItemProperties { Item = lines [ i ] , Description = lines [ i + 1 ] , Quantity = lines [ i + 2 ] , UnitPrice = lines [ i + 3 ] } ) ; } | Error : Index was outside the bounds of the array |
C_sharp : I have the following classAnd NUnit unit testMy Unit tests fails with When I debug the method return 8.49 so where does the unit test get the long number from with a 2 at the end ? <code> public static class MyClass { public static double Converter ( int mpg ) { return Math.Round ( ( double ) mpg / ( ( double ) 36 / 12.74 ) , 2 ) ; } } [ TestFixture ] public class ConverterTests { [ Test ] public void Basic_Tests ( ) Assert.AreEqual ( 8.50 , MyClass.Converter ( 24 ) ) ; } } Expected : 8.5dBut was : 8.4900000000000002d | C # NUnit unit test not using correct method return to compare |
C_sharp : I have implemented Multi Language Support into my ASP.NET C # followed by this tutorial and set english to my Default language as can be seen here : When switching to german nothing happens : In my App_GlobalResource Folder I have to files : de.language.resx and en.language.resxMy mls.cs file ( In the tutorial named BasePage.cs ) contains the following code : And here is my Login.aspx page : Here is my aspx code : Hope somebody can help . <code> public class mls : System.Web.UI.Page { public void setLang ( ) { InitializeCulture ( ) ; } protected override void InitializeCulture ( ) { if ( ! string.IsNullOrEmpty ( Request [ `` lang '' ] ) ) { Session [ `` lang '' ] = Request [ `` lang '' ] ; } string lang = Convert.ToString ( Session [ `` lang '' ] ) ; string culture = string.Empty ; // In case , if you want to set vietnamese as default language , then removing this comment if ( lang.ToLower ( ) .CompareTo ( `` en '' ) == 0 || string.IsNullOrEmpty ( culture ) ) { culture = `` en-US '' ; } if ( lang.ToLower ( ) .CompareTo ( `` en '' ) == 0 || string.IsNullOrEmpty ( culture ) ) { culture = `` en-US '' ; } if ( lang.ToLower ( ) .CompareTo ( `` de '' ) == 0 ) { culture = `` de-AT '' ; } Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture ( culture ) ; Thread.CurrentThread.CurrentUICulture = new CultureInfo ( culture ) ; base.InitializeCulture ( ) ; } } public partial class WebForm3 : mls { protected void Page_Load ( object sender , EventArgs e ) { if ( ! string.IsNullOrEmpty ( Convert.ToString ( Session [ `` lang '' ] ) ) ) { if ( Convert.ToString ( Session [ `` lang '' ] ) == `` en '' ) { lbl_Debug.Text = `` lang=en '' ; Session [ `` lang '' ] = null ; Session [ `` lang '' ] = `` en '' ; } else if ( Convert.ToString ( Session [ `` lang '' ] ) == `` de '' ) { lbl_Debug.Text = `` lang=de '' ; Session [ `` lang '' ] = null ; Session [ `` lang '' ] = `` de '' ; } } else { lbl_Debug.Text = `` nothing '' ; } } } < asp : Content ID= '' Content2 '' ContentPlaceHolderID= '' ph_RowMain '' runat= '' server '' > < div class= '' login-box '' > < div class= '' login-logo '' > < a href= '' Start.aspx '' > < b > < asp : Literal ID= '' lt_adminInterfaceHeader '' runat= '' server '' Text= '' < % $ Resources : en.language , lt_adminHeader % > '' > < /asp : Literal > < /b > < /a > < /div > < ! -- /.login-logo -- > < div class= '' login-box-body '' > < p class= '' login-box-msg '' > < asp : Literal ID= '' lt_adminInterfaceBox '' runat= '' server '' Text= '' < % $ Resources : en.language , lt_adminBox % > '' > < /asp : Literal > < /p > < div class= '' form-group has-feedback '' > < asp : TextBox ID= '' tb_email '' runat= '' server '' type= '' email '' class= '' form-control '' placeholder= '' < % $ Resources : en.language , tb_email % > '' > < /asp : TextBox > < span class= '' glyphicon glyphicon-envelope form-control-feedback '' > < /span > < /div > < div class= '' form-group has-feedback '' > < asp : TextBox ID= '' tb_password '' runat= '' server '' type= '' password '' class= '' form-control '' placeholder= '' < % $ Resources : en.language , tb_password % > '' > < /asp : TextBox > < span class= '' glyphicon glyphicon-lock form-control-feedback '' > < /span > < /div > < div class= '' row '' > < div class= '' col-xs-12 '' > < asp : Button ID= '' btn_signIn '' runat= '' server '' Text= '' < % $ Resources : en.language , btn_signIn % > '' type= '' submit '' class= '' btn btn-primary btn-block btn-flat '' / > < /div > < ! -- /.col -- > < /div > < /div > < ! -- /.login-box-body -- > < /div > < ! -- /.login-box -- > | Switching Language in C # .NET has no impact to site |
C_sharp : Reading through answers to this question prompted me to think about what happens exception-wise when the awaited task throws . Do all `` clients '' get to observe the exception ? I admit I may be confusing a couple of things here ; that 's the reason I 'm asking for clarification.I 'll present a concrete scenario ... Let 's say I have a server with a global collection of long-running Task instances , started by clients . After starting one or more tasks , a client can query their progress and retrieve results when they become available , as well as any errors that might occur.Tasks themselves may perform very different business-specific things - normally , no two are quite the same . However , if one of the clients does attempt to start the same task as another had started previously , the server should recognize this and `` attach '' the second client to the existing task instead of spooling up a new copy.Now , each time any client queries the status of the task it 's interested in , it does something along these lines : In short , it gives the task some reasonable time to finish what it 's doing first , then falls back to reporting the on-going progress . This means there 's a potentially significant window of time in which multiple clients could observe the same task failing.My question is : if the task happens to throw during this window , is the exception observed ( and handled ) by all clients ? <code> var timeout = Task.Delay ( numberOfSecondsUntilClientsPatienceRunsOut ) ; try { var result = await Task.WhenAny ( timeout , task ) ; if ( result == timeout ) { // SNIP : No result is available yet . Just report the progress so far . } // SNIP : Report the result . } catch ( Exception e ) { // SNIP : Report the error . } | What happens when multiple parallel threads await the same Task instance which then throws ? |
C_sharp : I have this list in C # : I can easily print the content of the list with : Now I want to do the same in F # ( I understand from over here that a List < T > is similar to a ResizeArray ) : Now the problem is , that in the for-loop word becomes null . What am I doing wrong here ? EDIT : Here is the full code . I have changed it to printf as suggested . Unfortunately I still get null in word when inside the for-loop : <code> List < string > words = new List < string > { `` how '' , `` are '' , `` you '' } ; foreach ( string word in words ) Debug.WriteLine ( word ) ; let words = ResizeArray < string > ( ) words.Add ( `` how '' ) words.Add ( `` are '' ) words.Add ( `` you '' ) for word in words do Debug.WriteLine ( sprintf `` % s '' word ) let myFunction = let words = ResizeArray < string > ( ) words.Add ( `` how '' ) words.Add ( `` are '' ) words.Add ( `` you '' ) for word in words do printf `` % s '' word // < -- word becomes null words [ < EntryPoint > ] let main argv = ignore myFunction 0 // return an integer exit code | Why ca n't I print this array in F # ? |
C_sharp : I have come across this several times in the last week , and am curious to know the reason - I had a google , but could n't find anything directly relevant.I have a class with a dynamic method , and I can add a static method with the same interface : This is fine , but if I try to call the static method from the dynamic method , replacing # 1 with return MyClass.MyMethod ( ) , I get an error `` The call is ambiguous between the following methods or properties : MyClass.MyMethod ( ) and MyClass.MyMethod ( ) .If the static method is deleted , the error changes to `` An object reference is required.. '' , which makes sense.So why is this ambiguous ? It has been prefaced with the class name to specify the static method , which works from anywhere else in code.Why not here ? EDIT : I had n't actually tried to compile it without the dynamic method calling the static one , I had just gone by VS not underlining it.But still a similar question I suppose but with an added `` Why ca n't there be both , as one is static , and one not '' <code> public class MyClass { public int MyMethod ( ) { //do something # 1 ; } public static int MyMethod ( ) { //do something } } | Method overload static + Dynamic fails |
C_sharp : I was wondering if this code could be improved . The IProvider implements IProvider and overwrites Request ( ... ) . I 'd like to combine these into a single interface . But I still need a typed and untyped interface to work with.Is there a way to combine these where I get both or is this how the interfaces should look ? <code> public interface IProvider { DataSourceDescriptor DataSource { get ; set ; } IConfiguration Configuration { get ; set ; } IResult Request ( IQuery request ) ; } public interface IProvider < T > : IProvider { new IResult < T > Request ( IQuery request ) ; } | Is it possible to define a non-generic interface which can have generic methods ? |
C_sharp : If it helps , the following question is in the context of a game I am building.In a few different places I have the following scenario . There exists a parent class , for this example called Skill , and I have a number of sub-classes implementing the methods from the parent class . There also exists another parent class that we will call Vocation . The skills need to be listed in different sub-classes of Vocation . However , those skills need to be available for anything in the game that uses any given vocation . My current setup is to have an Enum called Skill.Id , so that Vocation contains a collection of values from that Enum and when an entity in the game takes on that Vocation the collection is passed into another class , called SkillFactory . Skill.Id needs a new entry every time I create a new Skill sub-class , as well as a case in the switch block for the new sub-classes ' constructor.i.e . : This works perfectly fine , but using the enum and switch block as a go between feels like more overhead than I need to solve this problem . Is there a more elegant way to create instances of these Skill sub-classes , but still allows Vocation to contains a collection identifying the skills it can use ? Edit : I am fine throwing out the enum and associated switch block , so long as Vocation can contain a collection that allows arbitrary instantiation of the Skill sub-classes . <code> //Skill.IdEnum { FireSkill , WaterSkill , etc } //SkillFactorypublic static Skill Create ( Skill.Id id ) { switch ( id ) { case Skill.Id.FireSkill : return new FireSkill ( ) ; //etc } } | What is a correct way of replacing the switch block and Enum in this situation ( C # ) ? |
C_sharp : I have a class that manages collections of objects e.g . List < Car > and List < Bike > which are atribute . I 'd like to find a way to get a reference to each of those collections in a lookup so I can implement methods such as Add < Car > ( myCar ) or Add ( myCar ) ( with reflection ) and it will add it to the right collection.I tried the following , but .ToList ( ) creates a new list and not a reference , so _lookup [ typeof ( Car ) ] ( ) .Add ( myCar ) is only added to the dictionary list . <code> public class ListManager { private Dictionary < Type , Func < IEnumerable < object > > > _lookup = new Dictionary < Type , Func < IEnumerable < object > > > ( ) ; public ListManager ( ) { this._lookup.Add ( typeof ( Car ) , ( ) = > { return this.Cars.Cast < object > ( ) .ToList ( ) ; } ) ; this._lookup.Add ( typeof ( Bike ) , ( ) = > { return this.Bikes.Cast < object > ( ) .ToList ( ) ; } ) ; } public List < Car > Cars { get ; set ; } public List < Bike > Bikes { get ; set ; } } | Implementing a lookup table that takes T and returns attributes on method of type List < T > |
C_sharp : I would like to know the most efficient way of creating new arrays from the content of other arrays.I have several arrays of strings of the type : It would be possible to create now a new array of string in a similar way to this ? That would contain all the strings included in the other arrays . <code> public readonly string [ ] Taiwan = { `` TW '' , `` TWO '' } ; public readonly string [ ] Vietnam = { `` HM '' , `` HN '' , `` HNO '' } ; public readonly string [ ] Korea = { `` KQ '' , `` KS '' } ; public readonly string [ ] China = { `` SS '' , `` SZ '' } ; public readonly string [ ] Japan = { `` T '' , `` OS '' , `` NG '' , `` FU '' , `` SP '' , `` Q '' , `` OJ '' , `` JNX '' , `` IXJ '' , `` KAB '' , `` JA '' , `` JPx '' } ; public readonly string [ ] ASIA = { Taiwan , Vietnam , Korea , China , Japan } ; | Create new array using content of other arrays in C # |
C_sharp : I want to associate custom data to a Type , and retrieve that data in run-time , blazingly fast.This is just my imagination , of my perfect world : var myInfo = typeof ( MyClass ) .GetMyInformation ( ) ; this would be very fast ... of course this does not exist ! If it did I would not be asking . hehe ; ) This is the way using custom attributes : var myInfo = typeof ( MyClass ) .GetCustomAttribute ( `` MyInformation '' ) ; this is slow because it requires a lookup of the string `` MyInformation '' This is a way using a Dictionary < Type , MyInformation > : var myInfo = myInformationDictionary [ typeof ( MyClass ) ] ; This is also slow because it is still a lookup of 'typeof ( MyClass ) '.I know that dictionary is very fast , but this is not enough ... it is not as fast as calling a method . It is not even the same order of speed.I am not saying I want it to be as fast as a method call . I want to associate information with a type and access it as fast as possible . I am asking whether there is a better way , or event a best way of doing it.Any ideas ? ? Thanks ! EDIT : The typeof ( MyClass ) I mentioned in all of previous snippets , are actualy variable ... I do n't know that it is a specific MyClass type , it could be any type : Type myType = typeFromSomewhere ; i.e . MyClass in this case just says that the class is made by me , and any other types that could come into this situation is also made by me ... so it reads typeof ( One of My Own Classes , that I do n't know witch one is it , but it is mine for sure ) EDIT : CONCLUSIONSome performance results related to dictionaries : Interface Call : Virtual Call : I see that I have under-estimated Dictionaries ! ! ! = ) It seems that Dictionary of Type to anything is 3x to 4x slower than a virtual method call.This is not the case using Dictionary of strings . That ones are 10x to 12x slower than a virtual method call.So I have prooved me wrong ! And , NO I AM NOT MAKING A MISSILE ! ! ! someone has supposed this in a comment bellow = ) Thanks everybody . <code> Dic.buckets | Dic.Count | Dic.Key | Ops ( x17 ) /s | Avg.Time | Min.Time | Max.Time -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - 17519 | 12467 | Type | 1051538 | 0.95μs | 0.86μs | 0.42ms 919 | 912 | Type | 814862 | 1.23μs | 1.14μs | 0.46ms 1162687 | 912 | Type | 1126382 | 0.89μs | 0.81μs | 0.33ms 919 | 912 | Type | 806992 | 1.24μs | 1.16μs | 0.21ms 17 | 17 | Type | 872485 | 1.15μs | 1.06μs | 0.31ms -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - 36353 | 18160 | String | 227520 | 4.40μs | 3.98μs | 0.47ms 919 | 911 | String | 219159 | 4.57μs | 4.14μs | 0.29ms 1162687 | 911 | String | 236384 | 4.23μs | 3.82μs | 0.41ms 919 | 911 | String | 223042 | 4.49μs | 4.10μs | 0.43ms 17 | 17 | String | 229985 | 4.35μs | 3.94μs | 0.28ms ops ( x17 ) /s : 2896001Average : 0.35μsMin : 0.34μsMax : 1.20μs ops ( x17 ) /s : 3115254Average : 0.32μsMin : 0.32μsMax : 0.65μs | What is the most efficient performance-wise way of associating information with a 'Type ' object in .Net ? |
C_sharp : I have these classes : Then I have two generic methods with this signature : Now when I create an instance of Data class and call Add methodThe first generic method is used and generic type Data is correctly inferred.But when I call the same method with a more implemented type object instanceI would expect the second generic method to be invoked , but to my surprise it 's not . If I check generic type constraints on the second one being : The first one matches and the second one as well . And these types are more implemented than simple Data type if that makes any difference.Working exampleHere is a working .Net Fiddle for you to play with.QuestionsWhy is second method not being called because both generic type constraints match and could be inferred ? How can I rewrite my second Add method so type inference would work and wo n't have to explicitly provide these types just to make sure that correct overload is being used ? EditI 've found the answer to my first question in MSDN documentation The compiler can infer the type parameters based on the method arguments you pass in ; it can not infer the type parameters only from a constraint or return value.In my case the first generic type can be inferred directly from parameter , but second one is more tricky . It ca n't be inferred from parameter only . Type constraint should be used , but compiler does n't evaluate it.I also have one possible solution to my second question that changes one type to concrete and keeps the other one generic.But I 'm wondering if there 's a more general/generic way of mitigating around this problem so I can still keep both type parameters but somehow have both types as generic ? <code> /* Data classes */public class Data { public int Id { get ; set ; } } public class InfoData < TInfo > : Data where TInfo : InfoBase { public TInfo Info { get ; set ; } } /* Info classes */public abstract class InfoBase { public int Id { get ; set ; } } public interface IRelated { IList < InfoBase > Related { get ; set ; } } public class ExtraInfo : InfoBase , IRelated { public string Extras { get ; set ; } public IList < InfoBase > Related { get ; set ; } } public TData Add < TData > ( TData data ) where TData : Datapublic TData Add < TData , TInfo > ( TData data ) where TData : InfoData < TInfo > where TInfo : InfoBase , IRelated // data is of type DataAdd ( data ) ; // data is of type InfoData < ExtraInfo > // ExtraInfo is of type InfoBase and implements IRelatedAdd ( data ) ; where TData : InfoData < TInfo > where TInfo : InfoBase , IRelated public InfoData < TInfo > Add < TInfo > ( InfoData < TInfo > data ) where TInfo : InfoBase , IRelated | How does type inference work with overloaded generic methods |
C_sharp : We have a complex XML Structure and really a big one ( > 500 MB ) . the XSD of the structure is : This XSDAs we know this is a complex one . and because of size or non-tab deliminator structure , I could n't convert it to a readable better presentation . I want to read this file via C # and search the drug name . what is wrong via my code ? My error is as follows : How I can search inside this XML and get the information around Drug name ? Update : Sample XMLThe XML StructureWith nice answer of jdweng we want to extract all information . <code> try { XmlReader xmlFile ; xmlFile = XmlReader.Create ( `` C : \\Users\\Dr\\Desktop\\full database.xml '' , new XmlReaderSettings ( ) ) ; DataSet ds = new DataSet ( ) ; ds.ReadXml ( xmlFile ) ; dataGridView1.DataSource = ds.Tables [ 0 ] ; } catch ( Exception ex ) { MessageBox.Show ( ex.ToString ( ) ) ; } | Unstructured XML via non-tab deliminator ? |
C_sharp : I have an ad-hoc reporting system ; I have no compile-time knowledge of the source type of queries or of the required fields . I could write expression trees at runtime using the System.Linq.Expressions.Expression factory methods , and invoke LINQ methods using reflection , but Dynamic LINQ is a simpler solution.The reporting system is to allow for queries which returns the result of a LEFT JOIN . There are fields in the joined table which are NOT NULL in the database ; but because this is a LEFT JOIN , those fields will contain NULL for certain records . The EF6-generated expression falls on this , because the expression projects to a non-nullable value type.If I was doing this in compile-time LINQ , I would explicitly cast to the nullable type : Dynamic LINQ supports explicit conversions : but only a specific set of types can be referenced in the query . If I try to use Color in the query : I get the following error : No applicable method 'Color ' exists in type 'Color'and if I try to explicitly cast to Color ? : I get : Requested value 'Color ' was not found.How can I do this using the Dynamic LINQ library ? <code> enum Color { Red , Green , Blue } // using System ; // using static System.Linq.Enumerable ; // using System.Linq ; var range = Range ( 0 , 3 ) .Select ( x = > ( Color ) x ) .AsQueryable ( ) ; var qry = range.Select ( x = > ( Color ? ) x ) ; // using static System.Linq.Dynamic.Corevar qry1 = range.Select ( `` int ? ( it ) '' ) ; var qry2 = range.Select ( `` Color ( it ) '' ) ; var qry3 = range.Select ( `` Color ? ( it ) '' ) ; | Convert my value type to nullable equivalent |
C_sharp : I am trying to build the source for the .net connector c # in Visual Studio 2017 . I 've tried downloading several versions of the MySQL connector from GitHub ( https : //github.com/mysql/mysql-connector-net/releases ) , but every version has an issue , I 'm not sure what I 'm missing . I tried downloading the latest version 7.0.7-m6 but this throws an error about inconsistent targeting frameworks for a UAP project . I could n't find anything about what that means so I tried one of the previous versions , 6.10.1 and 6.10.0 but both of these have different problems . The error I 'm getting back is There 's tonnes of these types of errors , looking at the directory , these files do n't exist , yet the project is still referencing them . I would have thought importing a project from a GitHub release would just work and a release definetely would n't have files references that do n't exist , so what am I missing . <code> Source file 'Desktop\mysql-connector-net-6.10.0\Source\MySQL.Data\X\XDevAPI\Common\ColumnTypes.cs ' could not be found . | Opening MySQL.Data source from Github source |
C_sharp : I am collecting data from a USB device and this data has to go to an audio output component . At the moment I am not delivering the data fast enough to avoid clicks in the output signal . So every millisecond counts.At the moment I am collecting the data which is delivered in a byte array of 65536 bytes.The first two bytes represent 16 bits of data in little endian format . These two bytes must be placed in the first element of a double array . The second two bytes , must be placed in the first element of a different double array . This is then repeated for all the bytes in the 65536 buffer so that you end up with 2 double [ ] arrays of size 16384.I am currently using BitConverter.ToInt16 as shown in the code . It takes around 0.3ms to run this but it has to be done 10 times to get a packet to send off to the audio output . So the overhead is 3ms which is just enough for some packets to not be delivered on time eventually.CodeHow can I improve this ? Is it possible to copy the values with unsafe code ? I have no experience in that.Thanks <code> byte [ ] buffer = new byte [ 65536 ] ; double [ ] bufferA = new double [ 16384 ] ; double [ ] bufferB = new double [ 16384 ] for ( int i= 0 ; i < 65536 ; i +=4 ) { bufferA [ i/4 ] = BitConverter.ToInt16 ( buffer , i ) ; bufferB [ i/4 ] = BitConverter.ToInt16 ( buffer , i+2 ) ; } | Improve performance of Bitconverter.ToInt16 |
C_sharp : Below is my array : Now in above array , selected property represent check/uncheck status of checkbox and i am posting above array to web service ( WCF ) as string using json.stringify.Above array contains 2000 - 4000 records and now user can check/uncheck checkboxes.Now consider there are 4000 records in above array in which there are 2000 records which are checked and 2000 records are unchecked and in my web service i am processing only those records which are checked.I remove records with selected value as false.Now as due to 4000 records its a huge json string and because of that i get error from web service end : Now reason why i am not filtering out records with selected as flase is because it will create lots of overhead on client browser and can even hang browser so right now i am doing it on server side.So my question is that i should filter out records with selected as false on client side and then post 2000 records only or what i am doing is the right way.I have some question in my mind that posting such huge json string will again take some times and filtering out records with selected as false will also put lots of overhead on browser.So i am not sure i am doing wrong or right.Can anybody please guide me for this ? ? ? <code> var.child.Cars1 = { name : null , operation:0 , selected : false } Error : ( 413 ) Request Entity Too Large | Suggestions on posting huge string to web service |
C_sharp : I 'm trying to get the data for each cells to align correctly with each other , but for one column the contents are not lining up with the others . I 'm not sure why this is , as I have looked over all the default styles and other layout/appearance options and nothing is out of the ordinary . I do n't know if this will help but here is a screenshot of the program running in debug mode.It 's just the email column that is off for some reason . I can try and provide more information if it is required.ThanksI got the rest to line up but still am having trouble with the email columnsIt really is frustrating and makes no sense to me . Would the designer code be useful to take a look at ? I can provide it if need be.Update -I 've noticed its the 4th column ( email ) on each DGV . Everything else lines up right except for the 4th column . Any ideas ? Update 2 - Here is the code that is for the datagridview inside the InitializeComponent method : and the email column ( 4th column ) I put the whole solution on dropbox , if anyone can download it and check it out it would be much appreciated - https : //www.dropbox.com/s/bh5if8b04eshpo9/QBC % 20Members.zip ? dl=0 <code> // // dataGridView// dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft ; dataGridViewCellStyle1.Font = new System.Drawing.Font ( `` Verdana '' , 9.75F , System.Drawing.FontStyle.Regular , System.Drawing.GraphicsUnit.Point , ( ( byte ) ( 0 ) ) ) ; dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True ; this.dataGridView.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1 ; this.dataGridView.AutoGenerateColumns = false ; this.dataGridView.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells ; this.dataGridView.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.AllCells ; this.dataGridView.BackgroundColor = System.Drawing.Color.White ; dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft ; dataGridViewCellStyle2.BackColor = System.Drawing.SystemColors.Control ; dataGridViewCellStyle2.Font = new System.Drawing.Font ( `` Verdana '' , 9.75F , System.Drawing.FontStyle.Regular , System.Drawing.GraphicsUnit.Point , ( ( byte ) ( 0 ) ) ) ; dataGridViewCellStyle2.ForeColor = System.Drawing.SystemColors.WindowText ; dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight ; dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText ; dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.True ; this.dataGridView.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle2 ; this.dataGridView.Columns.AddRange ( new System.Windows.Forms.DataGridViewColumn [ ] { this.idDataGridViewTextBoxColumn , this.firstnameDataGridViewTextBoxColumn , this.lastnameDataGridViewTextBoxColumn , this.phonenumberDataGridViewTextBoxColumn , this.emailaddressDataGridViewTextBoxColumn , this.birthdayDataGridViewTextBoxColumn , this.addressDataGridViewTextBoxColumn , this.marriedDataGridViewTextBoxColumn } ) ; this.dataGridView.DataSource = this.headsBindingSource ; dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft ; dataGridViewCellStyle3.BackColor = System.Drawing.SystemColors.Window ; dataGridViewCellStyle3.Font = new System.Drawing.Font ( `` Verdana '' , 9.75F , System.Drawing.FontStyle.Regular , System.Drawing.GraphicsUnit.Point , ( ( byte ) ( 0 ) ) ) ; dataGridViewCellStyle3.ForeColor = System.Drawing.SystemColors.ControlText ; dataGridViewCellStyle3.SelectionBackColor = System.Drawing.SystemColors.Highlight ; dataGridViewCellStyle3.SelectionForeColor = System.Drawing.SystemColors.HighlightText ; dataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.True ; this.dataGridView.DefaultCellStyle = dataGridViewCellStyle3 ; this.dataGridView.GridColor = System.Drawing.Color.Black ; this.dataGridView.Location = new System.Drawing.Point ( 20 , 63 ) ; this.dataGridView.Name = `` dataGridView '' ; dataGridViewCellStyle4.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft ; dataGridViewCellStyle4.BackColor = System.Drawing.SystemColors.Control ; dataGridViewCellStyle4.Font = new System.Drawing.Font ( `` Verdana '' , 9.75F , System.Drawing.FontStyle.Regular , System.Drawing.GraphicsUnit.Point , ( ( byte ) ( 0 ) ) ) ; dataGridViewCellStyle4.ForeColor = System.Drawing.SystemColors.WindowText ; dataGridViewCellStyle4.SelectionBackColor = System.Drawing.SystemColors.Highlight ; dataGridViewCellStyle4.SelectionForeColor = System.Drawing.SystemColors.HighlightText ; dataGridViewCellStyle4.WrapMode = System.Windows.Forms.DataGridViewTriState.True ; this.dataGridView.RowHeadersDefaultCellStyle = dataGridViewCellStyle4 ; dataGridViewCellStyle5.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft ; dataGridViewCellStyle5.Font = new System.Drawing.Font ( `` Verdana '' , 9.75F , System.Drawing.FontStyle.Regular , System.Drawing.GraphicsUnit.Point , ( ( byte ) ( 0 ) ) ) ; dataGridViewCellStyle5.WrapMode = System.Windows.Forms.DataGridViewTriState.True ; this.dataGridView.RowsDefaultCellStyle = dataGridViewCellStyle5 ; this.dataGridView.RowTemplate.DefaultCellStyle.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft ; this.dataGridView.RowTemplate.DefaultCellStyle.Font = new System.Drawing.Font ( `` Verdana '' , 9.75F , System.Drawing.FontStyle.Regular , System.Drawing.GraphicsUnit.Point , ( ( byte ) ( 0 ) ) ) ; this.dataGridView.RowTemplate.DefaultCellStyle.WrapMode = System.Windows.Forms.DataGridViewTriState.True ; this.dataGridView.RowTemplate.Resizable = System.Windows.Forms.DataGridViewTriState.True ; this.dataGridView.Size = new System.Drawing.Size ( 1028 , 426 ) ; this.dataGridView.TabIndex = 0 ; this.dataGridView.KeyDown += new System.Windows.Forms.KeyEventHandler ( this.dataGridView_KeyDown ) ; // emailaddressDataGridViewTextBoxColumn// this.emailaddressDataGridViewTextBoxColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells ; this.emailaddressDataGridViewTextBoxColumn.DataPropertyName = `` email_address '' ; this.emailaddressDataGridViewTextBoxColumn.HeaderText = `` email_address '' ; this.emailaddressDataGridViewTextBoxColumn.Name = `` emailaddressDataGridViewTextBoxColumn '' ; this.emailaddressDataGridViewTextBoxColumn.Width = 125 ; // | Column cell value in datagridview not aligning with others |
C_sharp : Just wondering , does it matter in which sequence the LINQ methods are added ? Eg.and this are completely the same ? Of course I can have all methods tested one by one , but I 'd like to have some general idea about the logic.So : Other than methods like FirstOrDefault ( ) , ToList ( ) and other methods that really trigger the execution is it of any importance to have some type of order in the LINQ statement ? Thanks again ! <code> using ( MyDataContext context = new MyDataContext ( ) ) { var user = context.Users .Where ( u = > u.UserName.StartsWith ( `` t '' ) ) .OrderByDescending ( u = > u.CreatedDate ) .FirstOrDefault ( ) ; } using ( MyDataContext context = new MyDataContext ( ) ) { var user = context.Users .OrderByDescending ( u = > u.CreatedDate ) .Where ( u = > u.UserName.StartsWith ( `` t '' ) ) .FirstOrDefault ( ) ; } | Sequence of LINQ method of any importance ? |
C_sharp : Here is what I 'm trying to do overall . Just to be clear , this is n't homework or for a contest or anything . Hopefully , I 've made the wording clear enough : ProblemGiven a set of strings in the same format , but where some end in a lowercase letter and some do not , return a set of one of each string that does not end in a lowercase letter , but that has at least one identical string ending in a lowercase letter.ExampleTo keep it simple , let 's say the string format is \d+ [ a-z ] ? , where the common part is the number . Given { 1 , 4 , 3a , 1b , 3 , 6c } , I should receive a permutation of { 1 , 3 } because 1 and 3 have both an element with and without a lowercase letter at the end.Alternate SolutionYou can view this solution here.One way I thought of doing this was to partition the set into elements with and without a lowercase letter suffix ( { 1 , 4 , 3 } and { 3a , 1b , 6c } ) , and then return withoutSuffix.Where ( x = > withSuffix.Any ( y = > y.StartsWith ( x ) ) ) .I have two problems with this : I do n't see a good way to partition into the two sets , with the predicate Regex.IsMatch ( input , `` [ a-z ] $ '' ) . The two I thought of were two similarly-defined variables each using a Where clause and doing the regex matching twice per element , or transforming the set to store the regex match results and then forming the two variables from that . group ... by does n't seem to play well when you need to access both sets like this , but I could be wrong there.Although the size is small enough not to care about performance , going through withSuffix once per withoutSuffix element seems inelegant.Relevant SolutionYou can view this solution here.The other way that came to mind was to grab the common prefix and the optional suffix : { 1 = > { `` '' , b } , 3 = > { a , `` '' } , 4 = > { `` '' } , 6 = > { c } } . This is easily accomplished by capturing the prefix and the suffix with a regex ( ( \d+ ) ( [ a-z ] ) ? ) and grouping the suffix by the prefix into grouped.From here , it would be great to do : Or even : I could certainly create either of these , but unfortunately , the best I can see in LINQ is : It just feels super redundant . Is there anything better than this in LINQ already ? P.S . I 'm open to better approaches to solving the overall problem instead of making this an XY problem . Elegance is desired much more than performance , but ( maybe it 's just me ) being plain wasteful still seems inelegant . <code> where grouped.SomeButNotAll ( x = > x == string.Empty ) select grouped.Key where grouped.ContainsSomeButNotAll ( string.Empty ) select grouped.Key where grouped.Contains ( string.Empty ) & & grouped.Any ( x = > x ! = string.Empty ) select grouped.Key | Is there an elegant LINQ solution for SomeButNotAll ( ) ? |
C_sharp : I have this code , I am concerned that it is `` not safe '' I used Dispose ( ) before the using statement end , for me it is slightly illogical , but it works just fine . So , is it safe ? <code> using ( FileStream stream = new FileStream ( SfilePath , FileMode.Open ) ) { try { XmlSerializer deserializer = new XmlSerializer ( typeof ( HighscoresViewModel ) ) ; HVM = deserializer.Deserialize ( stream ) as HighscoresViewModel ; } catch ( InvalidOperationException ) { stream.Dispose ( ) ; ( new FileInfo ( SfilePath ) ) .Delete ( ) ; HVM = new HighscoresViewModel ( ) ; } } | What happens if I called Dispose ( ) before using statement end ? |
C_sharp : In our external boundaries that expose WCF services , we convert all internal exceptions to FaultException . This is a manual process which often has minor flaws unique to each implementation . It has been copy/pasted and mindlessly modified ( or forgotten ) for each exposed method . To reduce the errors , I wanted to create an aspect which would catch any unhandled exception.We do a mapping of internal exceptions to fault exceptions . How can I send a mapping function to the aspect ? If I add a property to the aspect like this : I can not ( as expected by Attribute restrictions ) initialize it like [ FaultExceptionConverter ( FaultConverter = MyConversionMethod ) ] ( where MyConversionMethod is some method assignable to Func < Exception , FaultException > ) . Is there any pattern for passing this type of parameter to the aspect ? Many types can be passed into aspects . Is this a common problem ? If there happens to be a better way to accomplish this , I would appreciate the advice . <code> [ Serializable ] public sealed class FaultExceptionConverter : OnExceptionAspect { public Func < Exception , FaultException > FaultConverter { get ; set } } | Passing Func < > or similar to PostSharp aspect |
C_sharp : I have an inline lambda expression that I would like to use throughout my application . I just ca n't seem to find a reference on how to do this with more parameters than the element being tested . Here is a quick example of what I currently have.I know the IEnumerable.Where accepts a method with the element type as a parameter and a returning boolean.I would like to pass the Search variable into FindName as well . I just ca n't seem to get the syntax figured accomplish this . The only working solution I 've come up with is passing everything to a function to perform the original statement.Do n't feel obligated to answer in VB . <code> Private Sub Test ( ) Dim List As New List ( Of String ) From { `` Joe '' , `` Ken '' , `` Bob '' , `` John '' } Dim Search As String = `` *Jo* '' Dim Result = List.Where ( Function ( Name ) Name Like Search ) End Sub Private Sub Test ( ) Dim List As New List ( Of String ) From { `` Joe '' , `` Ken '' , `` Bob '' , `` John '' } Dim Search As String = `` *Jo* '' Dim Result = List.Where ( AddressOf FindName ) End SubPrivate Function FindName ( Name As String ) As Boolean Return Name Like `` *Jo* '' End Function Private Sub Test ( ) Dim List As New List ( Of String ) From { `` Joe '' , `` Ken '' , `` Bob '' , `` John '' } Dim Search As String = `` *Jo* '' Dim Result = FindName ( List , Search ) End SubPrivate Function FindName ( List As IEnumerable ( Of String ) , Search As String ) As IEnumerable ( Of String ) Return List.Where ( Function ( Name ) Name Like Search ) End Function | Can I use a Method instead of Lambda expression with extra parameters |
C_sharp : I 've stumbled accross this code in production and I think It may be causing us problems.Calling the Instance field twice returns two objects with the same hash code . Is it possible that these objects are different ? My knowledge of the CLI says that they are the same because the hash codes are the same.Can anyone clarify please ? <code> internal static readonly MyObject Instance = new MyObject ( ) ; | Is the following code a rock solid way of creating objects from a singleton ? |
C_sharp : We can raise event in two ways : and I prefer the last one . It is shorter.My colleagues insist on the first variant.Is there any superiority of the first over the second one ? <code> public event EventHandler MyEvent ; private void DoSomething ( ) { ... var handler = MyEvent ; if ( handler ! = null ) handler ( this , EventArgs.Empty ) ; } public event EventHandler MyEvent = ( o , e ) = > { } ; private void DoSomething ( ) { ... MyEvent ( this , EventArgs.Empty ) ; } | .NET event raising and NullObject pattern |
C_sharp : I have some Action Attributes that allow parameters . This is how it looks like : Now I want to get rid of the magic string `` GetTerms '' in my Attribute . So I would prefer something like : ( Pseudocode , not working ) Having an additional Property inside my attribute-class and doing `` Method2String '' -Conversions inside my that class would be ok with me if this is needed to achieve what I want.Info : I am not looking for a way the get the current method name ( MethodBase.GetCurrentMethod ) <code> [ DeleteActionCache ( Action= '' GetTerms '' ) ] public ActionResult AddTerm ( string term ) { } public ActionResult GetTerms ( ) { } [ DeleteActionCache ( Action=this.GetTerms ( ) .GetType ( ) .Name ) ] | Get action name as string for Attribute-parameter |
C_sharp : I am currently working with json.net ! I know how to deserialize json data and how to map with our class . Now I am eager about some queries ! Suppose my jsonstrings isand my attribute class ( in which i want to deserialize above string ) isNow I am using following code for deserialization . ! And Obviously this code is not going to work for above jsonstring at all.Now How can I bind these name value pair in one class ? ? Is this possible ? In future , attributes may b more than 10 but format will be same as name value pair <code> `` attributes '' : { `` color '' : '' Brown '' , `` condition '' : '' Used '' , `` currency '' : '' USD '' , `` price '' : '' 10500 '' , `` price_display '' : '' $ 10,500 '' , } Public class Attribute { public string name { get ; set ; } public string value { get ; set ; } } JavaScriptSerializer ser = new JavaScriptSerializer ( ) ; < classname > p = ser.Deserialize < classname > ( jsonString ) ; | Is this possible in JSON ? |
C_sharp : I have a design problem I 'd like to solve.I have an interface , lets call it IProtocol , which is implemented by two separate classes . We 're looking at over 600 lines of code here . The vast majority of the stuff they do is the same , except for some specific areas , like DiffStuff ( ) ; Current structure is something like this : AndI 'm concerned with having copy-paste errors and the classic problem of code duplication if I keep the two protocols separate . We 're talking about a full 600 lines of code each , not some simple methods . I 'm considering changing the implementation of Protocol1 to inherit from protocol2 , like this ( Protocol2 would mostly stay the same , except I 'd have to wrap Same1 ( ) and Same2 ( ) into private methods . ) Is this the right way to go about dealing with this problem ? Edit : Many people helped me with this question , thanks for the clear understanding . In my case , the two objects are not of the same type , even though much of their implementation is shared , so I went with Bobby 's suggestion to use abstract base class , creating small methods to encapsulate changes between the classes . Additional Thanks to : jloubertHans PassantJeff Sternal <code> public class Protocol1 : IProtocol { MyInterfaceMethod1 ( ) { Same1 ( ) ; DiffStuff ( ) ; Same2 ( ) ; } } public class Protocol2 : IProtocol { MyInterfaceMethod1 ( ) { Same1 ( ) ; Same2 ( ) ; } } public class Protocol1 : Protocol2 { void Same1 ( ) { base.Same1 ( ) ; } void Same2 ( ) { base.Same2 ( ) ; } MyInterfaceMethod1 ( ) { Same1 ( ) ; DiffStuff ( ) ; Same2 ( ) ; } } | Design Problem - Is Inheritance the right way to simplify this code ? |
C_sharp : I have a method which I 'd like to take all list-like objects in my solution . Before .NET 4.5 , this was simple : However , .NET 4.5 introduced IReadOnlyList < T > , which this method should also apply to.I ca n't just change the signature to take an IReadOnlyList < T > , as there are places where I apply the method to something specifically typed as an IList < T > .The algorithm ca n't run on IEnumerable < T > , and it 's used too frequently ( and with too large objects ) to take an IEnumerable < T > and create a new List < T > on every call.I 've tried adding an overload : ... but this wo n't compile for anything which implements both interfaces ( T [ ] , List < T > , and numerous other types ) , as the compiler ca n't determine which method to use ( particularly annoying as they have the same body , so it does n't matter ) .I do n't want to have to add overloads of Method which take T [ ] , and List < T > , and every other type which implements both interfaces.How should I accomplish this ? <code> public static T Method < T > ( IList < T > list ) { // elided } public static T Method < T > ( IReadOnlyList < T > list ) { // elided } | C # overload resolution with IList < T > and IReadOnlyList < T > |
C_sharp : I have one asynchronous method : Let 's say I also have this class : I now want to create a convenience method producing a BitmapSource output , using the asynchronous method above to do the work . I can come up with at least three approaches to do this , but it is not immediately obvious to me which one I should choose from an efficiency and reliability point of view . Can someone advice ; what are the advantages and drawbacks of each one of the following approaches ? Option A Create a synchronous method that returns the Result of the Task : Option B Create a synchronous ( or is it asynchronous ? ) method that returns Task < BitmapSource > : Option C Create an asynchronous method that explicitly uses await : <code> public async Task < BitmapSource > GetBitmapAsync ( double [ ] pixels ) ; public class PixelData { public double [ ] Pixels { get ; } } public BitmapSource GetBitmap ( PixelData pixelData ) { return GetBitmapAsync ( pixelData.Pixels ) .Result ; } public Task < BitmapSource > GetBitmap ( PixelData pixelData ) { return GetBitmapAsync ( pixelData.Pixels ) ; } public async Task < BitmapSource > GetBitmapAsync ( PixelData pixelData ) { return await GetBitmapAsync ( pixelData.Pixels ) ; } | Recommended method signature when returning output from asynchronous method ? |
C_sharp : I 'm trying to test a really simple function . It returns numbers which contain some specified digit . If the first argument is null , it 'll throw ArgumentNullException.Unfortunately , Assert.Throws says , that the expected exception is n't thrown and the test fails . When I 'm trying to debug the test , it does n't step into my method . The same thing with ArgumentException.Only the two last tests fail , others are successful . My function to be tested : My test class : <code> /// < summary > /// Filter given numbers and return only numbers containing the specified digit . /// < /summary > /// < param name= '' numbers '' > The numbers to be filtered. < /param > /// < param name= '' digit '' > The digit which should be found. < /param > /// < returns > Numbers that contains the digit. < /returns > /// < exception cref= '' ArgumentException '' > Thrown if the digit value is n't between 0 and 9. < /exception > /// < exception cref= '' ArgumentNullException '' > Thrown if numbers are null. < /exception > public static IEnumerable < int > FilterDigits ( IEnumerable < int > numbers , byte digit ) { if ( numbers == null ) { throw new ArgumentNullException ( ) ; } foreach ( int number in numbers ) { if ( number.ContainsDigit ( digit ) ) { yield return number ; } } } /// < summary > /// Check whether the number contains the given digit . /// < /summary > /// < param name= '' number '' > The number which can contain the digit. < /param > /// < param name= '' digit '' > The digit to be found. < /param > /// < returns > True if the number contains the digit , else false. < /returns > /// < exception cref= '' ArgumentException '' > Thrown if the digit value is n't between 0 and 9. < /exception > /// < example > ContainsDigit ( 10 , 1 ) - > true < /example > /// < example > ContainsDigit ( 10 , 2 ) - > false < /example > private static bool ContainsDigit ( this int number , byte digit ) { if ( ! char.TryParse ( digit.ToString ( ) , out char digitChar ) ) { throw new ArgumentException ( `` The digit should be from 0 to 9 . `` ) ; } string numberString = number.ToString ( ) ; foreach ( char ch in numberString ) { if ( ch == digitChar ) { return true ; } } return false ; } [ TestFixture ] public class DigitsFilterTests { [ TestCase ( new int [ ] { 1 , 4 , 23 , 346 , 7 , 23 , 87 , 71 , 77 } , 7 , ExpectedResult = new int [ ] { 7 , 87 , 71 , 77 } ) ] [ TestCase ( new int [ ] { 345 , 4 , 0 , 90 , 709 } , 0 , ExpectedResult = new int [ ] { 0 , 90 , 709 } ) ] public IEnumerable < int > FilterDigits_NumbersContainDigit ( int [ ] numbers , byte digit ) = > DigitsFilter.FilterDigits ( numbers , digit ) ; [ TestCase ( new int [ ] { 1 , 4 , 222 , 9302 } , 7 , ExpectedResult = new int [ ] { } ) ] [ TestCase ( new int [ ] { 345 , 4 , 354 , 25 , 5 } , 0 , ExpectedResult = new int [ ] { } ) ] public IEnumerable < int > FilterDigits_NumbersNotContainDigit ( int [ ] numbers , byte digit ) = > DigitsFilter.FilterDigits ( numbers , digit ) ; [ TestCase ( new int [ ] { } , 0 , ExpectedResult = new int [ ] { } ) ] public IEnumerable < int > FilterDigits_EmptyList ( int [ ] numbers , byte digit ) = > DigitsFilter.FilterDigits ( numbers , digit ) ; [ Test ] public void FilterDigits_NullNumbers_ArgumentNullException ( ) = > Assert.Throws < ArgumentNullException > ( ( ) = > DigitsFilter.FilterDigits ( null , 5 ) ) ; [ Test ] public void FilterDigits_InvalidDigit_ArgumentException ( ) = > Assert.Throws < ArgumentException > ( ( ) = > DigitsFilter.FilterDigits ( new int [ ] { } , 10 ) ) ; } | Assert.Throws method does n't catch the expected exception |
C_sharp : I 'm currently studying for my MS 70-515 exam . In one of the practices the author implements an interface both implicit as well as explicit . The explicit implementation just calls the implicit implementation . The explicit implementation is just listed without an explanation.Does it make sense to have both an implicit and an explicit implementation of the interface ? I would think the explicit implementation is redundant ( in this case ) .BTW , the code seems to run just fine without the explicit implementation , as the implicit implementation is public.It concerns MCTS Self-Paced Training Kit ( Exam 70-515 ) : Web Applications Development with Microsoft .NET Framework 4 Chapter 9 , Lesson 2 , Practice 3 to be precise . <code> public class PassTextBox : TextBox , IScriptControl { public virtual IEnumerable < ScriptDescriptor > GetScriptDescriptors ( ) { var descriptor = new ScriptControlDescriptor ( `` AjaxEnabled.PassTextBox '' , ClientID ) ; // ... return new ScriptDescriptor [ ] { descriptor } ; } IEnumerable < ScriptDescriptor > IScriptControl.GetScriptDescriptors ( ) { return GetScriptDescriptors ( ) ; } } | Does implementing Interface both implicit and explicit make sense ? |
C_sharp : I am creating an application for a shop , where clients are divided into two groups : receivers and payers.1 ) Many receivers can be related to one same payer.2 ) Payer can be receiver itself , thus he is related to one receiver onlyMy code so far look like this : However I need to let the user create a new payer that is also a receiver at the same time , so the Receivers collection will have only one element . To do this I want to use a checkbox , which will be translated to a new column in the database ( IsAlsoReceiver ) .I am using MVC scaffolding for creating views , and it created two views for adding Receiver and another for adding Payer . When a user needs a Payer that is also a receiver he has to add entities in both views ; can that be simplified in this scenario ? I am asking for a smart way to do so . <code> public class Receiver { [ Key ] public int ReceiverId { get ; set ; } public string Name { get ; set ; } [ Required ] public int PayerId { get ; set ; } public virtual Payer Payer { get ; set ; } } public class Payer { [ Key ] public int PayerId { get ; set ; } public string Name { get ; set ; } public virtual ICollection < Receiver > Receivers { get ; set ; } } | How to model this entity |
C_sharp : I have a class that saves logging information to the database ( in an NServiceBus message Handle method ) . Most of the time that logging can be done on a separate thread ( and transaction ) from the main process . But it all needs to be done on the same background thread ( meaning that they have to be done in order , just not in sync with the main process ) .However , once it starts Foreign Keying to the actual data from NServiceBus , it needs to be on the same thread . Here is some example code : I am wondering if there is a way to use my transaction conditional to also conditionally move the running to a different thread . ( But only when it suppresses the transaction . ) <code> public class MyExample { public void LogSomeStuff ( Stuff stuff ) { using ( MoveOutsideTransaction ( ) ) { // Do Method Stuff here dataAccess.SaveChanges ( ) ; } } public void LogSomeOtherStuff ( Stuff stuff ) { using ( MoveOutsideTransaction ( ) ) { // Do Other Method Stuff here dataAccess.SaveChanges ( ) ; } } private IDisposable MoveOutsideTransaction ( ) { if ( loggingOutsideTransaction ) return new TransactionScope ( TransactionScopeOption.Suppress ) ; return null ; } } | Conditionally run the methods of a class on a separate thread |
C_sharp : I have a small program which creates Excel files from a database table , with Excel 2013 it works all fine , but i Need it now for Excel 2010 and now I get the following exception when i will add the `` Format '' to the NumberFormatLocal ( range.NumberFormatLocal = format ; ) The same exception will come when I use the range.NumberFormat = format ; Exception : Error message : System.Runtime.InteropServices.COMException ( 0x80020005 ) : Type Conflict . ( Exception of HRESULT : 0x80020005 ( DISP_E_TYPEMISMATCH ) ) At System.RuntimeType.ForwardCallToInvokeMember ( String memberName , BindingFlags flags , ObjectTarget , Int32 [ ] aWrapperTypes , MessageData & msgData ) function : My Excel Types : Update : I 've tried to use already the public const string TEXT = `` @ '' ; as only format but the same error comesUpdate 2 : The error only occurs if the table has to many entrys . When I use for example a table with 1000 entrys its no problem and all works fine , if i use a table with 200.000 entrys the error occursUpdate 3 : [ I 've tried to use only the standard format for testing , the following error occurs : Error message : System.OutOfMemoryException : Insufficient memory available to continue the program . <code> if ( chkWithValues.Checked & & results.Item3.Any ( ) ) { var rows = results.Item3.Count ; var cols = results.Item3.Max ( x = > x.Count ) ; object [ , ] values = new object [ rows , cols ] ; object [ , ] format = new object [ rows , cols ] ; //All returned items are inserted into the Excel file //Item2 contains the database types , Item3 the Values // pgMain shows the progress for the selected tables for ( int j = 0 ; j < results.Item3.Count ( ) ; j++ ) { int tmpNbr = 1 ; SetMessage ( $ '' { selectedTableItem.TableName } { j } von { results.Item3.Count } '' , LogHelper.NotificationType.Information ) ; foreach ( string value in results.Item3 [ j ] ) { values [ j , tmpNbr - 1 ] = Converter.Convert ( results.Item2 [ tmpNbr - 1 ] , value ) .ToString ( ) .Replace ( `` ' '' , `` '' ) ; format [ j , tmpNbr - 1 ] = ExcelColumnTypes.ConvertToExcelTypes ( results.Item2 [ tmpNbr - 1 ] ) ; tmpNbr++ ; } pgMain.Maximum = results.Item3.Count ( ) ; pgMain.PerformStep ( ) ; } Excel.Range range = xlWorksheet.Range [ `` A3 '' , GetExcelColumnName ( cols ) + ( rows + 2 ) ] ; SetMessage ( $ '' { results.Item3.Count * results.Item1.Count } Zellen werden formatiert ... . '' , LogHelper.NotificationType.Information ) ; range.NumberFormatLocal = format ; range.Value = values ; } public const string INT = `` 0 '' ; public const string TEXT = `` @ '' ; public const string GENERAL = `` General '' ; public const string STANDARD = `` Standard '' ; public const string Date1 = `` m/d/yyyy '' ; public const string DATE2 = `` TT.MM.JJJJ '' ; public const string DATE3 = `` T.M.JJ h : mm ; @ '' ; public const string DATETIME = `` d/m/yy h : mm ; @ '' ; public const string DOUBLECO1 = `` # . # # 0,00 '' ; public const string DOUBLECO2 = `` 0,00 '' ; public const string DOUBLEPO1 = `` # 0 , # # 0.00 '' ; public const string DOUBLEPO2 = `` 0.00 '' ; public const string CUSTOM = `` # , # # 000 '' ; public const string CURRENCYEU1 = `` # , # # 0,00 _€ '' ; public const string CURRENCYEU2 = `` # , # # 0 _€ '' ; public const string CURRENCYEU3 = `` # , # # 0,00 € '' ; public const string CURRENCYDO1 = `` # , # # 0.00 _ $ '' ; public const string CURRENCYDO2 = `` # , # # 0 _ $ '' ; public const string CURRENCYDO3 = `` # , # # 0.00 $ '' ; public const string PERCENTAGE1 = `` 0.00 % '' ; public const string PERCENTAGE2 = `` 0.0 % '' ; public const string PERCENTAGE3 = `` 0 % '' ; | excel 2010 Type Conflict NumberFormat |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.