text
stringlengths
46
37.3k
title
stringlengths
12
162
C_sharp : The lead developer says that when he uses my app , his keyboard beeps when he moves between TextBoxes on the TableLayoutPanel via the directional arrow keys.However , I hear no such aural activity . Here 's my code : ..He thought maybe I needed `` e.Handled '' but that is not available in the PreviewKeyDown event.Is there a way to suppress the beeping ( which apparently occurs only with certain keyboards or specific setups ( he 's using Windows7 , I 'm on XP still ) ) ? UPDATEI 've got this code now : ... but he still hears the beeping ( I do n't ) .He 's in Alaska and using Windows 7 ; I 'm in California and using XP . I do n't know if some combination/mismatch there is the problem ... UPDATED AGAINI know this may be shocking to some , but the Alaska/California disconnection has nothing to do with it . I 'm now hearing the beeps , too , and it 's not from the arrow keys . It 's when a value is entered in a TextBox and then , if that text box already has a character , focus is moved to the next textBox and the value is entered there ( this is my code that causes this to happen ) . But the irritating beeping seems to be random - I have n't figured out the pattern for when it beeps ( sometimes it does , sometimes it does n't ) ... has anybody ever run across anything like that , or , better yet , know how to suppress the beep ? All I 'm doing is pressing either the `` 1 '' or the `` 2 '' key above the keyboard . <code> // Had to intercept Up and Down arrows from Windowsprivate void textBoxPlatypi_PreviewKeyDown ( object sender , PreviewKeyDownEventArgs e ) { TextBox tb = ( TextBox ) sender ; if ( e.KeyCode.Equals ( Keys.Up ) ) { SetFocusOneRowUp ( tb.Name ) ; return ; } if ( e.KeyCode.Equals ( Keys.Down ) ) { SetFocusOneRowDown ( tb.Name ) ; return ; } } private void textBoxPlatypi_KeyDown ( object sender , KeyEventArgs e ) { TextBox tb = ( TextBox ) sender ; if ( e.KeyCode.Equals ( Keys.Left ) ) { SetFocusOneColumnBack ( tb.Name ) ; e.Handled = true ; return ; } if ( e.KeyCode.Equals ( Keys.Right ) ) { SetFocusOneColumnForward ( tb.Name ) ; e.Handled = true ; return ; } } private void textBoxPlatypus1_PreviewKeyDown ( object sender , PreviewKeyDownEventArgs e ) { switch ( e.KeyCode ) { case Keys.Down : case Keys.Up : e.IsInputKey = true ; break ; } } private void textBoxPlatypus1_KeyDown ( object sender , KeyEventArgs e ) { TextBox tb = ( TextBox ) sender ; if ( e.KeyCode.Equals ( Keys.Up ) ) { SetFocusOneRowUp ( tb.Name ) ; e.Handled = true ; return ; } if ( e.KeyCode.Equals ( Keys.Down ) ) { SetFocusOneRowDown ( tb.Name ) ; e.Handled = true ; return ; } if ( e.KeyCode.Equals ( Keys.Left ) ) { SetFocusOneColumnBack ( tb.Name ) ; e.Handled = true ; return ; } if ( e.KeyCode.Equals ( Keys.Right ) ) { SetFocusOneColumnForward ( tb.Name ) ; e.Handled = true ; return ; } }
Are some keyboards more loquacious than others ?
C_sharp : Why does the following fail to infer R : While pretty much the 'same ' , works : Usage : Ways the first sample 'must ' be called to compile : -- or -- Thoughts : As can be seen in the second snippet , R is already determined by the return type of the 'lambda ' . Why ca n't the same apply to the first ? Even with usage of ec ( which should be another compiler hint ) , it fails to infer . <code> static R Foo < R > ( Func < Action < R > , R > call ) { ... } static R Foo < R > ( Func < Action , R > call ) { ... } var i = Foo ( ec = > -1 ) ; var i = Foo < int > ( ec = > -1 ) ; var i = Foo ( ( Action < int > ec ) = > -1 ) ;
Type inference fails mysteriously
C_sharp : I was looking through What 's the strangest corner case you 've seen in C # or .NET ? , and this code made me think a little : I do understand what the code does , but I do not understand why it works . Is n't that like doing null.Foo ( ) ? It works as if Foo ( ) is static , and this is being called instead : Strange.Foo ( ) ; .Would you please tell me what I am missing ? <code> public class Program { delegate void HelloDelegate ( Strange bar ) ; [ STAThread ( ) ] public static void Main ( string [ ] args ) { Strange bar = null ; var hello = new DynamicMethod ( `` ThisIsNull '' , typeof ( void ) , new [ ] { typeof ( Strange ) } , typeof ( Strange ) .Module ) ; ILGenerator il = hello.GetILGenerator ( 256 ) ; il.Emit ( OpCodes.Ldarg_0 ) ; var foo = typeof ( Strange ) .GetMethod ( `` Foo '' ) ; il.Emit ( OpCodes.Call , foo ) ; il.Emit ( OpCodes.Ret ) ; var print = ( HelloDelegate ) hello.CreateDelegate ( typeof ( HelloDelegate ) ) ; print ( bar ) ; Console.ReadLine ( ) ; } internal sealed class Strange { public void Foo ( ) { Console.WriteLine ( this == null ) ; } } }
Why does this work ? Executing method from IL without instance
C_sharp : What is the purpose of allowing the following ? How is this meaningfully different from just declaring A to require an IFoo wherever it needs one ? The only difference that I can see is that in the first case I 'm guaranteed both that A < T > will always be instantiated with a T that implements IFoo and that all of the objects in A will be of the same base type . But for the life of me I ca n't figure out why I 'd need such a constraint . <code> class A < T > where T : IFoo { private T t ; A ( T t ) { this.t = t ; } /* etc */ } class A { private IFoo foo ; A ( IFoo foo ) { this.foo = foo ; } /* etc */ }
What is the purpose of constraining a type to an interface ?
C_sharp : I have a DataGrid view1 and a ListView and when ever I select the list view item ( I am passing the ListView item into the query and populating the DataGrid view according that item ) I have wrote some code like this ... .I have done it like above ... I think this is not an efficient way to do the coding . and this code consisits of a lot of repeated lines , is there any way to refractor this code to a small bunch of code ... ... in order improve the efficiency ? Any ideas and sample snippets for increasing code efficiency would be helpful to me ... Many thanks in advance ... .I am using c # and writting WinForms applications ... .. <code> private void listview_selectedindexchanged ( object sender event args ) { if ( listview.SelectedItems.Count > 0 & & listview.SelectedItems [ 0 ] .Group.Name == `` abc '' ) { if ( lstview.SelectedItems [ 0 ] .Text.ToString ( ) == `` sfs '' ) { method1 ( ) ; } else { // datagrid view1 binding blah ... .. } } if ( lstview.SelectedItems.Count > 0 & & lstview.SelectedItems [ 0 ] .Group.Name == `` def '' ) { if ( lstview.SelectedItems [ 0 ] .Text.ToString ( ) == `` xyz '' ) { method 1 ( ) ; } if ( lstview.SelectedItems [ 0 ] .Text.ToString ( ) == `` ghi '' ) { method 2 ( a , b ) ; } if ( lstview.SelectedItems [ 0 ] .Text.ToString ( ) == `` jkl '' ) { method 2 ( c , d ) ; } if ( lstview.SelectedItems [ 0 ] .Text.ToString ( ) == `` mno '' ) { method 3 ( ) ; } } } private void method 1 ( ) { // datagrid view1 binding blahh } private void method 2 ( e , g ) { // datagrid view1 binding blah ... .blah.. } private void method 3 ( ) { // datagrid view1 binding }
how to avoid the repeated code to increase the efficiency
C_sharp : The following works as expected : but if I combine the if statements like so : then I receive a compiler warningUse of unassigned local variable ' i'Can anyone explain why this happens ? <code> dynamic foo = GetFoo ( ) ; if ( foo ! = null ) { if ( foo is Foo i ) { Console.WriteLine ( i.Bar ) ; } } if ( foo ! = null & & foo is Foo i ) { Console.WriteLine ( i.Bar ) ; }
Error combining 'if ' statements that null-checks and Pattern Matches
C_sharp : Have a look at the following that demonstrates my issue with Visual Studio 2017 compilerWhen I make a breakpoint inside the PrintFoo method and want to look at the Key property of foo Visual Studio wont provide a tooltip for me.By adding the foo.Key to the watch window I receive the following error : error CS1061 : 'T ' does not contain a definition for 'Key ' and no extension method 'Key ' accepting a first argument of type 'T ' could be found ( are you missing a using directive or an assembly reference ? ) When I change the generic declaration to Foo instead of IFoo the compiler can acces the 'Key ' property , so this : Is there a way to make it work ? Edit : Both , looking at the local window and mouse over foo to get the tooltip and than expanding the properties works.Adding foo.Key to the watch window or writing ? foo.Key into immediate window brings the mentioned error , and you wont get a tooltip when you mouse over Key of foo.KeyTested with Visual Studio 2015 , 2017 . <code> public interface IFoo { string Key { get ; set ; } } public class Foo : IFoo { public string Key { get ; set ; } } class Program { static void Main ( string [ ] args ) { PrintFoo ( new Foo ( ) { Key = `` Hello World '' } ) ; Console.ReadLine ( ) ; } private static void PrintFoo < T > ( T foo ) where T : IFoo { //set breakpoint here and try to look at foo.Key Console.WriteLine ( foo.Key ) ; } } private static void PrintFoo < T > ( T foo ) where T : Foo { //set breakpoint here and try to look at foo.Key Console.WriteLine ( foo.Key ) ; }
Compiler doesnt recognise property in generic if declaration is an interface
C_sharp : I 'm working on an ASP.NET Web API project in which I had an issue where the child Tasks which run asynchronously were not inheriting the the current culture of the parent thread ; i.e. , even after setting the Thread.CurrentThread.CurrentUICulture in the controller constructor , any Task created within the action was having the invariant culture by default unless I set it separately . This seems to have fixed in framework > 4.0 and was working fine after upgrading the target framework from 3.5.2 to 4.6.2 as mentioned here . Starting with apps that target the .NET Framework 4.6 , the calling thread 's culture is inherited by each task , even if the task runs asynchronously on a thread pool thread.Now that the culture inheritance in the Tasks are working as expected , I 'm facing another weird issue which was not present in 4.5.2 . If the WebApi action result is of type IEnumerable , then the result will have the default culture in it . Maybe the issue could be better explained using a sample code snippet : Please note that I 'm setting the UI culture as `` ar-AE '' in the constructor . PFB the results : framework 4.5.2 - The Culture of all employees will be ar-AE as expectedframework 4.6.2 - The Culture of all employees will be en-US ( default ) framework 4.6.2 by doing a .ToList ( ) in the result ( calling BuildEmployees ( false ) instead of BuildEmployees ( true ) in the above code ) - The Culture of all employees will be ar-AE as expectedI did had some research and saw answers which suggests to set the NoAsyncCurrentCulture switch , for eg , by adding the switch in the app settings < add key= '' appContext.SetSwitch : Switch.System.Globalization.NoAsyncCurrentCulture '' value= '' true '' / > - but this will kinda rollback to the behavior we had in < 4.0 and will cause the issue with the culture inheritance in the Tasks as mentioned in the first para.What am I missing ? Update : Verified that the context culture is not getting inherited in the thread where the ( JSON/XML ) serialization is happening in Web API . <code> public SampleController ( ) { System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo ( `` ar-AE '' ) ; } [ Route ] public IHttpActionResult Get ( ) { IEnumerable < Employee > employeesDeferred = BuildEmployees ( true ) ; return Ok ( employeesDeferred ) ; } private IEnumerable < Employee > BuildEmployees ( bool isDeferred ) { var employees = Enumerable.Range ( 0 , 2 ) .Select ( count = > new Employee { Id = count++ , Culture = Thread.CurrentThread.CurrentUICulture.Name } ) ; if ( isDeferred ) { return employees ; } return employees.ToList ( ) ; }
ASP.NET CurrentUICulture behaves differently in Task and WebAPI deferred result
C_sharp : I am new to C # and still learning the threading concept . I wrote a program which is as followsI am expecting an output like : -as I believe that both main thread and newly created thread should be executing simultaneously.But the output is ordered , first the prnt function is called and then the Main method for loop is executed . <code> using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; using System.Threading ; namespace ConsoleApplication17 { class Program { static void Main ( string [ ] args ) { System.Threading.ThreadStart th1 = new System.Threading.ThreadStart ( prnt ) ; Thread th = new Thread ( th1 ) ; th.Start ( ) ; bool t = th.IsAlive ; for ( int i = 0 ; i < 10 ; i++ ) { Console.WriteLine ( i + `` A '' ) ; } } private static void prnt ( ) { for ( int i = 0 ; i < 10 ; i ++ ) { Console.WriteLine ( i + `` B '' ) ; } } } } 1A2A1B3A2B ...
Threading concept in C #
C_sharp : I 'm trying to learn Expressions , mainly for my own education . I am trying to work out how to build up an Expression that would represent something more complex than things like a+b and so on.I 'll take this step by step , so you can see how I 'm building it up . Please feel free to comment on any aspect of my approach , although the actual question comes on the third code block.I understand how to make a function that divides the input by 2 : I have also worked out how to make an expression that computes sin ( x ) : What I would like to do now is create an expression that computes sin ( x/2 ) . I can do this like this ... ... but ideally I would like to reuse my existing sine expression , rather than creating a new one.I 'm sure this is straightforward , but to a newbie in this area , I 'm finding it quite difficult . Anyone able to show me how to do this ? I 've looked through the Expression class , but have obviously overlooked the method that I need . <code> // Set up a parameter for use belowParameterExpression x = Expression.Parameter ( typeof ( double ) , `` x '' ) ; Expression two = Expression.Constant ( ( double ) 2 ) ; Expression halve = Expression.MakeBinary ( ExpressionType.Divide , x , two ) ; // Test itdouble halfOfTwenty = Expression.Lambda < Func < double , double > > ( halve , x ) .Compile ( ) ( 20 ) ; Expression sine = Expression.Call ( typeof ( Math ) .GetMethod ( `` Sin '' ) , x ) ; // Test itdouble sinePiOverTwo = Expression.Lambda < Func < double , double > > ( sine , x ) .Compile ( ) ( Math.PI / 2 ) ; Expression sineOfHalf = Expression.Call ( typeof ( Math ) .GetMethod ( `` Sin '' ) , halve ) ;
How do I reuse an Expression when building a more complex one ?
C_sharp : I started this question with a load of background of the types in question ; the interfaces and rationale behind the architecture.Then I realised - 'This is SO - keep it simple and get to the point'.So here goes.I have a class like this : .Net then , of course , allows me to do this : However , in the context of AGenericType < T > 's usage , it is a nonsense to do this in the same way that it 's a nonsense to do this : What I want to be able to do is restrict this generic type so that it becomes impossible to create such an instance or even declare a reference to the type when it 's T is derived from AGenericTypeBase - preferably at compile-time.Now an interesting thing here is that the Nullable < T > example I give here does indeed generate a compiler error . But I ca n't see how Nullable < T > restricts the T to non-Nullable < T > types - since Nullable < T > is a struct , and the only generic constraint I can find ( even in the IL , which often yields compiler secrets , like those with delegates ) is where T : struct . So I 'm thinking that one must be a compiler hack ( EDIT : See @ Daniel Hilgarth 's answer + comments below for a bit of an exploration of this ) . A compiler hack I ca n't repeat of course ! For my own scenario , IL and C # do n't allow a negative-assert constraint like this : ( note the ' ! ' in the constraint ) But what alternative can I use ? I 've thought of two:1 ) Runtime exception generated in the constructor of an AGenericType < T > : That does n't really reflect the nature of the error , though - because the problem is the generic parameter and therefore the whole type ; not just that instance.2 ) So , instead , the same runtime exception , but generated in a static initializer for AGenericType < T > : But then I 'm faced with the problem that this exception will be wrapped inside a TypeInitializationException and could potentially cause confusion ( in my experience developers that actually read a whole exception hierarchy are thin on the ground ) .To me , this is a clear case for 'negative assertion ' generic constraints in IL and C # - but since that 's unlikely to happen , what would you do ? <code> public class AGenericType < T > : AGenericTypeBase { T Value { get ; set ; } } AGenericType < AGenericType < int > > v ; Nullable < Nullable < double > > v ; public class AGenericType < T > : where ! T : AGenericTypeBase public AGenericType ( ) { if ( typeof ( AGenericBase ) .IsAssignableFrom ( typeof ( T ) ) ) throw new InvalidOperationException ( ) ; } static AGenericType ( ) { if ( typeof ( AGenericBase ) .IsAssignableFrom ( typeof ( T ) ) ) throw new InvalidOperationException ( ) ; }
Prevent a particular hierarchy of types being used for a generic parameter
C_sharp : I am writing a chess game which allows two programs compete , the player needs to write a DLL and expose a function to tell the main application where his player will move next , suppose the function looks like thisThe player 's DLL can be written using C # or C++.In the chess game application , I start a new thread to call the function that the player 's DLL exposed to get where he will move in a turn , and I start a timer to prevent the player timeouts , if a player timesout i will kill the corresponding thread by following APIsI have the following issues as described below : The thread can not be killed with 100 % assurance ( it depends on the player 's code ) During test I found that , if the player uses a deep recursions ( and if there is memory leak in the player 's program ) , the memory usage of the host application will increase and then the host application will be terminated without any exceptions.Are there any techniques , ideas or methods that can handle the above issues ? From this CodeInChaos suggested to load player 's DLL into separate domain and then unload it when necessary , I am not sure if it still works for the unmanaged DLL ( C++ ) and if it will cause a low efficiency ? <code> public static void MoveNext ( out int x , out int y , out int discKind ) ; thread.Abort ( ) ; thread.Join ( ) ;
How to host Plug-ins safely with .NET 2.0
C_sharp : I 've a ScreenLocker winform application . It 's full-screen and transparent . It unlocks the screen when user presses Ctrl+Alt+Shift+P.But I want it more dynamic . I would like to let a user set his own password in a config file . For example , he set his password mypass . My problem is- how can I track whether he typed 'mypass ' on that form ? I do n't want to have any textbox or button on the form . Help please.Here is my current code- <code> public frmMain ( ) { InitializeComponent ( ) ; this.KeyPreview = true ; this.WindowState = FormWindowState.Normal ; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None ; this.Bounds = Screen.PrimaryScreen.Bounds ; this.ShowInTaskbar = false ; double OpacityValue = 4.0 / 100 ; this.Opacity = OpacityValue ; } private void OnKeyDown ( object sender , KeyEventArgs e ) { if ( e.KeyCode == Keys.P & & e.Modifiers == ( Keys.Control | Keys.Shift | Keys.Alt ) ) { this.Close ( ) ; } }
Track whether a user typed an specific `` word '' on an WinForm
C_sharp : I have a Types project where I define custom class objects that I want to work on in my main application . The objects are basically derived from strings and parsed into a structure . I have two problems1 - In a separate project I have a File reader class where I scan text files for the string types I have defined . For example by regular expression . Currently I added my Types project as a project reference and I just list the regular expressions at the top of my read class . When i find a type I convert the string to the appropriate type . However how can i improve this so that is it directly connected to my Types project - so when i update it with new types the Read class knows that it should support the new types ? 2 - I 'm trying to create a DLL that works on these specific types after they are read from the text file . How do I tell my DLL that I want to support the types in my Types project ? Do I have to make an overloaded function for each type I want to work on ? Do I use an interface ? Any advice is greatly appreciated.EDIT : Added example code of what I '' m trying to do//PROJECT 1 - handles IO operation like Reading and writing//function in read class job is to find one of several predefined string types by regular expression ... once found they are converted to the data structure ( by passing string to constructor of type class defined in the other project//PROJECT 2 - contains classes that define the types//TYPE1 //TYPE 2//PROJECT 3//PROJECT 4 -- MAIN PROJECT with GUI <code> public class Read { public string [ ] FileList { get ; set ; } private static Int64 endOffset = 0 ; private FileStream readStream ; private StreamReader sr ; private System.Text.RegularExpressions.Regex type1 = new System.Text.RegularExpressions.Regex ( @ '' @ 123 : test '' ) ; private System.Text.RegularExpressions.Regex type2 = new System.Text.RegularExpressions.Regex ( @ '' TESTTYPE2 '' ) ; public Read ( string [ ] fl ) { FileList = fl ; } public object ReturnMessage ( FileStream readStream , out int x ) { //readStream = new FileStream ( file , FileMode.Open , FileAccess.Read ) ; x = 0 ; //endOffset = 0 ; bool found = false ; char ch ; string line = string.Empty ; object message = null ; while ( ! ( x < 0 ) ) //do this while not end of line ( x = -1 ) { readStream.Position = endOffset ; //line reader while ( found == false ) //keep reading characters until end of line found { x = readStream.ReadByte ( ) ; if ( x < 0 ) { found = true ; break ; } // else if ( ( x == 10 ) || ( x == 13 ) ) if ( ( x == 10 ) || ( x == 13 ) ) { ch = System.Convert.ToChar ( x ) ; line = line + ch ; x = readStream.ReadByte ( ) ; if ( ( x == 10 ) || ( x == 13 ) ) { ch = System.Convert.ToChar ( x ) ; line = line + ch ; found = true ; } else { if ( x ! = 10 & & ( x ! = 13 ) ) { readStream.Position -- ; } found = true ; } } else { ch = System.Convert.ToChar ( x ) ; line = line + ch ; } } //while - end line reader //examine line ( is it one of the supported types ? ) if ( type1.IsMatch ( line ) ) { message = line ; endOffset = readStream.Position ; break ; } else { endOffset = readStream.Position ; found = false ; line = string.Empty ; } } //while not end of line return message ; } } namespace MessageTypes.Type1 { public sealed class Type1 { public List < Part > S2 { get ; set ; } public Type1 ( string s ) { S2 = new List < Part > ( ) ; string [ ] parts = s.Split ( ' : ' ) ; for ( int i = 0 ; i < parts.Length ; i++ ) { S2.Add ( new Part ( parts [ i ] ) ) ; } } } public sealed class Part { public string P { get ; set ; } public Part ( string s ) { P = s ; } } } namespace MessageTypes.Type2 { public sealed class FullString { public string FS { get ; set ; } public FullString ( string s ) { FS = s ; } } } class DoSomethingToTypeObject { //detect type and call appropriate function to process } public partial class MainWindow : Window { public MainWindow ( ) { InitializeComponent ( ) ; } private void button1_Click ( object sender , RoutedEventArgs e ) { if ( tabControl1.SelectedIndex == 0 ) //Processing Mode 1 { //load file list from main window - Mode1 tab IOHandler.Read read = new IOHandler.Read ( new string [ 2 ] { @ '' C : \file1.txt '' , @ '' C : \file2.txt '' } ) ; //read files foreach ( string file in read.FileList ) { //while not end of stream myobject = read.ProcessFile ( file ) ; DoSomethingtoTypeObject DS = new DoSomethingtoTypeObject ( myobject ) ; //write transoformed object write ( myobject ) ; } } } }
How to support multiple custom types ?
C_sharp : If a float is assigned to a double , it accepts it , but if the float is first assigned to an object and then cast to double , it gives an InvalidCastException.Can someone please clarify this ? <code> float f = 12.4f ; double d = f ; //this is ok//but if f is assigned to objectobject o = f ; double d1 = ( double ) o ; //does n't work , ( System.InvalidCastException ) double d2 = ( float ) o ; //this works
Why ca n't an object which holds a float value be cast to double ?
C_sharp : I have a XAML form that I would like two independent features threaded out of the main XAML execution thread : 1 . ) a timer control that ticks up , and 2 . ) implement a pause button so I can freeze a set of procedural set of activities and clicking on the pause button again will resume.When I start the form , the entire app freezes . Because of this I ca n't interact with btnPause control . I got the timer class to work , but it ( lblTimer ) updates in chunks , or whenver it looks like the CPU is n't busy on the main thread.I tried to create a class `` Task '' that wraps a class or method in its own thread so I can control . Later on , I attempted to create a stopwatch class and assign the TimerThread to it so I can manage it independently.The timer appears to work , but it still spits updates in chunks - does this mean it 's not on its own thread ? <code> Automation.Task AutomationThread = new Automation.Task ( ) ; Automation.Task TimerThread = new Automation.Task ( ) ; Automation.WatchTimer stopwatch = new Automation.WatchTimer ( lblTimer , TimerThread ) ; class Task { private ManualResetEvent _shutdownFlag = new ManualResetEvent ( false ) ; private ManualResetEvent _pauseFlag = new ManualResetEvent ( true ) ; Thread _thread ; public Task ( ) { } public void Start ( ) { _thread = new Thread ( DoWork ) ; _thread.Start ( ) ; } public void Resume ( ) { _pauseFlag.Set ( ) ; } public void Stop ( ) { _shutdownFlag.Set ( ) ; _pauseFlag.Set ( ) ; _thread.Join ( ) ; } public void DoWork ( ) { do { _pauseFlag.WaitOne ( Timeout.Infinite ) ; } while ( ! _shutdownFlag.WaitOne ( 0 ) ) ; } // I AM NOT SURE IF THIS IS THE RIGHT APPROACH public void DoWork ( Func < void > method ? ? ? ? ) { do { // NOT SURE WHAT TO PUT HERE // This is where I want it to do a method // that wraps a long chain of procedural items // where I can pause ( block ) and unpause through the UI } while ( ! _shutdownFlag.WaitOne ( 0 ) ) ; } class WatchTimer { public WatchTimer ( System.Windows.Controls.Label lbl , Automation.Task worker ) { lblField = lbl ; worker.Start ( ) ; } private System.Windows.Controls.Label lblField ; Timer time = new Timer ( ) ; Stopwatch sw = new Stopwatch ( ) ; public void Start ( ) { time.Start ( ) ; sw.Start ( ) ; time.Tick += new EventHandler ( time_Tick ) ; } public void Stop ( ) { time.Stop ( ) ; sw.Stop ( ) ; } public void Reset ( ) { sw.Reset ( ) ; lblField.Content = this.elapsedTime ( ) ; } public string elapsedTime ( ) { TimeSpan ts = sw.Elapsed ; // return formatted TimeSpan value return String.Format ( `` { 0:00 } : { 1:00 } : { 2:00 } . { 3:00 } '' , ts.Hours , ts.Minutes , ts.Seconds , ts.Milliseconds ) ; } private void time_Tick ( object sender , EventArgs e ) { lblField.Content = this.elapsedTime ( ) ; } }
Is it possible to wrap specific classes or methods and assign them to a thread ?
C_sharp : In the code below , Resharper gives me a warning : Can not cast expression of type 'Color ' to type 'UIntPtr ' . ( Actually , Resharper thinks it 's an actual error . ) However , there is no compiler warning and it works fine.This looks like a Resharper bug to me . Is it ? Or is there something bad about it that the compiler is n't worrying about ? ( I 'm using Resharper 7.1.1 ) I can make the warning go away by casting the value to an int first , so I have a workaround : <code> using System ; namespace Demo { internal class Program { public enum Color { Red , Green , Blue } private static void Main ( string [ ] args ) { UIntPtr test = ( UIntPtr ) Color.Red ; // Resharper warning , no compile warning . } } } UIntPtr test = ( UIntPtr ) ( int ) Color.Red ;
Resharper warning casting enum to UIntPtr , but no compiler warning
C_sharp : I am creating plugins for a software called BIM Vision . They have a wrapper around a C API and thus I am using UnmanagedExports to have my unmanaged DLL compiled fine with the wrapper.Issue is that I can not use NuGet librairies at all in my project . They compile fine but calling any of their functions in my code crashes the software.All the libraries are compiled in their own separate DLLs alongside my own DLL . Only my DLL can be loaded by the software ( because the other DLLs miss code to talk to BIMVision ) How can I make the software find the missing DLLs ? Where should I place them ? My .csproj looks like this : Managed to use the debugger to get the real exception out of the software : <code> < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < Project ToolsVersion= '' 12.0 '' DefaultTargets= '' Build '' xmlns= '' http : //schemas.microsoft.com/developer/msbuild/2003 '' > < Import Project= '' $ ( MSBuildExtensionsPath ) \ $ ( MSBuildToolsVersion ) \Microsoft.Common.props '' Condition= '' Exists ( ' $ ( MSBuildExtensionsPath ) \ $ ( MSBuildToolsVersion ) \Microsoft.Common.props ' ) '' / > < PropertyGroup > < Configuration Condition= '' ' $ ( Configuration ) ' == `` `` > Debug < /Configuration > < Platform Condition= '' ' $ ( Platform ) ' == `` `` > AnyCPU < /Platform > < ProjectGuid > { 362E40F4-4A37-48B3-A7A5-93E5535A9B22 } < /ProjectGuid > < OutputType > Library < /OutputType > < AppDesignerFolder > Properties < /AppDesignerFolder > < RootNamespace > ExcelLink < /RootNamespace > < AssemblyName > ExcelLink < /AssemblyName > < TargetFrameworkVersion > v4.6.2 < /TargetFrameworkVersion > < FileAlignment > 512 < /FileAlignment > < /PropertyGroup > < PropertyGroup Condition= '' ' $ ( Configuration ) | $ ( Platform ) ' == 'Debug|AnyCPU ' `` > < DebugSymbols > true < /DebugSymbols > < DebugType > full < /DebugType > < Optimize > false < /Optimize > < OutputPath > C : \Users\Daniel\Documents\SAMT\BIMVISION SDK\bim_vision_exe\plugins < /OutputPath > < DefineConstants > DEBUG ; TRACE < /DefineConstants > < ErrorReport > prompt < /ErrorReport > < WarningLevel > 4 < /WarningLevel > < PlatformTarget > x86 < /PlatformTarget > < /PropertyGroup > < PropertyGroup Condition= '' ' $ ( Configuration ) | $ ( Platform ) ' == 'Release|AnyCPU ' `` > < DebugType > pdbonly < /DebugType > < Optimize > true < /Optimize > < OutputPath > ..\..\..\bim_vision_exe\plugins\ < /OutputPath > < DefineConstants > TRACE < /DefineConstants > < ErrorReport > prompt < /ErrorReport > < WarningLevel > 4 < /WarningLevel > < PlatformTarget > x86 < /PlatformTarget > < /PropertyGroup > < ItemGroup > < Reference Include= '' PresentationCore '' / > < Reference Include= '' System '' / > < Reference Include= '' System.configuration '' / > < Reference Include= '' System.Core '' / > < Reference Include= '' System.Drawing '' / > < Reference Include= '' System.Security '' / > < Reference Include= '' System.Xml.Linq '' / > < Reference Include= '' System.Data.DataSetExtensions '' / > < Reference Include= '' Microsoft.CSharp '' / > < Reference Include= '' System.Data '' / > < Reference Include= '' System.Xml '' / > < /ItemGroup > < ItemGroup > < Compile Include= '' C : \Users\Daniel\Documents\SAMT\BIMVISION SDK\sdk .NET\BIMVision.cs '' > < Link > BIMVision.cs < /Link > < /Compile > < Compile Include= '' ExcelLink.cs '' / > < Compile Include= '' Properties\AssemblyInfo.cs '' / > < /ItemGroup > < ItemGroup > < PackageReference Include= '' EPPlus '' Version= '' 4.5.3.3 '' / > < PackageReference Include= '' UnmanagedExports '' Version= '' 1.2.7 '' / > < PackageReference Include= '' ZetaIpc '' Version= '' 1.0.0.9 '' / > < /ItemGroup > < Import Project= '' $ ( MSBuildToolsPath ) \Microsoft.CSharp.targets '' / > < Import Project= '' C : \Users\Daniel\Documents\SAMT\BIMVISION SDK\exmaples .NET\vs_2013\packages\UnmanagedExports.1.2.7\tools/RGiesecke.DllExport.targets '' Condition= '' Exists ( ' C : \Users\Daniel\Documents\SAMT\BIMVISION SDK\exmaples .NET\vs_2013\packages\UnmanagedExports.1.2.7\tools/RGiesecke.DllExport.targets ' ) '' / > < /Project > Exception thrown at 0x75AA9962 in bim_vision.exe : Microsoft C++ exception : EEFileLoadException at memory location 0x0019C458 .
Using NuGet libraries in an Unmanaged C # .NET library project
C_sharp : I am stuck on a LINQ query where I have being trying to return a list records from an SQL Table using EntityFramework 6 , instead of getting that list , I keep end up getting an IEnumerable < string [ ] > .This is what I have made to get IEnumerable < string [ ] > . I have an column in the table that needs to be split and then I test to see if a list contains those strings : The value in the table column columnOne can be something like this `` a-b '' or `` b-c '' etc , hence the need to use this s.columnOne.Split ( '- ' ) The above works as it should , but in the end it returns a list of string , which is not what I need.I tried this below : And this is where I run into the error and can go no further as I am ultimately trying to return a list of < Foo > , not < string > Now I know that the Where clause needs to return a bool value such as fooList.Where ( s = > s.columnOne == `` someString '' ) ; , but I am at a loss as to how to go about structuring the LINQ query to get the results I am trying to get.Any shove in the right direction would be great . <code> list < string > checkList = new list < string > ( ) ; checkList.add ( `` a '' ) checkList.add ( `` b '' ) checkList.add ( `` c '' ) List < Foo > fooList = dbContext.Foos.ToList ( ) ; IEnumerable < string [ ] > items = fooList.Select ( s = > s.columnOne.Split ( '- ' ) ) ; var result = items.SelectMany ( x = > x ) .Where ( s = > checkList.Contains ( s ) ) .ToList ( ) ; List < Foo > fooList = dbContext.Foos.ToList ( ) ; var test = fooList.Where ( s = > s.columnOne.Split ( '- ' ) ) ;
How to get IEnumerable < Foo > instead of IEnumerable < string > from LINQ ?
C_sharp : I am trying to copy the behavior of Entity Framework in creating the query from expression and i found my way using ExpressionVisitor when getting the property of the model by using Attribute this is what i got so far i have an attribute NColumn that indicates the real name of the property from table column so i mark the property of the model by Attributenow when im trying to get the expression , i got this BonusTypeName.Contains ( value ( Payroll.Test.Administration.TestRepositories+ < > c__DisplayClass13 ) .searchKey ) what i am expecting to get is BonusTypeName.Contains ( `` Xmas '' ) is there any method that gets the expression string ? i am using which i think it might be wrong.. : ) any help would be appreciated . <code> internal class NVisitor : ExpressionVisitor { private readonly ParameterExpression _parameter ; private readonly Type _type ; public NVisitor ( Type type ) { _type = type ; _parameter = Expression.Parameter ( type ) ; } protected override Expression VisitParameter ( ParameterExpression node ) { return _parameter ; } protected override Expression VisitMember ( MemberExpression node ) { if ( node.Member.MemberType == MemberTypes.Property ) { var memberName = node.Member.Name ; PropertyInfo otherMember = _type.GetProperty ( memberName ) ; var ncols = node.Member.GetCustomAttributes ( typeof ( NColumn ) , true ) ; if ( ncols.Any ( ) ) { var ncol = ( NColumn ) ncols.First ( ) ; otherMember = _type.GetProperty ( ncol.Name ) ; } var inner = Visit ( node.Expression ) ; return Expression.Property ( inner , otherMember ) ; } return base.VisitMember ( node ) ; } } public class BonusTypeX { [ NColumn ( `` BonusTypeName '' ) ] public string Name { get ; set ; } } [ TestMethod ] public void ExpressionTesting2 ( ) { string searchKey = `` Xmas '' ; Expression < Func < BonusTypeX , bool > > expression = x = > x.Name.Contains ( searchKey ) ; Type t = typeof ( tbl_BonusType ) ; var body = new NVisitor ( t ) .Visit ( expression.Body ) ; string a = string.Join ( `` . `` , body.ToString ( ) .Split ( ' . ' ) .Skip ( 1 ) ) ; Assert.AreEqual ( `` BonusTypeName.Contains ( \ '' Xmas\ '' ) '' , a ) ; } string a = string.Join ( `` . `` , body.ToString ( ) .Split ( ' . ' ) .Skip ( 1 ) ) ;
Expression Tree GetString Result
C_sharp : I would like to do the following : this concept can be kludged in javascript using an eval ( ) ... but this idea is to have a loopthat can go forward or backward based on values set at runtime.is this possible ? Thanks <code> *OperatorType* o = *OperatorType*.GreaterThan ; int i = 50 ; int increment = -1 ; int l = 0 ; for ( i ; i o l ; i = i + increment ) { //code }
Is there a .NET class that represents operator types ?
C_sharp : Why does the following piece of code work ? call : code : Is this allowed to work or just a bug ? <code> SomeObject sO = null ; bool test = sO.TestNull ( ) ; public static bool TestNull ( this SomeObject sO ) { return sO == null ; }
Can extensions methods be called on no-object ?
C_sharp : I 've just tried the new C # 8 Nullable Reference Type , which allows us to use non-nullable strings.In my .csproj ( .NET Core 3.1 ) I set this : I created a FooClass as follows : However , when I create a new instance of my class in my Main ( ) with null values on purpose : The compiler is fine with the testString parameter , but with the testDate parameter it tells me : Argument 2 : can not convert from ' < null > ' to 'DateTime'How can I get the same behavior for the first argument ? My testString parameter is a non-nullable reference type , just like testDate . As I did n't declare it as string ? , I 'm expecting the compiler to behave the same way for both parameters.Is there another feature to activate to enforce real non-nullable strings in C # ? <code> < Nullable > enable < /Nullable > public class FooClass { public FooClass ( string testString , DateTime testDate ) { if ( testString == null || testString == string.Empty ) throw new ArgumentNullException ( nameof ( testString ) ) ; else if ( testDate == null ) throw new ArgumentNullException ( nameof ( testDate ) ) ; MyString = testString ; MyDate = testDate ; } public string MyString { get ; } public DateTime MyDate { get ; } } var test = new FooClass ( testString : null , testDate : null ) ;
Enforce REAL non-nullable string reference type
C_sharp : So I was happily reading this from Eric Lippert and then , of course , the excellent comments and in them John Payson said : a more interesting example might have been to use two static classes , since such a program could deadlock without any visible blocking statements . and I thought , yeah , that 'd be easy so I knocked up this : The output of which ( after calling B.Go ( ) ) is : No deadlock and I am am obviously a loser - so to perpetuate the embarrassment , here is my question : why no deadlock here ? It seems to my tiny brain that B.Initialize is called before the static constructor of B has finished and I thought that that was not allowed . <code> public static class A { static A ( ) { Console.WriteLine ( `` A.ctor '' ) ; B.Initialize ( ) ; Console.WriteLine ( `` A.ctor.end '' ) ; } public static void Initialize ( ) { Console.WriteLine ( `` A.Initialize '' ) ; } } public static class B { static B ( ) { Console.WriteLine ( `` B.ctor '' ) ; A.Initialize ( ) ; Console.WriteLine ( `` B.ctor.end '' ) ; } public static void Initialize ( ) { Console.WriteLine ( `` B.Initialize '' ) ; } public static void Go ( ) { Console.WriteLine ( `` Go '' ) ; } } B.ctorA.ctorB.InitializeA.ctor.endA.InitializeB.ctor.endGo
Why no deadlock in this scenario ?
C_sharp : Is it a pretty safe assumption that the following class is an odd representation of `` downgrading '' ( for lack of a better word ) the private class field ? I recently saw a `` working '' example of this , and it threw me for a bit of a loop . What is the point of the above ? If List < T > implements ICollection < T > , then is n't the above class a reversal ? You 're having a private class field that 's type class is an extension of it 's parent 's class implementation ( ICollection < T > ) .Is it accurate to say the above example is not really a great design ? <code> public class AggregatedClass : ICollection < SingleClass > { List < SingleClass > _singleClassList ; // ... rest of code }
Collections and Lists
C_sharp : Why do I have to use the following to detach an event ? I am some how irritated that the new operator is working.Can some one explain ? UpdateI already know that i do n't have to use the new operator for detaching events , but it is still the auto complete suggestion in Visual Studio 2010 . My real question is how does -= new work for the detach process . How can a new object / delegate match a prior created object / delegate on the += side ? <code> object.myEvent -= new MyEvent ( EventHandler ) ;
Why is `` new '' operator working for detaching a eventhandler using -= ?
C_sharp : I have a string in the format below . ( I added the markers to get the newlines to show up correctly ) I am trying to get a regular expression that will allow me to extract the information from the two separate parts of the string.The following expression matches the first portion successfully : I am trying to figure out a way that I can modify it to get the second part of the string . I have tried things like what is below , but it ends up extending the match all the way to the end of the string . It is like it is giving preference to the expression following the OR.Any help would be appreciated -- EDIT -- Here is a copy of the test program I created to try and get this correct . I also added a 3rd message and my RegEx above breaks in that case. -- EDIT -- Just to make it clear , the data I am trying to extract is the Date and Timestamp ( as one item ) , the name , and the `` body '' from each `` paragraph '' . <code> -- START BELOW THIS LINE -- 2013-08-28 00:00:00 - Tom Smith ( Work notes ) Blah blahb ; lah blah2013-08-27 00:00:00 - Tom Smith ( Work notes ) ZXcZXCZXCZXZXcZXCZXZXCZXcZXcZXCZXC -- END ABOVE THIS LINE -- ^ ( \\d { 4 } -\\d { 2 } -\\d { 2 } \\d { 2 } : \\d { 2 } : \\d { 2 } ) - ( . * ) \\ ( Work notes\\ ) \n ( [ \\w\\W ] * ) ( ? =\n\n\\d { 4 } -\\d { 2 } -\\d { 2 } \\d { 2 } : \\d { 2 } : \\d { 2 } - . * \\ ( Work notes\\ ) \n ) ^ ( \\d { 4 } -\\d { 2 } -\\d { 2 } \\d { 2 } : \\d { 2 } : \\d { 2 } ) - ( . * ) \\ ( Work notes\\ ) \n ( [ \\w\\W ] * ) ( ? : ( ? =\n\n\\d { 4 } -\\d { 2 } -\\d { 2 } \\d { 2 } : \\d { 2 } : \\d { 2 } - . * \\ ( Work notes\\ ) \n ) |\n\\Z ) using System ; using System.Text.RegularExpressions ; namespace RegExTest { class MainClass { public static void Main ( string [ ] args ) { string str = `` 2013-08-28 10:50:13 - Tom Smith ( Work notes ) \nWhat 's up ? \nHow you been ? \n\n2013-08-19 10:21:03 - Tom Smith ( Work notes ) \nWork Notes\n\n2013-08-19 10:10:48 - Tom Smith ( Work notes ) \nGood day\n\n '' ; var regex = new Regex ( `` ^ ( \\d { 4 } -\\d { 2 } -\\d { 2 } \\d { 2 } : \\d { 2 } : \\d { 2 } ) - ( . * ) \\ ( Work notes\\ ) \n ( [ \\w\\W ] * ) \n\n ( ? =\\d { 4 } -\\d { 2 } -\\d { 2 } \\d { 2 } : \\d { 2 } : \\d { 2 } - . * \\ ( Work notes\\ ) \n ) '' , RegexOptions.Multiline ) ; foreach ( Match match in regex.Matches ( str ) ) { if ( match.Success ) { for ( var i = 0 ; i < match.Groups.Count ; i++ ) { Console.WriteLine ( ' > '+match.Groups [ i ] .Value ) ; } } } Console.ReadKey ( ) ; } } }
Multiline Regex matches first occurance but ca n't match second
C_sharp : Node of the list where every element points to next element and the head of the list would look like this : head can change , therefore we were using Node ** head . I know classes are passed as reference , so I can make first 2 attributes like this : How to make the head attribute ? <code> typedef struct Node { int value ; Node* next ; Node** head ; } Node ; class Node { int value ; Node next ; ? ? ? ? }
How to implement this struct as a class without pointers in c # ?
C_sharp : I have 3 data sets . 2 for polynomial itself ( let 's call them x and y ) and 1 for the function value ( it 's gon na be z ) .Polynomial looks something like this ( assuming the power of both dimensions is 3 ) : I need to be able to set the power of each dimension when preparing for approximation of values of `` a '' .I do n't really get how CurveFitting functions work with Math.NET Numerics , but i 've tried Fit.LinearMultiDim and MultipleRegression.QR . I 'm having trouble with initializing the Func delegateSo ideally i need to be able to compose the function with some sort of loop that accounts for the max power of both variables.UPD : The function is always above zero on any axis <code> z = a00 + a01*x + a02*x^2 + a03*x^3 + a10*y + a11*y*x + a12*y*x^2 ... etc var zs = new double [ ] { //values here } ; var x = new double [ ] { //values here } ; var y = new double [ ] { //values here . But the amounts are equal } ; var design = Matrix < double > .Build.DenseOfRowArrays ( Generate.Map2 ( x , y , ( t , w ) = > { var list = new List < double > ( ) ; //Can i get this working ? for ( int i = 0 ; i < = 3 ; i++ ) { for ( int j = 0 ; j < = 3 ; j++ ) { list.Add ( Math.Pow ( t , j ) *Math.Pow ( w , i ) ) ; } } return list.ToArray ( ) ; } ) ) ; double [ ] p = MultipleRegression.QR ( design , Vector < double > .Build.Dense ( zs ) ) .ToArray ( ) ;
Curve fitting to a 3D polynomial with variable powers
C_sharp : I have a List < Cat > where Cat is a struct that has an Id and a Name.How do I change the name of the cat with id 7 ? I did ( without thinking ) But of course , structs are value types . So is it possible to use a technique like this , or do I have to change .Single into a for loop and store the index to replace it with the updated struct ? <code> var myCat = catList.Single ( c = > c.Id == 7 ) ; mycat.Name = `` Dr Fluffykins '' ;
Update the property of a struct within a List in C #
C_sharp : I noticed DateTime objects are serialized differently for the same values between QueryString and Body . The underlying value is still the same correct value , however the serialized QueryString has a DateTimeKind of Local , whereas the Body is Utc.EndpointRequestResponseAny idea why this is ? Is there perhaps a setting to always serialize to the same DateTimeKind ? Preferably I would n't want to use ToUniversalTime ( ) or ToLocalTime ( ) everywhere , nor use any custom IModelBinder . <code> [ HttpPost ] public ActionResult Post ( [ FromQuery ] DateTime queryDate , [ FromBody ] DateTime bodyDate ) { var result = new { queryDateKind = queryDate.Kind.ToString ( ) , bodyDateKind = bodyDate.Kind.ToString ( ) } ; return new ObjectResult ( result ) ; } POST /api/values ? queryDate=2019-05-12T00 % 3A00 % 3A00.000Z HTTP/1.1Host : localhost:5000Content-Type : application/jsoncache-control : no-cache '' 2019-05-12T00:00:00.000Z '' { `` queryDateKind '' : `` Local '' , `` bodyDateKind '' : `` Utc '' }
ASP.NET DateTime Serialization in QueryString vs Body
C_sharp : I have an abstract base class : And another abstract class derived from that : I understand why you 'd want to abstract override DoSomeStuff ( ) - it will require an new implementation for further derived classes . But I ca n't figure out why you would want to abstract override DoSomeCrazyStuff ( ) . As far as I can tell , it 's redundant - I 'm pretty sure removing it would have zero negative impact.Is there some use case where abstract override on an abstract does something useful ? If not , why is n't there a compiler warning informing me that what I 've wrote does nothing ? <code> abstract class Foo { virtual void DoSomeStuff ( ) { //Do Some Stuff } abstract void DoSomeCrazyStuff ( ) ; } abstract class Bar : Foo { abstract override void DoSomeStuff ( ) ; abstract override void DoSomeCrazyStuff ( ) ; }
Why can I abstract override an abstract method ?
C_sharp : I want to implement like this : but I am getting ErrorMessage : The type or namespace name 'T ' could not be found ( are you missing a using directive or an assembly reference ? ) What should I do to avoid it ? <code> namespace PIMP.Web.TestForum.Models { public class ThreadModel : PagedList < T > {
Implementing of class with < T >
C_sharp : I need to have an open file dialog for 1000 file types ( *.000 - *.999 ) .But adding it to the filter , the dialog gets really slow on choosing file types . Is there anything I can do to speed this up ? <code> string text ; for ( int i = 0 ; i < = 999 ; i++ ) { text.Append ( `` * . '' + i.ToString ( `` 000 '' ) + `` ; `` ) ; } string textWithoutLastSemicolumn = text.ToString ( ) .Substring ( 0 , text.ToString ( ) .Length - 2 ) ; dialog.Filter = `` Files ( `` + textWithoutLastSemicolumn + `` ) | '' + textWithoutLastSemicolumn ;
OpenFileDialog with many extensions
C_sharp : If i have some code like the following : Both operands are shorts and it 's going into a short so why do i have to cast it ? <code> short myShortA = 54 ; short myShortB = 12 ; short myShortC = ( short ) ( myShortA - myShortB ) ;
Why do i need to wrap this code in a cast to short ?
C_sharp : I 'm investigating the execution of this C # code : The equivalent IL code is : Based on this answer ( unnecessary unbox_any ) , can anyone explain to me what the exact logic the Jitter is doing here ; how exactly does the Jitter decide to ignore the 'unbox_any ' instruction in this specific case ( theoretically , according to msdn , a NullReferenceException should be thrown when the isinst instruction yields null , but this does n't happen in practice ! ) UpdateBased on usr answer and Hans comment , if the obj is a reference type , castclass will be called , and therefore , no NRE.But what about the following case ? And the equivalent IL code ( partial ) : In this case its value type so why NRE not thrown ? <code> public static void Test < T > ( object o ) where T : class { T t = o as T ; } .method public static void Test < class T > ( object A_0 ) cil managed { // Code size 13 ( 0xd ) .maxstack 1 .locals init ( ! ! T V_0 ) IL_0000 : ldarg.0 IL_0001 : isinst ! ! T IL_0006 : unbox.any ! ! T IL_000b : stloc.0 IL_000c : ret } // end of method DemoType : :Test static void Test < T > ( object o ) where T : new ( ) { var nullable = o as int ? ; if ( nullable ! = null ) //do something } Test < int ? > ( null ) ; IL_0001 : ldarg.0IL_0002 : isinst valuetype [ mscorlib ] System.Nullable ` 1 < int32 > IL_0007 : unbox.any valuetype [ mscorlib ] System.Nullable ` 1 < int32 > IL_000c : stloc.0IL_000d : ldloca.s nullableIL_000f : call instance bool valuetype [ mscorlib ] System.Nullable ` 1 < int32 > : :get_HasValue ( ) IL_0014 : stloc.1IL_0015 : ldloc.1IL_0016 : brfalse.s IL_0024
Jitter logic to remove unbox_any
C_sharp : Can someone explain this behavior ? StartsWith works same . <code> `` `` .EndsWith ( ( ( char ) 9917 ) .ToString ( ) ) // returns true
Unexpected behavior with EndsWith
C_sharp : I came from C # world , and used to arrays being reference types . As I understand , in swift arrays are value types , but they try to play as reference ones.I do n't actually know how to ask what I need ( I think this is the case when I need to know answer to be able to ask question ) , but in C # I would say I need to store a reference to inner array of a jagged array into local variable.Consider the following piece of code : Swift sandbox here http : //swiftlang.ng.bluemix.net/ # /repl/8608824e18317e19b32113e1aa08deeb4ec5ab96ed8cdbe1dbfb4e753e87d528Here I want to I process multidimensional array in-place , so that I do n't create a copy of array or parts of array . In option ( 1 ) I change everything to `` -1 '' , and it works , but is uses additional function for this.In option ( 2 ) I try to use local variable to store matrix [ rowIdx ] , but it actually creates a copy of inner array - not what I want ; working with this variable changes copy of array , and not original one.How can I achieve results like in option ( 1 ) , but using local variable instead of function ? That is , how can I obtain reference to inner array and put it to local variable ? I would understand answer `` there 's no way for this '' , but I want such answers to be accompanied by some Apple refs . <code> // a function to change row values in-placefunc processRow ( inout row : [ Int ] , _ value : Int ) { for col in 0.. < row.count { row [ col ] = value ; } } // a function to change matrix values in-placefunc processMatrix ( inout matrix : [ [ Int ] ] ) { for rowIdx in 0.. < matrix.count { // ( 1 ) Works with array in-place processRow ( & ( matrix [ rowIdx ] ) , -1 ) // ( 2 ) Creates local copy var r = matrix [ rowIdx ] ; // < -- - What to write here to not make a copy but still have this local variable ? processRow ( & r , -2 ) ; } } var matrix = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] processMatrix ( & matrix ) print ( matrix ) // outputs [ [ -1 , -1 , -1 ] , [ -1 , -1 , -1 ] , [ -1 , -1 , -1 ] ]
Local reference to inner array in swift
C_sharp : I am working a project that uses entity framework . I want simple thing when people click to searchLookUpedit button I want to show values filtered according to Companies that exists in Orders . So here is the code : In here second for loop . Lets imagine that in firmaIds < int > list type have 3 values . And assume that they are 3 , 5 and 8 for example , and I want only this 3 Companies will exist in firmalarBindingSource.DataSource after the click event finished running . I tried but it did not . If my criteria were different data type it was easy to filter . Is there anyway to do this ? <code> private void SearchLookUpEdit_Customer_Click ( object sender , EventArgs e ) { object [ ] siparisNo = new object [ gridView1.RowCount ] ; List < Siparisler > siparisList = new List < Siparisler > ( ) ; List < int > firmaIds = new List < int > ( ) ; for ( int i = 0 ; i < gridView1.RowCount ; i++ ) { siparisNo [ i ] = gridView1.GetRowCellValue ( i , '' SiparisNo '' ) ; int sipNo = Convert.ToInt32 ( siparisNo [ i ] ) ; Siparisler siparis = context.Siparisler.Where ( p = > p.Id == sipNo ) .FirstOrDefault ( ) ; siparisList.Add ( siparis ) ; firmaIds.Add ( siparis.Firma_Id ) ; } for ( int i = 0 ; i < firmaIds.Count ; i++ ) { int a = firmaIds [ i ] ; firmalarBindingSource.DataSource = context.Firmalar.Where ( p = > p.Id == ) ; } }
Giving Multiple List < int > type criteria by using linq in Entity Framework
C_sharp : Before I start I 'd like to say sorry if this is n't highly professionally written , I 've been working on this for hours banging my head against the wall trying to figure this out with no luck , I 'm tired and stressed.I 'm trying to get a moving object to enter through 1 portal at a specific point , and come out the other portal at the same point it entered . So if the ball enters the top of the portal , the object will come out at the top of the exit portal , and the if the object enters from the bottom of the portal it will exit the bottom of the other portal . I 'm not the best a illustration , but here 's what I want to it do : Here you can see in both images the object enters the blue portal and exits the orange at the point that it entered , so top to top , bottom to bottom.I 've actually gotten this to work fine , but now I need to do it again but this time , one of the portals needs to be horizontal instead of vertical : So what I 've done , is make it so when both a vertical , I leave a bool called `` exitIsHorizontal '' unchecked ( false ) , and when one of them is on the ceiling on the level , it translates the vertical axis to a horizontal one.I even sort of got that to work , however it 's got a reproducible quark that needs to be fixed . When the object enters the bottom of the portal , it works fine like you 'd expect and just like the image above . But when you hit the top of the portal , the object comes out the other side of the portal like you 'd expect , but the object begins moving in the opposite direction as see in this image : Correct exit location , wrong exit direction for some reason . I also need this function to be dynamic so that if say , the object hit the blue portal from the other direction that the exit direction would switch sides as well like this : Here is my script : This script is attached to both portals so that both Portals can handle both entering and exiting . And any variable you do n't see declared with anything in the script making it essentially null ( such as `` otherPotal '' ) I declare the in editor.I 'll bet it 's something extremely simple that I just keep missing , I just do n't know that something is . <code> public GameObject otherPortal ; public PortalController otherPortalScript ; private BallController ballController ; public bool exitIsHorizontal = false ; List < PortalController > inUseControllers = new List < PortalController > ( ) ; // Use this for initialization void Start ( ) { } // Update is called once per frame void Update ( ) { } void OnTriggerEnter2D ( Collider2D other ) { if ( other.gameObject.tag == `` Ball '' ) { ballController = other.GetComponent < BallController > ( ) ; if ( inUseControllers.Count == 0 ) { inUseControllers.Add ( otherPortalScript ) ; var offset = other.transform.position - transform.position ; if ( exitIsHorizontal ) { offset.x = offset.y ; offset.y = 0 ; } else { offset.x = 0 ; } other.transform.position = otherPortal.transform.position + offset ; } } } void OnTriggerExit2D ( Collider2D other ) { if ( other.gameObject.tag == `` Ball '' ) { inUseControllers.Clear ( ) ; } }
Object exits portal moving the wrong direction in Unity 2D ?
C_sharp : I ’ m not sure what this is called , or where I did see this , so I don ’ t really know what to search for . Therefore I ’ m trying to explain what I mean.Suppose I have the following class structure , where TypeB is used within TypeA : Now when I have an instance of TypeA , I want to disallow , that I can directly modify the values of TypeB without reassigning . So basically I want to prevent this : The reason is that I am persisting the object in a special way , so to keep track of changes in TypeB correctly , I want to require that the value of B within TypeA is reassigned.I think that I have seen a similar thing before with some built-in object , where this threw an error and compile time . What is this called , and how can I achieve it in my custom types ? <code> class TypeA { public TypeB B { get ; set } } class TypeB { public int X { get ; set } } TypeA a = new TypeA ( ) ; // this should not be possible : a.B.X = 1234 ; // but this should work : TypeB b = a.B ; b.X = 1234 ; a.B = b ;
Disallow setting property 's property
C_sharp : I have a class where every method starts the same way : Is there a nice way to require ( and hopefully not write each time ) the FooIsEnabled part for every public method in the class ? I check Is there an elegant way to make every method in a class start with a certain block of code ? , but that question is for Java , and its answer are using Java Library . <code> internal class Foo { public void Bar ( ) { if ( ! FooIsEnabled ) return ; // ... } public void Baz ( ) { if ( ! FooIsEnabled ) return ; // ... } public void Bat ( ) { if ( ! FooIsEnabled ) return ; // ... } }
Is there an elegant way to make every method in a class start with a certain block of code in C # ?
C_sharp : When seralizing a class and saving to a file , sometimes an error occurs where the serialized output looks like this : The class I 'm serializing looks like this : I ca n't seem to figure out why this is happening . Here 's my serializer class : Thanks ! <code> < ? xml version= '' 1.0 '' ? > < Template xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xmlns : xsd= '' http : //www.w3.org/2001/XMLSchema '' > < Route > Some Route < /Route > < TradePack > Something Here < /TradePack > < Transport / > < /Template > te > -- -- -- > Notice this extra string ? [ Serializable ] public class Template { public string Route = string.Empty ; public string TradePack = string.Empty ; public string Transport = string.Empty ; public Template ( ) { } } public static bool Save ( object obj , string path ) { try { XmlSerializer writer = new XmlSerializer ( obj.GetType ( ) ) ; using ( var stream = new FileStream ( path , FileMode.OpenOrCreate , FileAccess.ReadWrite , FileShare.ReadWrite ) ) { writer.Serialize ( stream , obj ) ; } return true ; } catch { } return false ; }
XML Serialization produces random strings at the end ? C #
C_sharp : I was making a simple test for running a validation method and came across this strange situation.Once this code runs , a will contain [ 0,1,2,3,4 ] . However , b will contain [ 0,1,2,3 ] . Why did calling the method as an argument in AddRange allow the list to be passed by reference ? Or if that did n't happen , what did ? <code> public IEnumerable < int > ints ( List < int > l ) { if ( false ) yield return 6 ; l.Add ( 4 ) ; } void Main ( ) { var a = new List < int > ( ) ; var b = new List < int > ( ) ; for ( int i = 0 ; i < 4 ; i++ ) { a.Add ( i ) ; b.Add ( i ) ; } a.AddRange ( ints ( a ) ) ; ints ( b ) ; Console.WriteLine ( a ) ; Console.WriteLine ( b ) ; }
What causes this list to be passed by reference when called one way , but by value another ?
C_sharp : I am troubleshooting a strange issue reported by a client which is caused by the application trying to parse invalid XML . I believe the root cause to be related to how the XML string is encoded and then decoded . I have an internal API that gets the XML string ( which I know to be valid to begin with ) , then converts it to a byte array and wraps it with a readonly MemoryStream . Then on the other side , the stream is converted back to a string and then passed to XDocument.Parse ( string ) . The latter call fails , saying `` Data at the root level is invalid . Line 1 , position 1 . '' Anyway , I believe the root cause has to do with how I am encoding and then decoding the string . In fact , the following line of debugging code returns a different string than what was passed in . Using Encoding.Default on the way in and then back out yields a different string than what I started with . That 's craaaazy . Any ideas ? Note : I am using an API which I can not change which retrieves the stream containing the XML , so I can not alter the use of Encoding.Default . Doing so will risk production issues ( a.k.a showstoppers ) for clients where everything is working fine . <code> Encoding.Default.GetString ( Encoding.Default.GetBytes ( GetMeAnXmlString ( ) ) ) ) ;
C # Converting a string to bytes and then back to a string with default encoder mangles the string
C_sharp : I am creating a simple WPF Application . I 've a function OpenFile : Ideally where should this function be present ? I feel it should be in .xaml.cs because it accesses a MessageBox which comes in the View part . But it also calls my Helper , which is in the model . So I also think it can be in the ViewModel . What is the advantage of having this in the View or in the ViewModel ? Can someone help me with some pointers ? Thanks . <code> private void OpenFile ( string fileName ) { if ( ! File.Exists ( Helper.GetPath ( fileName ) ) ) { MessageBox.Show ( `` Error opening file '' ) ; } else { //Code to handle file opening } }
Should I put this function in View ( code-behind ) or in ViewModel ?
C_sharp : Is there any way to add an if statement into a function parameter ? For example : <code> static void Main ( ) { bool Example = false ; Console.Write ( ( if ( ! Example ) { `` Example is false '' } else { `` Example is true '' } ) ) ; } //Desired outcome of when the code shown above is//executed would be for the console to output : //Example is false
Can I add an if statement to a parameter ?
C_sharp : Possible Duplicate : Impossible recursive generic class definition ? I just discovered thatis legal . What exactly does it mean ? It seemsrecursive and is it possible to instantiate somethinglike this ? <code> public class Foo < T > where T : Foo < T > { }
Strange C # generic contraint
C_sharp : I have a method in DAL like : In this method , I am passing two nullable types , because these values can be null ( and checking them as null in DB Stored Proc ) . I do n't want to use magic numbers , so is it ok passing nullables types like this ( from performance as well as architecture flexibility perspective ) ? <code> public bool GetSomeValue ( int ? a , int ? b , int c ) { //check a Stored Proc in DB and return true or false based on values of a , b and c }
Using nullable types in public APIs
C_sharp : Can anyone elaborate following statement : why i should not use <code> byte [ ] buffer = new Byte [ checked ( ( uint ) Math.Min ( 32 * 1024 , ( int ) objFileStream.Length ) ) ] ; byte [ ] buffer = new Byte [ 32 * 1024 ] ;
What is the significance of using checked here
C_sharp : I 've got the following code block . I 'm confused how the code can go past the Indeed it does . I thought any lines past that would automatically not execute . Am I missing somethig basic here ? I find the debugger actually executing the next lines . <code> Response.Redirect ( `` ~.. '' ) public ActionResult Index ( ) { Response.Redirect ( `` ~/Default.aspx '' , true ) ; string year = Utils.ConvertCodeCampYearToActualYear ( Utils.GetCurrentCodeCampYear ( ) .ToString ( CultureInfo.InvariantCulture ) ) ; var viewModel = GetViewModel ( year ) ; return View ( viewModel ) ; }
How can code go past response.redirect ?
C_sharp : I 've done this Unit Test and I do n't understand why the `` await Task.Delay ( ) '' does n't wait ! Here is the Unit Test output : How is this possible an `` await '' does n't wait , and the main thread continues ? <code> [ TestMethod ] public async Task SimpleTest ( ) { bool isOK = false ; Task myTask = new Task ( async ( ) = > { Console.WriteLine ( `` Task.BeforeDelay '' ) ; await Task.Delay ( 1000 ) ; Console.WriteLine ( `` Task.AfterDelay '' ) ; isOK = true ; Console.WriteLine ( `` Task.Ended '' ) ; } ) ; Console.WriteLine ( `` Main.BeforeStart '' ) ; myTask.Start ( ) ; Console.WriteLine ( `` Main.AfterStart '' ) ; await myTask ; Console.WriteLine ( `` Main.AfterAwait '' ) ; Assert.IsTrue ( isOK , `` OK '' ) ; }
How to declare a not started Task that will Await for another Task ?
C_sharp : I have a table name Students having ( studentId , StudentName , Address , PhoneNo ) i have provided a filter for user to select only StudentId from Combobox to get the details of Students ... and generate Report.I have written following Query to get student Detail : Here stdId is a Parameter that i pass from codeIt works fine if i select single studentId ... . But in user selection Comobobox i have also provided `` ALL '' if user Select All from combobox i want to display details of all studentSo what should I pass in stdId if user selects All ? I used inline Query in C # ( not using SQL Stored Procedure ) <code> ( select * from Students where StudentId = stdId )
Issue Related to where clause in SQL Server
C_sharp : I am trying to parse the date by using below code but its output is wrong , the datetoconvert in above code is 30/Mar/2017 but output is 29/Jan/2017looking forward for your valuable answers ... <code> DateTime mydate = DateTime.ParseExact ( datetoconvert , '' dd/mm/yyyy '' , System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat ) ;
Parsing Date Time in C # , Getting wrong output
C_sharp : Possible Duplicate : How to Round Up The Result Of Integer Division i would be 5.But I would like it to return 6 . ( if the result is 5.01 , I would want a 6 too ) How should I do it ? <code> double d1=11 , double d2=2int i=d1/d2 ;
Next larger integer after dividing
C_sharp : I want an indexed list by ID , ordered by a special attribute inside my class.SortedList , doesnt do this , because it forces me to sort by the key ... Lets say my class isIs there any structure that is indexed like a dictionary , and ordered by something else ? so that I can access data by ID , but in a foreach the data is ordered by Order <code> class example { int Id ; int Order }
SortedList indexed by something other than the Key
C_sharp : In my MVC3 application i have a dropdown list . In there i have to show all the results , but some results must be disabled , so that they are not selectable . How can i do that ? This is what i have right now . It simply does n't show the players that have Disabled set to true.So is there another way to also show the Disabled players , but that the output would be like this , instead of just hiding them completely : Is that possible with a DropDownListFor ? <code> @ Html.DropDownListFor ( m = > m.Position1 , Model.SelectedTeam.TeamPlayers .Where ( c = > c.Player.Disabled == false ) .OrderBy ( t = > t.Player.Lastname ) .ToSelectList ( m = > m.FullName , m = > m.PlayerId ) ) < select > < option > Player 1 < /option > < option disabled= '' disabled '' > Player 2 < /option > < option > Player 3 < /option > < option > Player 4 < /option > < option disabled= '' disabled '' > Player 5 < /option > < option > Player 6 < /option > < /select >
DropDownListFor callback or if statement
C_sharp : I often have call hierarchies in that all methods need the same parameters . If I dont't want to put them on the instance level ( member of the class ) then I ask me always if its meaningfull to check the validity of them in each method.For example : If Method A uses the parameter , then its clear , I have to check the validity there and also in MethdoB . But as long as MethodA does nothing more with o than give it to MethodB , is it good practice to check the validity also in MethodA.The avantage of checking also in MethodA may be that the exception throws in the method the callee has called , that is nice , but is it necessary ? The call stack will state this also . Maybe its meaningfull in public , internal , protected but not in private methods ? I took the null-check as an example , but also index-validations or range validations fall in the self question , however I think there are limitations because of the danger of redundant code . What do you think ? UPDATEThrough the answer of AakashM I have seen that I was to little precise . MethodA not only calls MethodB , it does also other things but not related to o. I added an example to clarify this . Thanks AakashM . <code> public void MethodA ( object o ) { if ( null == o ) { throw new ArgumentNullException ( `` o '' ) ; } // Do some thing unrelated to o MethodB ( o ) ; // Do some thing unrelated to o } public void MethodB ( object o ) { if ( null == o ) { throw new ArgumentNullException ( `` o '' ) ; } // Do something with o }
Repeated parameter checks in functions
C_sharp : I have code that copies the content of one PowerPoint slide into another . Below is an example of how images are processed.This code works fine . For other scenarios like Graphic Frames , it looks a bit different , because each graphic frame can contain multiple picture objects.Now I need to do the same thing with OLE objects.But it did n't work . The resulting PowerPoint is corrupted.What am I doing wrong ? NOTE : All of the code works except for the rId handling in the OLE Object . I know it works because if I simply pass the original rId from the source object to the target Object Part , like this : it will function properly , so long as that rId does n't already exist in the target slide , which will obviously not work every time like I need it to.The source slide and target slide are coming from different PPTX files . We 're using OpenXML , not Office Interop . <code> foreach ( OpenXmlElement element in sourceSlide.CommonSlideData.ShapeTree.ChildElements.ToList ( ) ) { string elementType = element.GetType ( ) .ToString ( ) ; if ( elementType.EndsWith ( `` .Picture '' ) ) { // Deep clone the element . elementClone = element.CloneNode ( true ) ; var picture = ( Picture ) elementClone ; // Get the picture 's original rId var blip = picture.BlipFill.Blip ; string rId = blip.Embed.Value ; // Retrieve the ImagePart from the original slide by rId ImagePart sourceImagePart = ( ImagePart ) sourceSlide.SlidePart.GetPartById ( rId ) ; // Add the image part to the new slide , letting OpenXml generate the new rId ImagePart targetImagePart = targetSlidePart.AddImagePart ( sourceImagePart.ContentType ) ; // And copy the image data . targetImagePart.FeedData ( sourceImagePart.GetStream ( ) ) ; // Retrieve the new ID from the target image part , string id = targetSlidePart.GetIdOfPart ( targetImagePart ) ; // and assign it to the picture . blip.Embed.Value = id ; // Get the shape tree that we 're adding the clone to and append to it . ShapeTree shapeTree = targetSlide.CommonSlideData.ShapeTree ; shapeTree.Append ( elementClone ) ; } // Go thru all the Picture objects in this GraphicFrame.foreach ( var sourcePicture in element.Descendants < Picture > ( ) ) { string rId = sourcePicture.BlipFill.Blip.Embed.Value ; ImagePart sourceImagePart = ( ImagePart ) sourceSlide.SlidePart.GetPartById ( rId ) ; var contentType = sourceImagePart.ContentType ; var targetPicture = elementClone.Descendants < Picture > ( ) .First ( x = > x.BlipFill.Blip.Embed.Value == rId ) ; var targetBlip = targetPicture.BlipFill.Blip ; ImagePart targetImagePart = targetSlidePart.AddImagePart ( contentType ) ; targetImagePart.FeedData ( sourceImagePart.GetStream ( ) ) ; string id = targetSlidePart.GetIdOfPart ( targetImagePart ) ; targetBlip.Embed.Value = id ; } // Go thru all the embedded objects in this GraphicFrame.foreach ( var oleObject in element.Descendants < OleObject > ( ) ) { // Get the rId of the embedded OLE object . string rId = oleObject.Id ; // Get the EmbeddedPart from the source slide . var embeddedOleObj = sourceSlide.SlidePart.GetPartById ( rId ) ; // Get the content type . var contentType = embeddedOleObj.ContentType ; // Create the Target Part . Let OpenXML assign an rId . var targetObjectPart = targetSlide.SlidePart.AddNewPart < EmbeddedObjectPart > ( contentType , null ) ; // Get the embedded OLE object data from the original object . var objectStream = embeddedOleObj.GetStream ( ) ; // And give it to the ObjectPart . targetObjectPart.FeedData ( objectStream ) ; // Get the new rId and assign it to the OLE Object . string id = targetSlidePart.GetIdOfPart ( targetObjectPart ) ; oleObject.Id = id ; } var targetObjectPart = targetSlide.SlidePart .AddNewPart < EmbeddedObjectPart > ( contentType , rId ) ;
Copying OLE Objects from one slide to another corrupts the resulting PowerPoint
C_sharp : Suppose I have At ( 1 ) , is the object bar is pointing to eligible for garbage collection ? Or does bar have to fall out of scope as well ? Does it make a difference if GC.Collect is called by doSomethingWithoutBar ? This is relevant to know if Bar has a ( C # ) destructor or something funky like that . <code> void foo ( ) { Bar bar = new Bar ( ) ; // bar is never referred to after this line // ( 1 ) doSomethingWithoutBar ( ) ; }
Special case lifetime analysis
C_sharp : First I would like to say thank you for helping me with this issue . I really appreciate your time and efforts.The title sums it up pretty well however I will provide a few specifics . Basically if I pull my OS version using C # it returns the result 6.2 which is for Windows 8 even though my system is 8.1 which should return 6.3 . After my research I found that this was a documented limitation inside of the System.Enviroment class , ... got ta love those `` features '' .I have found a way to deal with this by going into the reg and comparing my 6.2 result with the current version key under HKLM\SOFTWARE\Microsoft\WindowsNT\CurrentVersion however , this is a very risky operation as the reg info could change without notice . It all got screwy on me when I tried to poll WMI though Powershell . I ca n't remember why I did a WMI search though Powershell , I guess its not just cats that get curious : ) C # Code : Powershell Code : I have tried both x86 and x64 builds of my C # program as well as running the Powershell both x86 and x64 . The discrepancies did not change.This raises several questions for me but the basic one is where does Powershell get the correct info from ? Does Powershell use the reg like I had planned to fix its output ? Since my build targets .Net 3.5 does Powershell pull .Net 4.5 ( changed my build and this changed nothing ) . From my understanding [ System.Environment ] : :OSVersion pulls info the same as System.Environment.OSVersion . How the heck does Powershell work and C # fails ? ? : ) Thanks again ! <code> string version = Environment.OSVersion.ToString ( ) ; MessageBox.Show ( version ) ; //Output `` Microsoft Windows NT 6.2.9200.0 '' [ System.Environment ] : :OSVersion | Select-Object -Property VersionString//OUtput `` Microsoft Windows NT 6.3.9600.0 ''
Powershell WMI output doesnt match c # WMI output
C_sharp : If have the following method : When i call this method with null as a parameter , the type check returns false for this parameter . For example this coderesults in this output : Is there any way to preserve the type information when using a Nullable and passing null ? I know that checking the type in this example is useless , but it illustrates the problem . In my project , I pass the parameters to another method that takes a params object [ ] array and tries to identify the type of the objects . This method needs to do different things for Nullable < int > and Nullable < long > . <code> static void DoSomethingWithTwoNullables ( Nullable < int > a , Nullable < int > b ) { Console.WriteLine ( `` Param a is Nullable < int > : `` + ( a is Nullable < int > ) ) ; Console.WriteLine ( `` Param a is int : `` + ( a is int ) ) ; Console.WriteLine ( `` Param b is Nullable < int > : `` + ( b is Nullable < int > ) ) ; Console.WriteLine ( `` Param b is int : `` + ( b is int ) ) ; } DoSomethingWithTwoNullables ( 5 , new Nullable < int > ( ) ) ; Param a is Nullable < int > : TrueParam a is int : TrueParam b is Nullable < int > : FalseParam b is int : False
Type checking on Nullable < int >
C_sharp : Consider the following class and method : andIf called with a MyDto with a null Child left to it 's own devices this will throw a NullReferenceException which can be extremely difficult to diagnose in more complex methods.Typically I throw an ArgumentNullException at the start of the method if myDto is null but what is the appropriate exception to throw if myDto.Children is null ? An ArgumentNullException ? A NullReferenceException ? A custom exception ? <code> public class MyDto { public MyDtoChild Child { get ; set ; } } public void ProcessDto ( MyDto myDto ) { if ( myDto == null ) throw new ArgumentNullException ( `` myDto '' ) ; this.CheckSomething ( myDto.Child.ChildProperty ) ; }
Which Null Exception to throw ?
C_sharp : I have no idea what to call this , so it may have already been addressed numerous times.I have a wrapper class for a collection : public class TreeCategory < T > : IEnumerable < T > In my xaml I am using the class in the HierarchicalDataTemplate as follows : So my question is , when I build using local : TreeCategory the build fails , as the project complains it does not know what the class TreeCategory is . However if I use : then the project builds fine.What is the ` 1 , why is it necessary ? <code> < HierarchicalDataTemplate x : Key= '' m_CategoryTemplate '' DataType= '' { x : Type local : TreeCategory ` 1 } '' < -- - WHAT IS THIS ? ! ItemsSource= '' { Binding CategoryCollection } '' > < TextBox Text= '' { Binding CategoryName } '' / > < /HierarchicalDataTemplate > TreeCategory ` 1
Mysterious ` 1 in XAML Datatype
C_sharp : I have a simple c # question ( so I believe ) . I 'm a beginner with the language and I ran into a problem regarding interfaces and classes that implement them . The problem isI have the Interface iAand 3 classes that implement the interface : class B , C and Dif class B had another method that is not in the interface , let 's say method4 ( ) and I have the following : and then I would use : I would get an error saying that I do n't have a method4 ( ) that takes a first argument of type iA.The question is : Can I have an object of interface type and instantiated with a class and have that object call a method from the class , a method that is not in the interface ? A solution I came up with was to use an abstract class between the interface and the derived classes , but IMO that would put the interface out of scope . In my design I would like to use only the interface and the derived classes . <code> interface iA { bool method1 bool method2 bool method3 } class B : iA { public bool method1 public bool method2 public bool method3 } iA element = new B ( ) ; element.method4 ( ) ;
Class method that is not in the interface
C_sharp : I am wondering why the code like this wo n't work : I assume , that there should be an IComparable constraint added , to make it work ( maybe CompareTo instead of == as well ) . With class constraint , references would be compared . With struct constraint , no comparison is allowed , as well as with no constraint.Would n't it be possible to resolve given type and compare references in case when object is passed , and compare values when the value types are passed ? <code> public static bool cmp < T > ( T a , T b ) { return a == b ; }
Why do I need to implement IComparable < T > to compare two values in generic method ?
C_sharp : I ca n't quite get my head around trying to figure this out but I 'll explain as follows , Here I have the var coords which contains some List < int > ; what I need is for some new lists to be populated inside combinedCoords which will contain some combined lists where there are numbers in common . From this there should be 2 combined lists produced , the first will be { 0,1,2,3,4,5 } and the second will be { 7,8,9,10 } . To further illustrate what I 'm trying to say , below is a graphical representation were each circle is a list ; the red number in brackets denotes the index of each list . ( source : aboutireland.ie ) <code> var combinedCoords = new List < List < int > > ( ) ; var coords = new List < List < int > > { new List < int > ( ) { 0 , 1 } , new List < int > ( ) { 0 , 1 , 2 } , new List < int > ( ) { 1 , 3 , 4 , 5 } , new List < int > ( ) { 3 , 4 } , new List < int > ( ) { 7 , 8 } , new List < int > ( ) { 7 , 8 , 9 } , new List < int > ( ) { 8 , 9 , 10 } } ;
Create combined Lists from multiple Lists
C_sharp : Basically I have the following : The problem is I ca n't do this because you ca n't have a member with the same signature , even if the constraints are different . But , there is no way to state that the constraint is either IComparable OR IComparable < T > . So , I 'm not sure what to do here outside of just picking one and going with it . And , no matter which one I pick I 'm losing out on the other because they are separate and do n't inherit from each other ( which makes sense ) .Am I missing something here in that is there a way to accomplish using both , or am I going to have to pick one ( probably the generic version ) ? <code> public static bool IsBetween < T > ( this T value , T a , T b ) where T : IComparable { ... } public static bool IsBetween < T > ( this T value , T a , T b ) where T : IComparable < T > { ... }
Generic constraints -- I 'm not sure how to fix this situation with an either/or case
C_sharp : I am trying to replace a \ with \\ and it works with everything except the specific variable I need it to work on . Throwing the error Illegal characters in path . probably because it thinks \t is a character , which is tab and is therefor not allowed in a paththe variable is loaded in from a json file using Newtonsoft.Json in to a classI have triedvar escapedir = Regex.Replace ( Directory , @ '' \\ '' , @ '' \ '' ) ; and any possible way I could form var escapedir = Directory.Replace ( `` \ '' , `` \\ '' ) ; .Trying Regex.Replace ( `` C : \test '' , @ '' \ '' , @ '' \\ '' ) ; ( C : \test being the exact same as in Directory ) worked perfectly and then inside a foreach I am trying to combine the Directory with a filename . `` Dump '' of current code : And config.json : Here 's a screenshot to show the exception : <code> public class WebsiteConfig { public string Name { get ; set ; } public string Directory { get ; set ; } } var json = File.ReadAllText ( Path.Combine ( Environment.CurrentDirectory , `` config.json '' ) ) ; _config = JsonConvert.DeserializeObject < Config > ( json ) ; foreach ( WebsiteConfig website in _config.WebsiteConfigList ) { for ( int i = 0 ; i < = 9 ; i++ ) { string dir = website.Directory ; string escapedir = Regex.Replace ( dir , @ '' \\ '' , @ '' \\\\ '' ) ; var path = Path.Combine ( escapedir , `` Backedup_ '' + i.ToString ( ) + `` .txt '' ) ; } } { `` WebsiteConfigList '' : [ { `` Name '' : `` test '' , `` Directory '' : `` C : \test '' } ] }
Replace \ with \\ does n't work for specific variable
C_sharp : ive been asking myself : `` why should i use lock to only one statement '' ... ( IMHO - if its 1 operation only like an assignment - so there shouldnt be a problem.. ) ? then i saw this : As a basic rule , you need to lock around accessing any writable shared field . Even in the simplest case—an assignment operation on a single field—you must consider synchronization . In the following class , neither the Increment nor the Assign method is thread-safe : can you please tell me why this is not thread safe ? ive been running many scripts in my head and couldnt find any problem ... <code> class ThreadUnsafe { static int _x ; static void Increment ( ) { _x++ ; } static void Assign ( ) { _x = 123 ; } }
locking only 1 operation ?
C_sharp : As I am fairly new to web application development I am currently having some difficulty in implementing some testing functionality.As part of the project I am currently working ( An MVC 3 Web App for processing payments ) I have been asked to create a testmode which can be accessed through the URL in this manner : The idea behind this is that when one of the development team adds the testmode parameter to the URL a set of form values are auto generated in order to save time on entering data each time the application is tested.Currently I have an if statement in the controller which uses Request.QueryString to set the parameter below is the code that I am currently using : Given the context what if any would be the best method of achieving this ? Would it be possible to using a mocking framework such as Moq or RhinoMocks to create a fake repository rather than retrieving results from a database or would it be better to have test data preloaded in the database ? <code> http : //websiteurl ? testmode=1 if ( Request.QueryString.AllKey.Contains ( `` tm '' ) ) { if ( Request.QueryString [ `` tm '' ] == 1 ) { insert values to be generated } }
creating a testmode through the url parameter which inserts values into a form
C_sharp : We are trying to list appointments for a given period for a given calendar.For each of those appointments , if the appointment is recurring , we want to know the Id of the master appointment.The issue is that the following code : Is extremely slow , because it makes an EWS call for every recurring appointment.Is there a faster way to get JUST the Id of the recurring master appointment ? <code> ItemId masterId = Appointment.BindToRecurringMaster ( Service , appointment.Id , new PropertySet ( BasePropertySet.IdOnly ) ) ;
EWS : BindToRecurringMaster is slow , just need the recurring master Id
C_sharp : I have the following two methods that get data from my DB and return a populated SelectList object ( including an `` All '' option value ) that I then pass onto my view . The problem is that they are almost identical with the exception that they both access different repository objects and they have different ID names ( StatusId and TeamId ) . I think there is an opportunity to refactor them into a single method that accepts the repository as a parameter and somehow figures out what the ID name should be , perhaps by using reflection or some sort of lambda expression , but I do n't know quite how to accomplish this . Can anyone help figure out how to refactor these into a single method ? <code> private SelectList GetStatusSelectList ( int selectedStatusId ) { List < MemberStatus > statusList = _memberStatusRepository.All ( ) .ToList ( ) ; statusList.Insert ( 0 , new MemberStatus { StatusId = 0 , Name = `` All '' } ) ; var statusSelectList = new SelectList ( statusList , `` StatusId '' , `` Name '' , selectedStatusId ) ; return statusSelectList ; } private SelectList GetTeamSelectList ( int selectedTeamId ) { List < MemberTeam > teamList = _memberTeamRepository.All ( ) .ToList ( ) ; teamList.Insert ( 0 , new MemberTeam { TeamId = 0 , Name = `` All '' } ) ; var teamSelectList = new SelectList ( teamList , `` TeamId '' , `` Name '' , selectedTeamId ) ; return teamSelectList ; }
Refactor two methods that generate a SelectList into a single method
C_sharp : I have two tables in my DataBase , BUNTS , which contains information about pieces of steeland POLL_WEIGHT_BUNTS , which contains information about operations that had been performed on each buntThe relationship is one-to-many . I mapped those tables to models . Everything worked just fine.Recently I 've decided to add a field to table BUNTS which would reference to the last operation that had been performed on bunt : Now my models look like this : After I 've made this , when I try to query Operations like thisit generates an SQL-statement with new incorrect field Bunt_CodeI assume that now EF looks for a field that is a foreign key for BUNTS table , and cant find it . So it generates Bunt_Code field , which is missing in my database . But I already have a property Bunt in BuntOperation class , which references to BUNTS table . What am I missing ? UPDATEseems like this solves my problem <code> CREATE TABLE BUNTS ( BUNTCODE INTEGER NOT NULL , BUNTNAME VARCHAR ( 20 ) , BUNTSTEEL INTEGER , ... ... ) ; CREATE TABLE POLL_WEIGHT_BUNTS ( PWBCODE INTEGER NOT NULL , PWBBUNTCODE INTEGER , PWBDEPARTMENTFROM INTEGER , PWBDEPARTMENTTO INTEGER ... . ) ; BUNTLASTOPER INTEGER [ Table ( `` BUNTS '' ) ] public class Bunt { [ Key ] [ Column ( `` BUNTCODE '' ) ] public int ? Code { set ; get ; } [ Column ( `` BUNTNAME '' ) ] public string Name { set ; get ; } [ Column ( `` BUNTSTEEL '' ) ] public int ? SteelCode { set ; get ; } [ Column ( `` BUNTLASTOPER '' ) ] public int ? LastOperationID { set ; get ; } [ ForeignKey ( `` LastOperationID '' ) ] public BuntOperation LastOperation { set ; get ; } public virtual ICollection < BuntOperation > Operations { set ; get ; } } [ Table ( `` POLL_WEIGHT_BUNTS '' ) ] public class BuntOperation { [ Key ] [ Column ( `` PWBCODE '' ) ] public int ? Code { set ; get ; } [ Column ( `` PWBBUNTCODE '' ) ] public int ? BuntCode { set ; get ; } [ ForeignKey ( `` BuntCode '' ) ] public Bunt Bunt { set ; get ; } [ Column ( `` PWBDEPARTMENTFROM '' ) ] public int ? DepartmentFromCode { set ; get ; } ... .. } return _context.Operations ; SELECT `` B '' . `` PWBCODE '' AS `` PWBCODE '' , `` B '' . `` PWBBUNTCODE '' AS `` PWBBUNTCODE '' , `` B '' . `` PWBDEPARTMENTFROM '' AS `` PWBDEPARTMENTFROM '' , ... . '' B '' . `` Bunt_Code '' AS `` Bunt_Code '' FROM `` POLL_WEIGHT_BUNTS '' AS `` B '' protected override void OnModelCreating ( DbModelBuilder modelBuilder ) { modelBuilder.Entity < Bunt > ( ) .HasOptional ( b = > b.LastOperation ) .WithMany ( ) ; modelBuilder.Entity < Bunt > ( ) .HasMany ( b = > b.Operations ) .WithRequired ( op = > op.Bunt ) ; }
Entity Framework suggest invalid field name
C_sharp : Let 's start this with a little honesty . I am not a fan of goto , but neither am I a fan of repeating my code over and over . Anyway , I hit this scenario . It 's unusual , but not out of this world . I ca n't help but wonder if this is a good scenario for goto . Is there a better way ? Here 's the next best alternative I see : But look at that needless repetition . Thanks for your consideration . <code> public Task Process ( CancellationTokenSource token ) { await SpinUpServiceAsync ( ) ; foreach ( var item in LongList ( ) ) { if ( token.IsCancellationRequested ) goto cancel ; await LongTask1 ( item ) ; if ( token.IsCancellationRequested ) goto cancel ; await LongTask2 ( item ) ; if ( token.IsCancellationRequested ) goto cancel ; await LongTask3 ( item ) ; if ( token.IsCancellationRequested ) goto cancel ; await LongTask4 ( item ) ; if ( token.IsCancellationRequested ) goto cancel ; await LongTask5 ( item ) ; continue ; cancel : { Log ( $ '' Cancelled during { item } '' ) ; await SpinDownServiceAsync ( ) ; return ; } } } public Task Process ( CancellationTokenSource token ) { await SpinUpServiceAsync ( ) ; foreach ( var item in LongList ( ) ) { if ( token.IsCancellationRequested ) { Log ( $ '' Cancelled during { item } '' ) ; await SpinDownServiceAsync ( ) ; return ; } await LongTask1 ( item ) ; if ( token.IsCancellationRequested ) { Log ( $ '' Cancelled during { item } '' ) ; await SpinDownServiceAsync ( ) ; return ; } await LongTask2 ( item ) ; if ( token.IsCancellationRequested ) { Log ( $ '' Cancelled during { item } '' ) ; await SpinDownServiceAsync ( ) ; return ; } await LongTask3 ( item ) ; if ( token.IsCancellationRequested ) { Log ( $ '' Cancelled during { item } '' ) ; await SpinDownServiceAsync ( ) ; return ; } await LongTask4 ( item ) ; if ( token.IsCancellationRequested ) { Log ( $ '' Cancelled during { item } '' ) ; await SpinDownServiceAsync ( ) ; return ; } await LongTask5 ( item ) ; } }
Is there a better way than GOTO in this scenario ?
C_sharp : This generates an error saying I can not convert type ClassType to T. Is there any workaround for this ? Is there any way to specify that the type of this can in fact be converted to T ? <code> public void WorkWith < T > ( Action < T > method ) { method.Invoke ( ( T ) this ) ; }
Cast object to method generic type
C_sharp : Here is a snippet of a class I use for testing Type extension methods : I have the following extension method : Usage in a unit test : This returns a passing test ( using FluentAssertions ) .However , I 'd like to get the method call to GetCustomAttribute ( ) in line 2 down to the following : Is this possible ? Am I missing something ? Maybe I 'm on a caffeine crash . : ( <code> class Something { [ StringLength ( 100 , MinimumLength = 1 , ErrorMessage = `` Must have between 1 and 100 characters '' ) ] public string SomePublicString { get ; set ; } } public static class TypeExtensions { public static TAttributeType GetCustomAttribute < T , TAttributeType , TProperty > ( this T value , Expression < Func < T , TProperty > > propertyLambda , bool inherit = false ) { var type = typeof ( T ) ; var member = ( MemberExpression ) propertyLambda.Body ; var propertyInfo = ( PropertyInfo ) member.Member ; var customAttributes = propertyInfo.GetCustomAttributes ( typeof ( TAttributeType ) , inherit ) ; return customAttributes.OfType < TAttributeType > ( ) .FirstOrDefault ( ) ; } } 1 : var something = new Something ( ) ; 2 : var actual = something.GetCustomAttribute < Something , StringLengthAttribute , string > ( x = > x.SomePublicString ) ; 3 : actual.MinimumLength.Should ( ) .Be ( 1 ) ; 4 : actual.MaximumLength.Should ( ) .Be ( 100 ) ; 5 : actual.ErrorMessage.Should ( ) .Be ( `` Must have between 1 and 100 characters '' ) ; var actual = something.GetCustomAttribute < StringLengthAttribute > ( x = > x.SomePublicString ) ;
Calling a generic extension method without specifying as many types
C_sharp : The original method calling is like : where the api is simply a imported dll reference.Right now I want to add a time out feature to the AskAPI method , so that if the api.Query takes longer than , say 30 seconds , AskAPI will throw an exception.Seems I wo n't be able to get it working . Can anyone share their thoughts about this ? Thanks ! <code> public string AskAPI ( string uri ) { return api.Query ( uri ) ; }
timing out a method call
C_sharp : Recently , in this question , I 've asked how to get a raw memory address of class in C # ( it is a crude unreliable hack and a bad practice , do n't use it unless you really need it ) . I 've succeeded , but then a problem arose : according to this article , first 2 words in the class raw memory representation should be pointers to SyncBlock and RTTI structures , and therefore the first field 's address must be offset by 2 words [ 8 bytes in 32-bit systems , 16 bytes in 64-bit systems ] from the beginning . However , when I dump first bytes from memory at the object location , first field 's raw offset from the object 's address is only 1 32-bit word ( 4 bytes ) , which does n't make any sense for both types of systems . From the question I 've linked : Why is so ? Maybe I 've just got the address wrong , but how and why ? And if I did n't , what could be wrong anyway ? Maybe , if that article is wrong , I simply misunderstood what managed class header looks like ? Or maybe it does n't have that Lock pointer - but why and how is this possible ? .. ( These are , obviously , only a few possible options , and , while I 'm still going to carefully check each one I can predict , wild guessing can not compare in both time and accuracy to a correct answer . ) <code> class Program { // Here is the function . // I suggest looking at the original question 's solution , as it is // more reliable . static IntPtr getPointerToObject ( Object unmanagedObject ) { GCHandle gcHandle = GCHandle.Alloc ( unmanagedObject , GCHandleType.WeakTrackResurrection ) ; IntPtr thePointer = Marshal.ReadIntPtr ( GCHandle.ToIntPtr ( gcHandle ) ) ; gcHandle.Free ( ) ; return thePointer ; } class TestClass { uint a = 0xDEADBEEF ; } static void Main ( string [ ] args ) { byte [ ] cls = new byte [ 16 ] ; var test = new TestClass ( ) ; var thePointer = getPointerToObject ( test ) ; Marshal.Copy ( thePointer , cls , 0 , 16 ) ; //Dump first 16 bytes ... Console.WriteLine ( BitConverter.ToString ( BitConverter.GetBytes ( thePointer.ToInt32 ( ) ) ) ) ; Console.WriteLine ( BitConverter.ToString ( cls ) ) ; Console.ReadLine ( ) ; gcHandle.Free ( ) ; } } /* Example output ( yours should be different ) :40-23-CA-024C-38-04-01-EF-BE-AD-DE-00-00-00-80-B4-21-50-73That field 's value is `` EF-BE-AD-DE '' , 0xDEADBEEF as it is stored in memory . Yay , we found it ! */
What are layout and size of a managed class 's header in unmanaged memory ?
C_sharp : I love generics in C # , but sometimes working with them can get a bit complicated . The problem below I run into every now and then . Is there any way of making this scenario simpler ? I ca n't see how , but I 'm hoping someone can : ) Given three base classes : And some simple implementations : Now my question is : For HandleOut , the type of TInner is given by the type `` Out '' , so is there any way to simplify the definition of HandleOut to something like public class HandleOut : Handler < Out > and still be able to use the inner type as a parameter to SetValue ? This is a very simple example , but I sometimes get a long list of generic types in definitions , when usually all of them can be logically deduced from the first type . Are there any tricks I 'm missing ? <code> public abstract class Inner { } public abstract class Outer < T > where T : Inner { } public abstract class Handler < TOuter , TInner > where TOuter : Outer < TInner > where TInner : Inner { public abstract void SetValue ( TInner value ) ; } public class In : Inner { } public class Out : Outer < In > { } public class HandleOut : Handler < Out , In > { public override void SetValue ( In value ) { } }
Is it possible to simplify nested generics in C # ?
C_sharp : I recently heard about the new C # Feature in 7.2 , so that we now can return a reference of value type ( for example int ) or even a readonly reference of a value type . So as far as I know a value type is stored in the stack . And when the method is left , they are removed from stack . So what happens with the int when the method GetX exits ? I 'm getting the error Error CS8168 : Can not return local 'myInt ' by reference because it is not a ref local ( 11 , 24 ) So why does it not work ? Does it not work just because the variable can not be moved to the heap ? Is this the problem ? can we only return value types by reference if they do not live in the stack ? I know that this are two question in one.First : Where do value type-variables returned by ref live ? Stack or heap ? ( I guess on the heap but why ) ? Second : Why can a value type created on the stack not be returned by reference ? So this is able to be compiled : If I understand your comments right it is because now the _myInt lives not inside the method GetX and there fore is not created in the stack right ? <code> private ref int GetX ( ) { // myInt is living on the stack now right ? int myInt = 5 ; return ref myInt ; } private void CallGetX ( ) { ref int returnedReference = ref GetX ( ) ; // where does the target of 'returnedReference ' live now ? // Is it somehow moved to the heap , because the stack of 'GetX ' was removed right ? } private int _myInt ; private ref int GetX ( ) { // myInt is living on the stack now right ? _myInt = 5 ; return ref _myInt ; } private void CallGetX ( ) { ref int returnedReference = ref GetX ( ) ; // where does the target of 'returnedReference ' live now ? // Is it somehow moved to the heap ? becase the stack of 'GetX ' was removed right ? }
Where does a value type-variable - which is returned by ref - live ? Stack or heap ?
C_sharp : I need convert short to VariantTypeMy try ( works not correct ) So how can I convert short to VariantType ? ( vb.net tag because VariantType is from Microsoft.VisualBasic ) <code> VariantType vt = ( VariantType ) vt ;
Convert short to VariantType ( extract VariantType from short )
C_sharp : In MVC what is the best method to manage exceptions or errors in the business ? I found several solutions but do not know which to choose.Solution 1Solution 2Solution 3Solution 4 <code> public Person GetPersonById ( string id ) { MyProject.Model.Person person = null ; try { person = _personDataProvider.GetPersonById ( id ) ; } catch { // I use a try / catch to handle the exception and I return a null value // I do n't like this solution but the idea is to handle excpetion in // business to always return valid object to my MVC . person = null ; } return person ; } public Person GetPersonById ( string id ) { MyProject.Model.Person person = null ; person = _personDataProvider.GetPersonById ( id ) ; // I do nothing . It to my MVC to handle exceptions return person ; } public Person GetPersonById ( string id , ref MyProject.Technical.Errors errors ) { MyProject.Model.Person person = null ; try { person = _personDataProvider.GetPersonById ( id ) ; } catch ( Exception ex ) { // I use a try / catch to handle the exception but I return a // collection of errors ( or status ) . this solution allow me to return // several exception in case of form validation . person = null ; errors.Add ( ex ) ; } return person ; } // A better idea ?
In MVC what is the best method to manage exceptions or errors in the business ?
C_sharp : So , want to make a multi-row insert query , and I need to replace the keys with the values inside a loop where I have the values.It was working by hardcoding the values into the query string , but I need to do it by using the `` cmd.Parameters.AddValue ( ) or cmd.Parameters.AddWithValue ( ) '' as I need to prevent SQL Injection.So , my code is something like this : I want to ExecuteNonQuery ( ) ; outside the loop , to make just one insert.Any ideas ? I thought about making a loop where I add the keys in the string with a identifier and then replacing all of them iterating another loop with the same id 's , but I do n't see that very efficient or a good practice . <code> string query = `` insert into dbo.Foo ( column1 , column2 , column3 ) values `` ; SqlCommand cmd foreach ( line in rowsArray ) { cmd.Parameters.Clear ( ) ; cmd = new SqlCommand ( query , cnn ) ; //So , the problem is this override query += `` ( @ key1 , @ key2 , @ key3 ) , `` ; cmd.Parameters.AddWithValue ( `` @ key1 '' , line.value1 ) ; cmd.Parameters.AddWithValue ( `` @ key2 '' , line.value2 ) ; cmd.Parameters.AddWithValue ( `` @ key3 '' , line.value3 ) ; } query = query.Substring ( 0 , query.Length-2 ) ; //Last comma cmd.ExecuteNonQuery ( ) ; cnn.Close ( ) ;
Add SQL Parameters inside the loop , excecute outside the loop . ( Single query multi-insert with parameters in C # SQL Client )
C_sharp : Resharper is always asking me to change foreach loops into linq , and I try to . This one stumped me.The fileEnvironment is returned as an object from the configuration section . That 's the reason for the cast . <code> foreach ( var fileEnvironment in fileEnvironmentSection.FileEnvironmentList ) { var element = fileEnvironment as FileEnvironmentElement ; if ( element == null ) { //Not the expected type , so nothing to do } else { //Have the expected type , so add it to the dictionary result.Add ( element.Key , element.Value ) ; } }
This foreach has a cast in the middle , can it be translated to linq ?
C_sharp : The best way to do this ? Tried things like that : Did n't work for me , maybe someone could give me a clean Solution on how I can do that . <code> public String FormatColumnName ( String columnName ) { String formatedColumnName = columnName.Replace ( ' _ ' , ' ' ) .Trim ( ) ; StringBuilder result = new StringBuilder ( formatedColumnName ) ; result [ 0 ] = char.ToUpper ( result [ 0 ] ) ; return result.ToString ( ) ; }
C # String Manipulation : From `` TABLE_NAME '' to `` TableName ''
C_sharp : I am a little confused by the behavior of my code [ below ] . I am working on a specialized , command line utility that downloads and processes some files . I am trying to use c # 's async functionality when possible . The code snippet runs as expected when the tasks are created and Task.WaitAll ( ) is used . After the wait I have 2 tasks both of which have been marked as completed . The issue : My attempt to fetch the results from the tasks ends up running both tasks a second time ! Why is this ? How can I read the result without executing the task a second time ? And if relevant here is the download method : <code> private IEnumerable < Task < FileInfo > > DownloadFiles ( ) { int fileCount = 1 ; Console.Clear ( ) ; Console.SetCursorPosition ( 0 , 0 ) ; Console.Write ( `` Download files ... '' ) ; yield return DownloadFile ( Options.SkuLookupUrl , `` SkuLookup.txt.gz '' , fileCount++ , f = > { return DecompressFile ( f ) ; } ) ; yield return DownloadFile ( Options.ProductLookupUrl , `` ProductList.txt.gz '' , fileCount++ , f = > { return DecompressFile ( f ) ; } ) ; } public void Execute ( ) { var tasks = DownloadFiles ( ) ; Task.WaitAll ( tasks.ToArray ( ) ) ; Console.WriteLine ( ) ; Console.WriteLine ( `` Download ( s ) completed . Parsing sku lookup file . `` ) ; FileInfo [ ] files = tasks.Select ( t = > t.Result ) .ToArray ( ) ; // < -- triggers a second round of task execution ParseSkuLookups ( files.SingleOrDefault ( f = > f.Name.ToLowerInvariant ( ) .Contains ( `` skulookup '' ) ) ) ; } private async Task < FileInfo > DownloadFile ( string targetUrl , string destinationFile , int lineNumber , Func < FileInfo , FileInfo > callback = null ) { FileInfo fi = new FileInfo ( destinationFile ) ; if ( ! Options.NoCleanup || ! fi.Exists ) { WebClient client = new WebClient ( ) ; client.DownloadProgressChanged += ( s , e ) = > { char spinnerChar ; switch ( ( e.ProgressPercentage % 10 ) ) { case 0 : spinnerChar = '| ' ; break ; case 1 : spinnerChar = '/ ' ; break ; case 2 : spinnerChar = '- ' ; break ; case 3 : spinnerChar = '| ' ; break ; case 4 : spinnerChar = '\\ ' ; break ; case 5 : spinnerChar = '| ' ; break ; case 6 : spinnerChar = '/ ' ; break ; case 7 : spinnerChar = '- ' ; break ; case 8 : spinnerChar = '\\ ' ; break ; default : case 9 : spinnerChar = '| ' ; break ; } lock ( ConsoleLockSync ) { Console.SetCursorPosition ( 0 , lineNumber ) ; Console.WriteLine ( String.Format ( `` { 0 } download : { 1 } % { 2 } '' , destinationFile , e.ProgressPercentage==100 ? `` [ Complete ] '' : spinnerChar.ToString ( ) ) ) ; } } ; await client.DownloadFileTaskAsync ( new Uri ( targetUrl , UriKind.Absolute ) , destinationFile ) ; } else if ( Options.NoCleanup ) { lock ( ConsoleLockSync ) { Console.SetCursorPosition ( 0 , lineNumber ) ; Console.WriteLine ( String.Format ( `` { 0 } download : Skipped [ No Cleanup ] `` , destinationFile ) ) ; } } fi.Refresh ( ) ; return callback ! = null ? callback ( fi ) : fi ; }
Completed c # Task Runs Again ... Why ?
C_sharp : I have an ASP.NET 4.7.2 MVC 5 application that uses ASP.NET Identity and the OWIN OAuthAuthorizationServerMiddleware . In the RefreshTokenProvider.OnReceive method i 'm accessing the SignInManager.CreateUserIdentity method which is an ASP.NET Identity method that internally uses AsyncHelper ( see below ) to call the asynchronous method . Every so often ( typically months apart on a busy system ) , this breaks down and locks up the entire application . From a memory dump i 've gathered , there were 565 threads waiting inside GetResultThe memory dump showed 580+ Tasks , that were all in the RanToCompletion state . I was unable to diagnose why GetResult does not succeed , given that the Task has completed , nor why that many threads pile up there rapidly when it worked for months before and why the entire app becomes unresponsive , even if they do n't exercise this path . This caused a production outage now multiple times and i do n't see how to resolve this other than rebooting it.I 've tried to use the OnReceiveAsync method but those seem pointless because before they 're invoked , there 's this little snippet : EDIT : Reproduction and explanation of the issue : The issue can be reproduced by this WebAPI 2 Controllerand this program to generate loadWhat the program will do , is hit the application with 100 requests in just a few milliseconds . This will lead to all previously free threads being stuck at AsyncHelper.RunSync with a lot more requests queued and no response being sent yet at all . The ThreadPool notices that it needs more threads but will add about only one thread per second which will immediately get stuck at AsyncHelper.RunSync trying to serve one of the queued requests . About a minute later , when the ThreadPool has expanded by about 100 additional threads to serve the 100 requests , all pending requests will respond in the blink of an eye and the application is responsive again.The difference on my app is , that requests keep comming in , unlike the sample where only 100 requests are sent at once . This means my app ca n't recover from this scenario as the ThreadPool does not create new threads fast enough to keep up with incomming requests.Creating an async copy of my ReceiveRefreshToken method and populating OnReceiveAsync in addition to OnReceive appears to avoid the problem enough to not get exhausted on the ThreadPool . <code> // Copyright ( c ) Microsoft Corporation , Inc. All rights reserved.// Licensed under the MIT License , Version 2.0 . See License.txt in the project root for license information.using System ; using System.Globalization ; using System.Threading ; using System.Threading.Tasks ; namespace Microsoft.AspNet.Identity { internal static class AsyncHelper { private static readonly TaskFactory _myTaskFactory = new TaskFactory ( CancellationToken.None , TaskCreationOptions.None , TaskContinuationOptions.None , TaskScheduler.Default ) ; public static TResult RunSync < TResult > ( Func < Task < TResult > > func ) { var cultureUi = CultureInfo.CurrentUICulture ; var culture = CultureInfo.CurrentCulture ; return _myTaskFactory.StartNew ( ( ) = > { Thread.CurrentThread.CurrentCulture = culture ; Thread.CurrentThread.CurrentUICulture = cultureUi ; return func ( ) ; } ) .Unwrap ( ) .GetAwaiter ( ) .GetResult ( ) ; } public static void RunSync ( Func < Task > func ) { var cultureUi = CultureInfo.CurrentUICulture ; var culture = CultureInfo.CurrentCulture ; _myTaskFactory.StartNew ( ( ) = > { Thread.CurrentThread.CurrentCulture = culture ; Thread.CurrentThread.CurrentUICulture = cultureUi ; return func ( ) ; } ) .Unwrap ( ) .GetAwaiter ( ) .GetResult ( ) ; } } } if ( OnReceiveAsync ! = null & & OnReceive == null ) { throw new InvalidOperationException ( Resources.Exception_AuthenticationTokenDoesNotProvideSyncMethods ) ; } using System.Threading.Tasks ; using System.Web.Http ; namespace WebApplication65.Controllers { public class ValuesController : ApiController { public string Post ( [ FromBody ] string value ) { return AsyncHelper.RunSync ( PostAsync ) ; } private async Task < string > PostAsync ( ) { await Task.Delay ( 10 ) ; return `` Hello World '' ; } } } using System ; using System.Collections.Generic ; using System.Net.Http ; using System.Net.Http.Headers ; using System.Threading.Tasks ; namespace ConsoleApp36 { class Program { static void Main ( string [ ] args ) { HttpClient client = new HttpClient ( ) ; MediaTypeHeaderValue mediaTypeHeaderValue = new MediaTypeHeaderValue ( `` application/json '' ) ; var tasks = new List < Task > ( ) ; for ( int i = 0 ; i < 100 ; i++ ) { int x = i ; var t = Task.Run ( async ( ) = > { var content = new StringContent ( `` \ '' '' + Guid.NewGuid ( ) .ToString ( ) + `` \ '' '' ) ; content.Headers.ContentType = mediaTypeHeaderValue ; await client.PostAsync ( `` https : //localhost:44371/api/values '' , content ) ; Console.WriteLine ( x ) ; } ) ; tasks.Add ( t ) ; } Task.WhenAll ( tasks ) .Wait ( ) ; } } }
Sporadic application deadlock in ASP.NET Identity
C_sharp : If you install the nuget Ninject package for mvc , it puts a NinjectWebCommon.cs file in the App_Start folder . I understand 99 % of the stuff in this file apart from this line : Full code file here on GitHubIn my mind , it would be better to use : As the static instance is already defined at the top of the file , and thus it will get the kernal that has all the mappings built.After some googling it seems this is also common : What is the reasoning behind the way the boilerplate code is the way it is ? <code> kernel.Bind < Func < IKernel > > ( ) .ToMethod ( ctx = > ( ) = > new Bootstrapper ( ) .Kernel ) ; kernel.Bind < Func < IKernel > > ( ) .ToMethod ( ctx = > ( ) = > bootstrapper.Kernel ) ; kernel.Bind < Func < IKernel > > ( ) .ToMethod ( ctx = > ( ) = > ctx.Kernel ) ;
Understanding Ninject mvc 3 boiler plate code
C_sharp : Goal : Spin up 20 threads that will all hit the SessionFactory.GetSessionFactory ( key ) method at the same time for testing purposes . ( I 'm trying to simulate a multi-threaded environment such as ASP.NET ) Question : By using the EndInvoke ( ) method am I essentially calling the GetSessionFactory ( key ) method synchronously or is my code correct in simulating multiple threads all hitting GetSessionFactory ( key ) at the same time ? Thanks , Kyle <code> public void StressGetSessionFactory ( ) { for ( int i = 0 ; i < 20 ; i++ ) { Func < string , ISessionFactory > method = GetSessionFactory ; IAsyncResult asyncResult = method.BeginInvoke ( `` RBDB '' , null , null ) ; ISessionFactory sessionFactory = method.EndInvoke ( asyncResult ) ; //My concern is with this call Debug.WriteLine ( `` RBDB ISessionFactory ID : `` + sessionFactory.GetHashCode ( ) ) ; } } static ISessionFactory GetSessionFactory ( string key ) { return SessionFactory.GetSessionFactory ( key ) ; }
Is this code actually multithreaded ?
C_sharp : I have a huge text file around 2GB which I am trying to parse in C # .The file has custom delimiters for rows and columns . I want to parse the file and extract the data and write to another file by inserting column header and replacing RowDelimiter by newline and ColumnDelimiter by tab so that I can get the data in tabular format.sample data:1'~ ' 2'~ ' 3 # # # # # 11'~'12'~'13 RowDelimiter : # # # # # ColumnDelimiter : '~ ' I keep on getting System.OutOfMemoryException on the following line while ( ( line = rdr.ReadLine ( ) ) ! = null ) <code> public void ParseFile ( string inputfile , string outputfile , string header ) { using ( StreamReader rdr = new StreamReader ( inputfile ) ) { string line ; while ( ( line = rdr.ReadLine ( ) ) ! = null ) { using ( StreamWriter sw = new StreamWriter ( outputfile ) ) { //Write the Header row sw.Write ( header ) ; //parse the file string [ ] rows = line.Split ( new string [ ] { ParserConstants.RowSeparator } , StringSplitOptions.None ) ; foreach ( string row in rows ) { string [ ] columns = row.Split ( new string [ ] { ParserConstants.ColumnSeparator } , StringSplitOptions.None ) ; foreach ( string column in columns ) { sw.Write ( column + `` \\t '' ) ; } sw.Write ( ParserConstants.NewlineCharacter ) ; Console.WriteLine ( ) ; } } Console.WriteLine ( `` File Parsing completed '' ) ; } } }
Parsing a huge text file ( around 2GB ) with custom delimiters
C_sharp : In msdn link , it is mentioned thatDo not throw System.Exception or System.SystemException.In my code i am throwing like thisis this a bad practice ? ? <code> private MsgShortCode GetshortMsgCode ( string str ) { switch ( str.Replace ( `` `` , '' '' ) .ToUpper ( ) ) { case `` QNXC00 '' : return MsgShortCode.QNXC00 ; default : throw new Exception ( `` Invalid message code received '' ) ; } }
Best practices for Catching and throwing the exception
C_sharp : Ran into this as part of some EF/DB code today and ashamed to say I 'd never encountered it before.In .NET you can explicitly cast between types . e.g.And you can box to object and unbox back to that original typeBut you ca n't unbox directly to a type that you can explicitly cast toThis is actually documented behaviour , although I never actually run into it until today . https : //docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/boxing-and-unboxing # example-1 For the unboxing of value types to succeed at run time , the item being unboxed must be a reference to an object that was previously created by boxing an instance of that value type . Attempting to unbox null causes a NullReferenceException . Attempting to unbox a reference to an incompatible value type causes an InvalidCastException.I 'm curious is there some technical reason why this is n't possible/supported by the runtime ? <code> int x = 5 ; long y = ( long ) x ; int x = 5 ; object y = x ; int z = ( int ) y ; int x = 5 ; object y = x ; long z = ( long ) y ;
Why ca n't you unbox directly to a type which you can explicity cast to ?
C_sharp : Last day closing stock should be the opening stock value of the next day.I have tried this Table structureID , STOCK_DATE , STOCK_QTYPlease any one can help to solve this I need to print like thisThanks in advance . <code> var k = INV_STOCKs.Select ( x = > new DemoItemV1 { AreaId = x.STOCK_DATE , CategoryTitle = x.STOCK_QTY } ) .AsEnumerable ( ) .Select ( ( x , i ) = > { x.ID = i + 1 ; return x } ) .ToList ( ) ; Date Opening Stock Closing Stock01/01/13 0 501/02/13 5 1001/03/13 10 1501/04/13 15 2201/05/13 22 30
Stock data carry over to next day in LINQ
C_sharp : If I have a very large IEnumerable collection , in the order of millions of objects , that would be too large to load all at once . The collections is returned via a yield method : This Data is consumed in a single Foreach loop : I know that the collection under the IEnumerable is getting loaded one object at a time , but are the objects getting removed once they have been used in the ForEach or do they remain in the collection until the ForEach is complete . <code> private static IEnumerable < MyData > ExtractModelsFromDb ( ) { using ( DbDataReader reader = cmd.ExecuteReader ( ) ) { while ( reader.Read ( ) ) { Load MyData yield return MyData ; } reader.Close ( ) ; } } public void RunStuff ( ) { var myCollection = ExtractModelsFromDb ( ) ; foreach ( var data in myCollection ) { //DO STUFF } }
Does a IEnumerable store objects after use
C_sharp : I have created a roslyn CodeAnalyzer and a CodeFixProvider.The Analyzer runs fine , and creates the rule , but when I 'm trying to open the popup showing the fix , I get a `` One or more errors occurred '' VS popup.First time I ran it , it worked fine , but then I stopped debugging and after that it gave me that error , so I tried on another computer and again it worked fine the first time I debugged.My Analyzer : My CodeFixProviderWhat I 'm trying to achive isBecomesWhen you press ctrl+ . on `` stat '' ... And it is here that VS2015 gives the error , just not first time ... <code> private static void Analyze ( SyntaxNodeAnalysisContext context ) { var localDeclaration = ( LocalDeclarationStatementSyntax ) context.Node ; foreach ( var variable in localDeclaration.Declaration.Variables ) { var initializer = variable.Initializer ; if ( initializer == null ) return ; } var node = context.Node ; while ( node.Kind ( ) ! = SyntaxKind.MethodDeclaration ) { node = node.Parent ; } var method = ( MethodDeclarationSyntax ) node ; if ( method.AttributeLists.Any ( x = > x.Attributes.Any ( y = > y.Name is IdentifierNameSyntax & & ( ( IdentifierNameSyntax ) y.Name ) .Identifier.Text.ToLower ( ) .Contains ( `` test '' ) ) ) ) { context.ReportDiagnostic ( Diagnostic.Create ( Rule , context.Node.GetLocation ( ) ) ) ; } } private async Task < Document > AddAssertionsAsync ( Document document , LocalDeclarationStatementSyntax localDeclaration , CancellationToken cancellationToken ) { var editor = await DocumentEditor.CreateAsync ( document , cancellationToken ) ; var assert = SyntaxFactory.IdentifierName ( `` Assert '' ) ; var areEqual = SyntaxFactory.IdentifierName ( `` AreEqual '' ) ; var memberAccess = SyntaxFactory.MemberAccessExpression ( SyntaxKind.SimpleMemberAccessExpression , assert , areEqual ) ; var firstArgument = SyntaxFactory.Argument ( SyntaxFactory.LiteralExpression ( SyntaxKind.StringLiteralExpression , SyntaxFactory.Literal ( @ '' '' ) ) ) ; var secondArgument = SyntaxFactory.Argument ( SyntaxFactory.LiteralExpression ( SyntaxKind.StringLiteralExpression , SyntaxFactory.Literal ( @ '' '' ) ) ) ; var argumentList = SyntaxFactory.SeparatedList < ArgumentSyntax > ( new SyntaxNodeOrToken [ ] { firstArgument , SyntaxFactory.Token ( SyntaxKind.CommaToken ) , secondArgument } ) ; var assertToken = SyntaxFactory.ExpressionStatement ( SyntaxFactory.InvocationExpression ( memberAccess , SyntaxFactory.ArgumentList ( argumentList ) ) ) ; editor.InsertAfter ( localDeclaration , assertToken ) ; var newDocument = editor.GetChangedDocument ( ) ; return newDocument ; } [ Test ] public void blah ( ) { var stat = string.Empty ; } [ Test ] public void blah ( ) { var stat = string.Empty ; Assert.AreEqual ( `` '' , `` '' ) ; }
Roslyn CodeFixProvider gives VS 2015 error
C_sharp : I need to create functionality that would allow users to filter entities using literal queries ( i.e . age gt 20 and name eq 'john ' ) . Is there a provided functionality to do this in C # /Asp.Net MVC or do I have to parse this query by myself ? I found that OData implies having exactly such functionality ( OData Filter Expressions MSDN ) . However , I 'm not familiar with it so I do n't know how to implement such behavior in my project.I need something like this : Any advice would be appreciated . <code> var list = new List < Person > { new Person { Name = `` John '' , Age = 30 } , new Person { Name = `` Hanna '' , Age = 25 } , new Person { Name = `` John '' , Age = 15 } } ; string query = `` age gt 20 and name eq /'John/ ' '' ; IEnumerable < Person > result = list.FilterByExpression ( query ) ; // returns list with John aged 30
How to filter entities using queries in C # ?
C_sharp : I have the following code : It compiles , runs and obviously I get an System.InvalidCastException.Why does the compiler not complain ? MyClass is a simple bean , no extensions.Edit 1 : As suggested by David switching the type from IList to List the compiler complainsEdit 2 : I 've understood that the behaviour is as specified in the C # Language definition . However , I do n't understand why such a cast/conversion is allowed , since at runtime I always get an InvalidCastException . I opened this in order to go deeper . <code> IEnumerable < IList < MyClass > > myData = // ... getMyDataforeach ( MyClass o in myData ) { // do something }
C # foreach on IEnumerable < IList < object > > compiles but should n't
C_sharp : I have been meddling with an idea in C # to create a piece of software ( for pseudo-personal usage ) but ran into implementation problems . Well ... maybe they are design problems I am unaware of , but I just simply ca n't figure out.The idea , expectation and general pseudo algorithmConsider we have the following `` database '' : These are recipes for creating the said items . Using one Foo and one Bar , we create a Foobar result which can further be an ingredient for another recipe.Now think that we need to figure out the full recipe for the item Foobarbazqux . For the human mind and intelligence , it 's relatively easy : And of course , if and when we have all ingredients at our disposal , we can `` run '' the recipe and create the items with executing each recipe in the order a few paragraphs above . ( So like : we first create Foobar , then Bazqux , then combine the two to get the final result . ) But in real time , the database is a lot bigger . That 's where , I suppose , computers should come in . With a working software , the machine could easily find all the ingredients and execution ( crafting ) steps and give it to the user , so we do n't need to read through ALL the entries by hand.The implementation ( ... attempt ) I have thought about using C # for achieving this piece of software . Command-line project , nothing shiny or anything , just pure stdio.First , of course , I needed to define the item . ( Note : Right now I think about using structs , but if needed , I can `` upgrade '' them to classes . The `` database '' is initialized from some sort of sequential text file which will be made later . The `` database '' is not altered or written in any manner during or after execution , once it is loaded , it 's read-only . ) And of course , I needed to define the recipe.These two structs are held in a generic , static List < > field of Program ( the default class ) .At entry point , we define some items and some recipes for testing : Because items are primary keyed by their Name field , GetItem is simply a List.Find < > shortcut : So right now , the database is set . I have realized that I need to make some sort of recursive method to fetch all the ingredients , but this is where I came to problem.Consider the following , first attempt ( this is not recursive , only goes `` one level deep '' ) : This produces the following output , which is , without recursion , is pretty fine and expected : So for the recursion , I modified the code like this : Now the output is the following : I see what happens as I understand my code right now . Lines marked with * are recursions for Foobar , @ are recursions for Bazqux and | are the output of the original method call . But this is n't ... kinda the output I would want to implement , as it fails to be understood easily and ... is n't generally right.The expected output and the questionThe output I visualized is something like the following ( of course the `` extra '' status lines are ignorable ) : This is what I call as breaking down the chain of item creation recipes ... or ... I do n't call , but imagine so , in reference to the question 's title . So the program works as : User enters the `` final '' item they are searching for ( this is Foobarbazqux in our example ) The program ravages the database enough times so first the ingredients of the searched item are found , and then it recurses ( ? ) deeper until it finds only subatomic ingredients that can not be `` crafted '' from others : they are not a Result for any Recipe . ( While working so ) output is shown.Note : Fits the real scenario better , but makes an extra implementation gap : Much of the items have more than one recipes from which they can be created.What I would like to ask for is advices and help . I am slowly wanting to convince myself that this program is unwritable ( which is only some sort of desperate outcry ) and that my idea has design issues . But I still hope that , within boundaries , we do n't need fancy , yet-to-be-created AI systems to solve this ... kinda underestimatable problem.Thank you . <code> Foo + Bar = FoobarBaz + Qux = BazquxFoobar + Bazqux = Foobarbazqux We need FoobarbazquxFoobarbazqux = Foobar + Bazqux Foobar = Foo + Bar Bazqux = Baz + QuxFoobarbazqux = Foo + Bar + Baz + Qux struct Item { public string Name ; } struct Recipe { public Item Result ; public Item [ ] Ingredients ; } items.Add ( new Item { Name = `` Foo '' } ) ; items.Add ( new Item { Name = `` Bar '' } ) ; items.Add ( new Item { Name = `` Baz '' } ) ; items.Add ( new Item { Name = `` Qux '' } ) ; items.Add ( new Item { Name = `` Foobar '' } ) ; items.Add ( new Item { Name = `` Bazqux '' } ) ; items.Add ( new Item { Name = `` Foobarbazqux '' } ) ; recipes.Add ( new Recipe { Result = GetItem ( `` Foobar '' ) , Ingredients = new Item [ ] { GetItem ( `` Foo '' ) , GetItem ( `` Bar '' ) } } ) ; recipes.Add ( new Recipe { Result = GetItem ( `` Bazqux '' ) , Ingredients = new Item [ ] { GetItem ( `` Baz '' ) , GetItem ( `` Qux '' ) } } ) ; recipes.Add ( new Recipe { Result = GetItem ( `` Foobarbazqux '' ) , Ingredients = new Item [ ] { GetItem ( `` Foobar '' ) , GetItem ( `` Bazqux '' ) } } ) ; private static Item GetItem ( string _name ) { return Program.Items.Find ( match = > match.Name == _name ) ; } string search = `` Foobarbazqux '' ; SearchRecipe ( search ) ; private static void SearchRecipe ( string _search ) { List < Recipe > item_recipes = Program.Recipes.FindAll ( match = > match.result.Name == GetItem ( search ) .Name ) ; foreach ( Recipe recp in item_recipes ) { Console.WriteLine ( `` -- -- -- -- -- -- - '' ) ; Console.WriteLine ( `` Ingredients : `` ) ; foreach ( Item ingredient in recp.Ingredients ) { Console.WriteLine ( ingredient.Name ) ; } } } -- -- -- -- -- -- -Ingredients : FoobarBazqux foreach ( Item ingredient in recp.Ingredients ) { +++ if ( recipes.FindAll ( match2 = > match2.Result.name == Ingredient.name ) .Count ! = 0 ) +++ { +++ SearchRecipe ( ingredient.Name ) ; +++ } Console.WriteLine ( ingredient.Name ) ; } | -- -- -- -- -- -- -| Ingredients : * -- -- -- -- -- -- -* Ingredients : * Foo* Bar| Foobar @ -- -- -- -- -- -- - @ Ingredients : @ Baz @ Qux| Bazqux Searching for : Foobarbazqux1 recipe found. -- -- -1 Foobarbazqux = 1 Foobar + 1 Bazqux1 Foobar = 1 Foo + 1 Bar1 Bazqux = 1 Baz + 1 Qux1 Foobarbazqux = 1 Foo + 1 Bar + 1 Baz + 1 Qux1 Foo + 1 Bar = > 1 Foobar1 Baz + 1 Qux = > 1 Bazqux1 Foobar + 1 Bazqux = > 1 Foobarbazqux -- -- -Exit .
Breaking down chain of item creation equation chain ( possibly with recursion )
C_sharp : I have a sample program with a base Fruit class and a derived Apple class.I want to have a list of fruit delegates and be able to add delegates of more derived fruit to the list . I believe this has something to do with covariance or contravariance but I can not seem to figure it out.The error message is ( without namespaces ) : <code> class Testy { public delegate void FruitDelegate < T > ( T o ) where T : Fruit ; private List < FruitDelegate < Fruit > > fruits = new List < FruitDelegate < Fruit > > ( ) ; public void Test ( ) { FruitDelegate < Apple > f = new FruitDelegate < Apple > ( EatFruit ) ; fruits.Add ( f ) ; // Error on this line } public void EatFruit ( Fruit apple ) { } } The best overloaded method match for 'List < FruitDelegate < Fruit > > .Add ( FruitDelegate < Fruit > ) ' has some invalid arguments `
How to add an apple delegate to a list of fruit delegates ?