lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
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 th...
// 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....
Are some keyboards more loquacious than others ?
C#
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 ...
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#
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.F...
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.GetILGener...
Why does this work ? Executing method from IL without instance
C#
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...
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#
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 cod...
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...
how to avoid the repeated code to increase the efficiency
C#
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 ?
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#
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 ...
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 br...
Compiler doesnt recognise property in generic if declaration is an interface
C#
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 ...
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 < Em...
ASP.NET CurrentUICulture behaves differently in Task and WebAPI deferred result
C#
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 ...
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 ...
Threading concept in C #
C#
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 approa...
// 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 , dou...
How do I reuse an Expression when building a more complex one ?
C#
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 AGener...
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 n...
Prevent a particular hierarchy of types being used for a generic parameter
C#
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...
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#
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 typ...
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 ; ...
Track whether a user typed an specific `` word '' on an WinForm
C#
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 . Fo...
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.Re...
How to support multiple custom types ?
C#
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 ?
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#
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 ent...
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 _p...
Is it possible to wrap specific classes or methods and assign them to a thread ?
C#
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 co...
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#
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 cra...
< ? 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 ( ' $ ( MS...
Using NuGet libraries in an Unmanaged C # .NET library project
C#
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 ...
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...
How to get IEnumerable < Foo > instead of IEnumerable < string > from LINQ ?
C#
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 t...
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 ; } pr...
Expression Tree GetString Result
C#
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
*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#
Why does the following piece of code work ? call : code : Is this allowed to work or just a bug ?
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#
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 par...
< 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 ) ) ;...
Enforce REAL non-nullable string reference type
C#
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 kn...
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 ( ) ; Cons...
Why no deadlock in this scenario ?
C#
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 >...
public class AggregatedClass : ICollection < SingleClass > { List < SingleClass > _singleClassList ; // ... rest of code }
Collections and Lists
C#
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...
object.myEvent -= new MyEvent ( EventHandler ) ;
Why is `` new '' operator working for detaching a eventhandler using -= ?
C#
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 o...
-- 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 ...
Multiline Regex matches first occurance but ca n't match second
C#
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 ?
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#
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 '' ....
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...
Curve fitting to a 3D polynomial with variable powers
C#
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 wit...
var myCat = catList.Single ( c = > c.Id == 7 ) ; mycat.Name = `` Dr Fluffykins '' ;
Update the property of a struct within a List in C #
C#
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 settin...
[ 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.000...
ASP.NET DateTime Serialization in QueryString vs Body
C#
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 te...
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#
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 ?
namespace PIMP.Web.TestForum.Models { public class ThreadModel : PagedList < T > {
Implementing of class with < T >
C#
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 ?
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#
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 ?
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#
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 , acco...
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 } // en...
Jitter logic to remove unbox_any
C#
Can someone explain this behavior ? StartsWith works same .
`` `` .EndsWith ( ( ( char ) 9917 ) .ToString ( ) ) // returns true
Unexpected behavior with EndsWith
C#
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 t...
// 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-pl...
Local reference to inner array in swift
C#
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 th...
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 ] = gr...
Giving Multiple List < int > type criteria by using linq in Entity Framework
C#
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 ...
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...
Object exits portal moving the wrong direction in Unity 2D ?
C#
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 mod...
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#
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 ,...
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#
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 !
< ? 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 ? [ Serializ...
XML Serialization produces random strings at the end ? C #
C#
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 ...
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.Writ...
What causes this list to be passed by reference when called one way , but by value another ?
C#
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...
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#
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 ...
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#
Is there any way to add an if statement into a function parameter ? For example :
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#
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 ?
public class Foo < T > where T : Foo < T > { }
Strange C # generic contraint
C#
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 ) ?
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#
Can anyone elaborate following statement : why i should not use
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#
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 .
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#
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 ?
[ 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...
How to declare a not started Task that will Await for another Task ?
C#
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 wor...
( select * from Students where StudentId = stdId )
Issue Related to where clause in SQL Server
C#
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 ...
DateTime mydate = DateTime.ParseExact ( datetoconvert , '' dd/mm/yyyy '' , System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat ) ;
Parsing Date Time in C # , Getting wrong output
C#
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 ?
double d1=11 , double d2=2int i=d1/d2 ;
Next larger integer after dividing
C#
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 da...
class example { int Id ; int Order }
SortedList indexed by something other than the Key
C#
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 ...
@ 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 > < optio...
DropDownListFor callback or if statement
C#
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...
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#
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 ...
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 ...
Copying OLE Objects from one slide to another corrupts the resulting PowerPoint
C#
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 .
void foo ( ) { Bar bar = new Bar ( ) ; // bar is never referred to after this line // ( 1 ) doSomethingWithoutBar ( ) ; }
Special case lifetime analysis
C#
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 ...
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#
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 us...
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 > ) ...
Type checking on Nullable < int >
C#
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...
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#
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 t...
< 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#
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 ...
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#
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...
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#
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 shou...
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 < i...
Create combined Lists from multiple Lists
C#
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 o...
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#
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...
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.WebsiteCo...
Replace \ with \\ does n't work for specific variable
C#
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...
class ThreadUnsafe { static int _x ; static void Increment ( ) { _x++ ; } static void Assign ( ) { _x = 123 ; } }
locking only 1 operation ?
C#
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 ...
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#
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 ...
ItemId masterId = Appointment.BindToRecurringMaster ( Service , appointment.Id , new PropertySet ( BasePropertySet.IdOnly ) ) ;
EWS : BindToRecurringMaster is slow , just need the recurring master Id
C#
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 ...
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 '' , selectedS...
Refactor two methods that generate a SelectList into a single method
C#
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...
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 { [ ...
Entity Framework suggest invalid field name
C#
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 alternati...
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 ) g...
Is there a better way than GOTO in this scenario ?
C#
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 ?
public void WorkWith < T > ( Action < T > method ) { method.Invoke ( ( T ) this ) ; }
Cast object to method generic type
C#
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 mi...
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 , Expressio...
Calling a generic extension method without specifying as many types
C#
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...
public string AskAPI ( string uri ) { return api.Query ( uri ) ; }
timing out a method call
C#
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 ...
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.ReadIn...
What are layout and size of a managed class 's header in unmanaged memory ?
C#
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 : F...
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 H...
Is it possible to simplify nested generics in C # ?
C#
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 wh...
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 rig...
Where does a value type-variable - which is returned by ref - live ? Stack or heap ?
C#
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 )
VariantType vt = ( VariantType ) vt ;
Convert short to VariantType ( extract VariantType from short )
C#
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
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 retu...
In MVC what is the best method to manage exceptions or errors in the business ?
C#
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...
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 '...
Add SQL Parameters inside the loop , excecute outside the loop . ( Single query multi-insert with parameters in C # SQL Client )
C#
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 .
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#
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 .
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#
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...
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 ) ; } ) ; y...
Completed c # Task Runs Again ... Why ?
C#
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 as...
// 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 { inte...
Sporadic application deadlock in ASP.NET Identity
C#
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 ...
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#
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 sync...
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 Debu...
Is this code actually multithreaded ?
C#
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 ta...
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...
Parsing a huge text file ( around 2GB ) with custom delimiters
C#
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 ? ?
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#
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 behaviou...
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#
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 .
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#
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 , ...
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 ) { //...
Does a IEnumerable store objects after use
C#
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 ...
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 ; whil...
Roslyn CodeFixProvider gives VS 2015 error
C#
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 Filt...
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 Jo...
How to filter entities using queries in C # ?
C#
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 sp...
IEnumerable < IList < MyClass > > myData = // ... getMyDataforeach ( MyClass o in myData ) { // do something }
C # foreach on IEnumerable < IList < object > > compiles but should n't
C#
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 `` d...
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 {...
Breaking down chain of item creation equation chain ( possibly with recursion )
C#
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 name...
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 vo...
How to add an apple delegate to a list of fruit delegates ?