text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
C_sharp : I have in xaml : And here is screenshot ( using magnifier ) : My question is what is going on here ? Why tooltip displays value differently ( decimal point is . while , is expected ) ? Longer story : I am trying to display numbers in same format as in user Windows number format preferences.For this I 've override the language before displaying window ( overriding App.OnStartup ) : And using following custom binding ( to set converter culture by default ) It works for Text property of TextBox , but it does n't work for ToolTip.To actually see what I show on screenshot : go ( Windows 7 ) Control Panel/Region and Language/Formats and set Format as English ( United States ) go Additional settings/Numbers and change Decimal symbol from . to , create new wpf application , copy xaml , add language override , add converter and set : <code> < TextBlock Text= '' { local : Bind Test } '' ToolTip= '' { local : Bind Test } '' / > FrameworkElement.LanguageProperty.OverrideMetadata ( typeof ( FrameworkElement ) , new FrameworkPropertyMetadata ( XmlLanguage.GetLanguage ( CultureInfo.CurrentCulture.IetfLanguageTag ) ) ) ; public class Bind : Binding { public Bind ( string path ) : base ( path ) { ConverterCulture = CultureInfo.CurrentCulture ; } } public partial class MainWindow : Window { public double Test { get ; set ; } = 1.234567 ; public MainWindow ( ) { InitializeComponent ( ) ; DataContext = this ; } } | Tooltip culture is wrong |
C_sharp : I try to find some information about method overloading resolution in case of presence of user-defined implicit conversions and about conversions priority.This code : Produces output : So , It looks like compiler chosen user-defined conversion instead of built-in implicit conversion from int to double ( built-in conversion is implicit due to info from this page https : //docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/implicit-numeric-conversions-table ) .I tried to find something about this in specification , but with no success.Why compiler selected ProcessValue ( Value value ) instead of ProcessValue ( double value ) <code> class Value { private readonly int _value ; public Value ( int val ) { _value = val ; } public static implicit operator int ( Value value ) { return value._value ; } public static implicit operator Value ( int value ) { return new Value ( value ) ; } } class Program { static void ProcessValue ( double value ) { Console.WriteLine ( `` Process double '' ) ; } static void ProcessValue ( Value value ) { Console.WriteLine ( `` Process Value '' ) ; } static void Main ( string [ ] args ) { ProcessValue ( new Value ( 10 ) ) ; ProcessValue ( 10 ) ; Console.ReadLine ( ) ; } } Process ValueProcess Value | C # Method overloading resolution and user-defined implicit conversions |
C_sharp : Lets assume , we have an operation based on some file , connection , or other resource.We need a method , which can be run with provided resource , or - if not provided - creates own : } It works , but this is really ugly for me.Is it a way to write it in more compact and `` nice '' way ? I can not use : as it disposes my original Resource if passed as parameter.PS . What is proper tag for this question ? # coding-style is marked as `` do not use '' . <code> string Foo ( Resource parameter = null ) { if ( parameter == null ) { using ( var res = new Resource ) { res.Something ( ) ; /* ... ... */ /* ... ... */ /* ... ... */ return /* ... ... ... .*/ } } else { parameter.Something ( ) ; /* ... ... */ /* ... ... */ /* ... ... */ return /* ... ... ... .*/ } } string Foo ( Resource parameter = null ) { using ( var res = parameter ? ? new Resource ( ) ) { res.Something ( ) ; /* ... ... */ /* ... ... */ /* ... ... */ return /* ... ... ... .*/ } } | C # conditional using and default parameter |
C_sharp : I need a PHP version of the following C # code : ... this code snippet appears to be incomplete . But here 's what I think is going on : concatenating dateSince , siteID , and sharedSecret . Stealing underpants. ? ? ? converting that string into a ascii encoded byte array.taking the MD5 hash of that array.This mysterious BitConverter object appears to be converting that MD5 hashed array , into a string of hexadecimal numbers . According to the aforementioned doc , the value of result should look something like : `` 6D-E9-9A-B6-73-D8-10-79-BC-4F-EE-51-A4-84-15-D8 '' Any help is greatly appreciated ! ! Forgot to include this earlier . Here 's the PHP version of what I 've written so far : <code> string dateSince = `` 2010-02-01 '' ; string siteID = `` bash.org '' ; string sharedSecret = `` 12345 '' ; // the same combination on my luggage ! using System.Security.Cryptography ; MD5CryptoServiceProvider x = new MD5CryptoServiceProvider ( ) ; byte [ ] dataBytes = System.Text.Encoding.ASCII.GetBytes ( string.Format ( `` { 0 } { 1 } { 2 } '' , dateSince , siteID , sharedSecret ) ) ; string result = BitConverter.ToString ( x.ComputeHash ( dataBytes ) ) ; $ date_since = `` 2010-02-01 '' ; $ site_id = `` bash.org '' ; $ shared_secret = `` 12345 '' ; $ initial_token = $ date_since. $ site_id. $ shared_secret ; $ ascii_version = array ( ) ; foreach ( $ i=0 ; $ i < strlen ( $ initial_token ) ; $ i++ ) { $ ascii_version [ ] = ord ( substr ( $ initial_token , $ i,1 ) ) ; } $ md5_version = md5 ( join ( `` '' , $ ascii_version ) ) ; $ hexadecimal_bits = array ( ) ; foreach ( $ i=0 ; $ i < strlen ( $ md5_version ) ; $ i++ ) { // @ todo convert to hexadecimal here ? $ hexadecimal_bits [ ] = bin2hex ( substr ( $ md5_version , $ i,1 ) ) ; } $ result = join ( `` - '' , $ hexadecimal_bits ) ; | How would I translate this C # code into PHP ? |
C_sharp : I have a Linq query with a select , from my Linq query provider it I get an expression tree containing a MethodCallExpression , but just how can I get the select projections from the MethodCallExpression ? Query may look like : <code> internal static object Execute ( Expression expression , bool isEnumerable ) { var whereExpression = expression as MethodCallExpression ; if ( whereExpression == null ) throw new InvalidProgramException ( `` Error '' ) ; foreach ( var arg in whereExpression.Arguments ) { if ( arg is UnaryExpression ) { var unaryExpression = arg as UnaryExpression ; var lambdaExpression = unaryExpression.Operand as LambdaExpression ; if ( lambdaExpression == null ) continue ; // Here I would like to get the select projections , in this example the `` word '' projection ... var queryable = new MyQueriableClass ( ) ; var query = from thing in queryable where thing.id == 1 select word ; | Getting projections from MethodCallExpression |
C_sharp : I am creating a console application for the purpose of learning the state and observer patterns . The program is based on a basic order system whereby each order can have a state ( pending , ready , submitted i.e state pattern ) and subscribers that are interested in receiving notifications from the order when it gets updated are notified ( observer pattern ) . The Order class is implementing three interfaces ; IOrder , IOrderState and IObservable but I realised that instead I could have the interfaces inheriting from each other . Which approach would be better ? When would you make the class implement from each of the interfaces separately instead of having say , IOrder inherit from the other two ? For example : oreditI may have just answered my question - am I right in thinking you would make the IOrder interface inherit from the other two interfaces if you are sure the object that will implement it ( the Order class ) will always need to use those methods ? And if you 're not sure if an interfaces methods are needed , or if other classes i.e perhaps an order that does not need to be observed by subscribers , then you would include the interfaces separately at class level ? <code> public class Order : IOrder , IOrderState , IObservable public interface IOrder : IOrderState , IObservable | Should these interfaces be inherited at interface level or implemented at class level ? |
C_sharp : Imagine this C # code in some method : Let 's say no one is using any explicit memory barriers or locking to access the dictionary . If no optimization takes place , then the global dictionary should be either null ( initial value ) or a properly constructed dictionary with one entry.The question is : Can the effect of the Add call and assigning to SomeGlobalStaticDictionary be reordered such that some other thread would see an empty non-null SomeGlobalStaticDictionary ( or any other invalid partially constructed dictionary ? ) Does the answer change if SomeGlobalStaticDictionary is volatile ? After reading http : //msdn.microsoft.com/en-us/magazine/jj863136.aspx ( and also its second part ) I learned that in theory just because one variable is assigned in source code other threads might see it differently due to many reasons . I looked at the IL code but the question is whether the JIT compiler and/or CPU are allowed to not `` flush '' the effect of the Add call to other threads before the assignment of the SomGlobalStaticDictionary . <code> SomeClass.SomeGlobalStaticDictionary = new Dictionary < int , string > ( ) { { 0 , `` value '' } , } ; | Can another thread see partially created collection when using collection initializer ? |
C_sharp : So I made myself a C # -WebApi REST Service.When I build/run my application in Visual Studio everything works perfectly.But everytime I try to publish my project as a filesystem , two errors appear in the error list . The strange thing here is that these errors disappear after a few seconds and no errors are shown.ErroMessages : 'Yow.Contracts.IEvent ' does not contain a definition for 'CreatetionDate ' and no extension method 'CreationDate ' accepting a first argument of type 'Yow.Contracts.IEvent ' could be found ( are you missing a using directive or an assembly reference ) 'Yow.Contracts.IEvent ' does not contain a definition for 'Color ' and no extension method 'Color ' accepting a first argument of type 'Yow.Contracts.IEvent ' could be found ( are you missing a using directive or an assembly reference ) In this Method the errors occur : Interface which my class implements looks like this : <code> public override void CopyProperties ( object other ) { base.CopyProperties ( other ) ; Contracts.IEvent _event = other as Contracts.IEvent ; if ( _event ! = null ) { this.Description = _event.Description ; this.Enddate = _event.Enddate ; this.Host = _event.Host ; this.Location = _event.Location ; this.Name = _event.Name ; this.Color = _event.Color ; this.CreationDate = _event.CreationDate ; } } namespace Yow.Contracts { public interface IEvent : DataObjectBase.IDataObject { string Host { get ; set ; } string Location { get ; set ; } DateTime Startingdate { get ; set ; } DateTime Enddate { get ; set ; } string Description { get ; set ; } string Name { get ; set ; } string Privacy { get ; set ; } string State { get ; set ; } string Agerestriction { get ; set ; } int Age { get ; set ; } string Color { get ; set ; } DateTime CreationDate { get ; set ; } } } | Visual Studio 2013 publishing fails and reports `` non-existing '' error |
C_sharp : please look at the below code : and the result is : FalseTrueand now consider this one : and the result is : TrueTrue “ == ” compares if the object references are same while “ .Equals ( ) ” compares if the contents are same . and i want to know what is different between these codes ? ! and both of them turn out an object but why results are different ? <code> using System ; class MyClass { static void Main ( ) { object o = `` .NET Framework '' ; object o1 = new string ( `` .NET Framework '' .ToCharArray ( ) ) ; Console.WriteLine ( o == o1 ) ; Console.WriteLine ( o.Equals ( o1 ) ) ; } } using System ; class MyClass { static void Main ( ) { object o = `` .NET Framework '' ; object o1 = `` .NET Framework '' ; Console.WriteLine ( o == o1 ) ; Console.WriteLine ( o.Equals ( o1 ) ) ; } } object o1 = new string ( `` .NET Framework '' .ToCharArray ( ) ) ; object o1 = `` .NET Framework '' ; | `` stringDemo '' versus new string ( `` stringDemo '' .ToCharArray ) ; |
C_sharp : 2nd edit : I think my original test script has an issue , the 10000000 times loop is , in fact , dealing with the same memory location of an array , which makes the unsafe version ( provided by Marc here ) much faster than bitwise version . I wrote another test script , I noticed that bitwise and unsafe offers almost the same performance.loop for 10,000,000 timesBitwise : 4218484 ; UnsafeRaw : 41017190.0284673328426447545529081831 ( ~2 % Difference ) here is the code:1st edit : I tried to implement using fixed and stackalloc , compare with bitwise . It seems that bitwise is faster than unsafe approach in my test code.Here is the measurement : after loops of 10000000 times with stopwatch frequency 3515622unsafe fixed - 2239790 ticksbitwise - 672159 ticksunsafe stackalloc - 1624166 ticksIs there anything I did wrong ? I thought unsafe will be faster than bitwise.Here is the code : Original : I 'm confused about the bitwise way to convert c # data type short , int , long and ushort , uint , ulong to a byte array , and vice versa.Performance is really really important to me.I know there is a slow way of doing all these using BitConverter and Array.Reverse , but the performance is terrible.I know there are basically two more approaches other than BitConverter , one is bitwise , and the other is unsafe.After research on StackOverflow like : Efficient way to read big-endian data in C # Bitwise endian swap for various typesIn C # , convert ulong [ 64 ] to byte [ 512 ] faster ? Fast string to byte [ ] conversionI tried and tested bitwise method first , combining all these small pieces into one whole picture.I 'm even more confused about all these bit shifting , here is my testing code : I 'm asking a solution that provides best performance , with consistent code style and cleanness of the code . <code> unsafe class UnsafeRaw { public static short ToInt16BigEndian ( byte* buf ) { return ( short ) ToUInt16BigEndian ( buf ) ; } public static int ToInt32BigEndian ( byte* buf ) { return ( int ) ToUInt32BigEndian ( buf ) ; } public static long ToInt64BigEndian ( byte* buf ) { return ( long ) ToUInt64BigEndian ( buf ) ; } public static ushort ToUInt16BigEndian ( byte* buf ) { return ( ushort ) ( ( *buf++ < < 8 ) | *buf ) ; } public static uint ToUInt32BigEndian ( byte* buf ) { return unchecked ( ( uint ) ( ( *buf++ < < 24 ) | ( *buf++ < < 16 ) | ( *buf++ < < 8 ) | *buf ) ) ; } public static ulong ToUInt64BigEndian ( byte* buf ) { unchecked { var x = ( uint ) ( ( *buf++ < < 24 ) | ( *buf++ < < 16 ) | ( *buf++ < < 8 ) | *buf++ ) ; var y = ( uint ) ( ( *buf++ < < 24 ) | ( *buf++ < < 16 ) | ( *buf++ < < 8 ) | *buf ) ; return ( ( ulong ) x < < 32 ) | y ; } } } class Bitwise { public static short ToInt16BigEndian ( byte [ ] buffer , int beginIndex ) { return unchecked ( ( short ) ( buffer [ beginIndex ] < < 8 | buffer [ beginIndex + 1 ] ) ) ; } public static int ToInt32BigEndian ( byte [ ] buffer , int beginIndex ) { return unchecked ( buffer [ beginIndex ] < < 24 | buffer [ beginIndex + 1 ] < < 16 | buffer [ beginIndex + 2 ] < < 8 | buffer [ beginIndex + 3 ] ) ; } public static long ToInt64BigEndian ( byte [ ] buffer , int beginIndex ) { return unchecked ( ( long ) buffer [ beginIndex ] < < 56 | ( long ) buffer [ beginIndex + 1 ] < < 48 | ( long ) buffer [ beginIndex + 2 ] < < 40 | ( long ) buffer [ beginIndex + 3 ] < < 32 | ( long ) buffer [ beginIndex + 4 ] < < 24 | ( long ) buffer [ beginIndex + 5 ] < < 16 | ( long ) buffer [ beginIndex + 6 ] < < 8 | buffer [ beginIndex + 7 ] ) ; } public static ushort ToUInt16BigEndian ( byte [ ] buffer , int beginIndex ) { return unchecked ( ( ushort ) ToInt16BigEndian ( buffer , beginIndex ) ) ; } public static uint ToUInt32BigEndian ( byte [ ] buffer , int beginIndex ) { return unchecked ( ( uint ) ToInt32BigEndian ( buffer , beginIndex ) ) ; } public static ulong ToUInt64BigEndian ( byte [ ] buffer , int beginIndex ) { return unchecked ( ( ulong ) ToInt64BigEndian ( buffer , beginIndex ) ) ; } } class BufferTest { static long LongRandom ( long min , long max , Random rand ) { long result = rand.Next ( ( Int32 ) ( min > > 32 ) , ( Int32 ) ( max > > 32 ) ) ; result = result < < 32 ; result = result | ( long ) rand.Next ( ( Int32 ) min , ( Int32 ) max ) ; return result ; } public static void Main ( ) { const int times = 10000000 ; const int index = 100 ; Random r = new Random ( ) ; Stopwatch sw1 = new Stopwatch ( ) ; Console.WriteLine ( $ '' loop for { times : # # , # # # } times '' ) ; Thread.Sleep ( 1000 ) ; for ( int j = 0 ; j < times ; j++ ) { short a = ( short ) r.Next ( short.MinValue , short.MaxValue ) ; int b = r.Next ( int.MinValue , int.MaxValue ) ; long c = LongRandom ( int.MinValue , int.MaxValue , r ) ; ushort d = ( ushort ) r.Next ( ushort.MinValue , ushort.MaxValue ) ; uint e = ( uint ) r.Next ( int.MinValue , int.MaxValue ) ; ulong f = ( ulong ) LongRandom ( int.MinValue , int.MaxValue , r ) ; var arr1 = BitConverter.GetBytes ( a ) ; var arr2 = BitConverter.GetBytes ( b ) ; var arr3 = BitConverter.GetBytes ( c ) ; var arr4 = BitConverter.GetBytes ( d ) ; var arr5 = BitConverter.GetBytes ( e ) ; var arr6 = BitConverter.GetBytes ( f ) ; Array.Reverse ( arr1 ) ; Array.Reverse ( arr2 ) ; Array.Reverse ( arr3 ) ; Array.Reverse ( arr4 ) ; Array.Reverse ( arr5 ) ; Array.Reverse ( arr6 ) ; var largerArr1 = new byte [ 1024 ] ; var largerArr2 = new byte [ 1024 ] ; var largerArr3 = new byte [ 1024 ] ; var largerArr4 = new byte [ 1024 ] ; var largerArr5 = new byte [ 1024 ] ; var largerArr6 = new byte [ 1024 ] ; Array.Copy ( arr1 , 0 , largerArr1 , index , arr1.Length ) ; Array.Copy ( arr2 , 0 , largerArr2 , index , arr2.Length ) ; Array.Copy ( arr3 , 0 , largerArr3 , index , arr3.Length ) ; Array.Copy ( arr4 , 0 , largerArr4 , index , arr4.Length ) ; Array.Copy ( arr5 , 0 , largerArr5 , index , arr5.Length ) ; Array.Copy ( arr6 , 0 , largerArr6 , index , arr6.Length ) ; sw1.Start ( ) ; var n1 = Bitwise.ToInt16BigEndian ( largerArr1 , index ) ; var n2 = Bitwise.ToInt32BigEndian ( largerArr2 , index ) ; var n3 = Bitwise.ToInt64BigEndian ( largerArr3 , index ) ; var n4 = Bitwise.ToUInt16BigEndian ( largerArr4 , index ) ; var n5 = Bitwise.ToUInt32BigEndian ( largerArr5 , index ) ; var n6 = Bitwise.ToUInt64BigEndian ( largerArr6 , index ) ; sw1.Stop ( ) ; //Console.WriteLine ( n1 == a ) ; //Console.WriteLine ( n2 == b ) ; //Console.WriteLine ( n3 == c ) ; //Console.WriteLine ( n4 == d ) ; //Console.WriteLine ( n5 == e ) ; //Console.WriteLine ( n6 == f ) ; } Stopwatch sw2 = new Stopwatch ( ) ; for ( int j = 0 ; j < times ; j++ ) { short a = ( short ) r.Next ( short.MinValue , short.MaxValue ) ; int b = r.Next ( int.MinValue , int.MaxValue ) ; long c = LongRandom ( int.MinValue , int.MaxValue , r ) ; ushort d = ( ushort ) r.Next ( ushort.MinValue , ushort.MaxValue ) ; uint e = ( uint ) r.Next ( int.MinValue , int.MaxValue ) ; ulong f = ( ulong ) LongRandom ( int.MinValue , int.MaxValue , r ) ; var arr1 = BitConverter.GetBytes ( a ) ; var arr2 = BitConverter.GetBytes ( b ) ; var arr3 = BitConverter.GetBytes ( c ) ; var arr4 = BitConverter.GetBytes ( d ) ; var arr5 = BitConverter.GetBytes ( e ) ; var arr6 = BitConverter.GetBytes ( f ) ; Array.Reverse ( arr1 ) ; Array.Reverse ( arr2 ) ; Array.Reverse ( arr3 ) ; Array.Reverse ( arr4 ) ; Array.Reverse ( arr5 ) ; Array.Reverse ( arr6 ) ; var largerArr1 = new byte [ 1024 ] ; var largerArr2 = new byte [ 1024 ] ; var largerArr3 = new byte [ 1024 ] ; var largerArr4 = new byte [ 1024 ] ; var largerArr5 = new byte [ 1024 ] ; var largerArr6 = new byte [ 1024 ] ; Array.Copy ( arr1 , 0 , largerArr1 , index , arr1.Length ) ; Array.Copy ( arr2 , 0 , largerArr2 , index , arr2.Length ) ; Array.Copy ( arr3 , 0 , largerArr3 , index , arr3.Length ) ; Array.Copy ( arr4 , 0 , largerArr4 , index , arr4.Length ) ; Array.Copy ( arr5 , 0 , largerArr5 , index , arr5.Length ) ; Array.Copy ( arr6 , 0 , largerArr6 , index , arr6.Length ) ; sw2.Start ( ) ; unsafe { fixed ( byte* p1 = & largerArr1 [ index ] , p2 = & largerArr2 [ index ] , p3 = & largerArr3 [ index ] , p4 = & largerArr4 [ index ] , p5 = & largerArr5 [ index ] , p6 = & largerArr6 [ index ] ) { var u1 = UnsafeRaw.ToInt16BigEndian ( p1 ) ; var u2 = UnsafeRaw.ToInt32BigEndian ( p2 ) ; var u3 = UnsafeRaw.ToInt64BigEndian ( p3 ) ; var u4 = UnsafeRaw.ToUInt16BigEndian ( p4 ) ; var u5 = UnsafeRaw.ToUInt32BigEndian ( p5 ) ; var u6 = UnsafeRaw.ToUInt64BigEndian ( p6 ) ; //Console.WriteLine ( u1 == a ) ; //Console.WriteLine ( u2 == b ) ; //Console.WriteLine ( u3 == c ) ; //Console.WriteLine ( u4 == d ) ; //Console.WriteLine ( u5 == e ) ; //Console.WriteLine ( u6 == f ) ; } } sw2.Stop ( ) ; } Console.WriteLine ( $ '' Bitwise : { sw1.ElapsedTicks } ; UnsafeRaw : { sw2.ElapsedTicks } '' ) ; Console.WriteLine ( ( decimal ) sw1.ElapsedTicks / sw2.ElapsedTicks - 1 ) ; Console.ReadKey ( ) ; } } class Bitwise { public static short ToInt16BigEndian ( byte [ ] buf , int i ) { return ( short ) ( ( buf [ i ] < < 8 ) | buf [ i + 1 ] ) ; } public static int ToInt32BigEndian ( byte [ ] buf , int i ) { return ( buf [ i ] < < 24 ) | ( buf [ i + 1 ] < < 16 ) | ( buf [ i + 2 ] < < 8 ) | buf [ i + 3 ] ; } public static long ToInt64BigEndian ( byte [ ] buf , int i ) { return ( buf [ i ] < < 56 ) | ( buf [ i + 1 ] < < 48 ) | ( buf [ i + 2 ] < < 40 ) | buf [ i + 3 ] < < 32 | ( buf [ i + 4 ] < < 24 ) | ( buf [ i + 5 ] < < 16 ) | ( buf [ i + 6 ] < < 8 ) | buf [ i + 7 ] ; } public static ushort ToUInt16BigEndian ( byte [ ] buf , int i ) { ushort value = 0 ; for ( var j = 0 ; j < 2 ; j++ ) { value = ( ushort ) unchecked ( ( value < < 8 ) | buf [ j + i ] ) ; } return value ; } public static uint ToUInt32BigEndian ( byte [ ] buf , int i ) { uint value = 0 ; for ( var j = 0 ; j < 4 ; j++ ) { value = unchecked ( ( value < < 8 ) | buf [ j + i ] ) ; } return value ; } public static ulong ToUInt64BigEndian ( byte [ ] buf , int i ) { ulong value = 0 ; for ( var j = 0 ; j < 8 ; j++ ) { value = unchecked ( ( value < < 8 ) | buf [ i + j ] ) ; } return value ; } } class Unsafe { public static short ToInt16BigEndian ( byte [ ] buf , int i ) { byte [ ] arr = new byte [ 2 ] ; arr [ 0 ] = buf [ i + 1 ] ; arr [ 1 ] = buf [ i ] ; unsafe { fixed ( byte* ptr = arr ) { return * ( short* ) ptr ; } } } public static int ToInt32BigEndian ( byte [ ] buf , int i ) { byte [ ] arr = new byte [ 4 ] ; arr [ 0 ] = buf [ i + 3 ] ; arr [ 1 ] = buf [ i + 2 ] ; arr [ 2 ] = buf [ i + 1 ] ; arr [ 3 ] = buf [ i ] ; unsafe { fixed ( byte* ptr = arr ) { return * ( int* ) ptr ; } } } public static long ToInt64BigEndian ( byte [ ] buf , int i ) { byte [ ] arr = new byte [ 8 ] ; arr [ 0 ] = buf [ i + 7 ] ; arr [ 1 ] = buf [ i + 6 ] ; arr [ 2 ] = buf [ i + 5 ] ; arr [ 3 ] = buf [ i + 6 ] ; arr [ 4 ] = buf [ i + 3 ] ; arr [ 5 ] = buf [ i + 2 ] ; arr [ 6 ] = buf [ i + 1 ] ; arr [ 7 ] = buf [ i ] ; unsafe { fixed ( byte* ptr = arr ) { return * ( long* ) ptr ; } } } public static ushort ToUInt16BigEndian ( byte [ ] buf , int i ) { byte [ ] arr = new byte [ 2 ] ; arr [ 0 ] = buf [ i + 1 ] ; arr [ 1 ] = buf [ i ] ; unsafe { fixed ( byte* ptr = arr ) { return * ( ushort* ) ptr ; } } } public static uint ToUInt32BigEndian ( byte [ ] buf , int i ) { byte [ ] arr = new byte [ 4 ] ; arr [ 0 ] = buf [ i + 3 ] ; arr [ 1 ] = buf [ i + 2 ] ; arr [ 2 ] = buf [ i + 1 ] ; arr [ 3 ] = buf [ i ] ; unsafe { fixed ( byte* ptr = arr ) { return * ( uint* ) ptr ; } } } public static ulong ToUInt64BigEndian ( byte [ ] buf , int i ) { byte [ ] arr = new byte [ 8 ] ; arr [ 0 ] = buf [ i + 7 ] ; arr [ 1 ] = buf [ i + 6 ] ; arr [ 2 ] = buf [ i + 5 ] ; arr [ 3 ] = buf [ i + 6 ] ; arr [ 4 ] = buf [ i + 3 ] ; arr [ 5 ] = buf [ i + 2 ] ; arr [ 6 ] = buf [ i + 1 ] ; arr [ 7 ] = buf [ i ] ; unsafe { fixed ( byte* ptr = arr ) { return * ( ulong* ) ptr ; } } } } class UnsafeAlloc { public static short ToInt16BigEndian ( byte [ ] buf , int i ) { unsafe { const int length = sizeof ( short ) ; byte* arr = stackalloc byte [ length ] ; byte* p = arr ; for ( int j = length - 1 ; j > = 0 ; j -- ) { *p = buf [ i + j ] ; p++ ; } return * ( short* ) arr ; } } public static int ToInt32BigEndian ( byte [ ] buf , int i ) { unsafe { const int length = sizeof ( int ) ; byte* arr = stackalloc byte [ length ] ; byte* p = arr ; for ( int j = length - 1 ; j > = 0 ; j -- ) { *p = buf [ i + j ] ; p++ ; } return * ( int* ) arr ; } } public static long ToInt64BigEndian ( byte [ ] buf , int i ) { unsafe { const int length = sizeof ( long ) ; byte* arr = stackalloc byte [ length ] ; byte* p = arr ; for ( int j = length - 1 ; j > = 0 ; j -- ) { *p = buf [ i + j ] ; p++ ; } return * ( long* ) arr ; } } public static ushort ToUInt16BigEndian ( byte [ ] buf , int i ) { unsafe { const int length = sizeof ( ushort ) ; byte* arr = stackalloc byte [ length ] ; byte* p = arr ; for ( int j = length - 1 ; j > = 0 ; j -- ) { *p = buf [ i + j ] ; p++ ; } return * ( ushort* ) arr ; } } public static uint ToUInt32BigEndian ( byte [ ] buf , int i ) { unsafe { const int length = sizeof ( uint ) ; byte* arr = stackalloc byte [ length ] ; byte* p = arr ; for ( int j = length - 1 ; j > = 0 ; j -- ) { *p = buf [ i + j ] ; p++ ; } return * ( uint* ) arr ; } } public static ulong ToUInt64BigEndian ( byte [ ] buf , int i ) { unsafe { const int length = sizeof ( ulong ) ; byte* arr = stackalloc byte [ length ] ; byte* p = arr ; for ( int j = length - 1 ; j > = 0 ; j -- ) { *p = buf [ i + j ] ; p++ ; } return * ( ulong* ) arr ; } } } class Program { static void Main ( ) { short a = short.MinValue + short.MaxValue / 2 ; int b = int.MinValue + int.MaxValue / 2 ; long c = long.MinValue + long.MaxValue / 2 ; ushort d = ushort.MaxValue / 2 ; uint e = uint.MaxValue / 2 ; ulong f = ulong.MaxValue / 2 ; Console.WriteLine ( a ) ; Console.WriteLine ( b ) ; Console.WriteLine ( c ) ; Console.WriteLine ( d ) ; Console.WriteLine ( e ) ; Console.WriteLine ( f ) ; Console.WriteLine ( ) ; var arr1 = BitConverter.GetBytes ( a ) ; var arr2 = BitConverter.GetBytes ( b ) ; var arr3 = BitConverter.GetBytes ( c ) ; var arr4 = BitConverter.GetBytes ( d ) ; var arr5 = BitConverter.GetBytes ( e ) ; var arr6 = BitConverter.GetBytes ( f ) ; Array.Reverse ( arr1 ) ; Array.Reverse ( arr2 ) ; Array.Reverse ( arr3 ) ; Array.Reverse ( arr4 ) ; Array.Reverse ( arr5 ) ; Array.Reverse ( arr6 ) ; Console.WriteLine ( Unsafe.ToInt16BigEndian ( arr1 , 0 ) ) ; Console.WriteLine ( Unsafe.ToInt32BigEndian ( arr2 , 0 ) ) ; Console.WriteLine ( Unsafe.ToInt64BigEndian ( arr3 , 0 ) ) ; Console.WriteLine ( Unsafe.ToUInt16BigEndian ( arr4 , 0 ) ) ; Console.WriteLine ( Unsafe.ToUInt32BigEndian ( arr5 , 0 ) ) ; Console.WriteLine ( Unsafe.ToUInt64BigEndian ( arr6 , 0 ) ) ; Console.WriteLine ( ) ; Console.WriteLine ( Bitwise.ToInt16BigEndian ( arr1 , 0 ) ) ; Console.WriteLine ( Bitwise.ToInt32BigEndian ( arr2 , 0 ) ) ; Console.WriteLine ( Bitwise.ToInt64BigEndian ( arr3 , 0 ) ) ; Console.WriteLine ( Bitwise.ToUInt16BigEndian ( arr4 , 0 ) ) ; Console.WriteLine ( Bitwise.ToUInt32BigEndian ( arr5 , 0 ) ) ; Console.WriteLine ( Bitwise.ToUInt64BigEndian ( arr6 , 0 ) ) ; Console.WriteLine ( ) ; Console.WriteLine ( UnsafeAlloc.ToInt16BigEndian ( arr1 , 0 ) ) ; Console.WriteLine ( UnsafeAlloc.ToInt32BigEndian ( arr2 , 0 ) ) ; Console.WriteLine ( UnsafeAlloc.ToInt64BigEndian ( arr3 , 0 ) ) ; Console.WriteLine ( UnsafeAlloc.ToUInt16BigEndian ( arr4 , 0 ) ) ; Console.WriteLine ( UnsafeAlloc.ToUInt32BigEndian ( arr5 , 0 ) ) ; Console.WriteLine ( UnsafeAlloc.ToUInt64BigEndian ( arr6 , 0 ) ) ; Console.WriteLine ( ) ; Stopwatch sw = new Stopwatch ( ) ; sw.Start ( ) ; int times = 10000000 ; var t0 = sw.ElapsedTicks ; for ( int i = 0 ; i < times ; i++ ) { Unsafe.ToInt16BigEndian ( arr1 , 0 ) ; Unsafe.ToInt32BigEndian ( arr2 , 0 ) ; Unsafe.ToInt64BigEndian ( arr3 , 0 ) ; Unsafe.ToUInt16BigEndian ( arr4 , 0 ) ; Unsafe.ToUInt32BigEndian ( arr5 , 0 ) ; Unsafe.ToUInt64BigEndian ( arr6 , 0 ) ; } var t1 = sw.ElapsedTicks ; var t2 = sw.ElapsedTicks ; for ( int i = 0 ; i < times ; i++ ) { Bitwise.ToInt16BigEndian ( arr1 , 0 ) ; Bitwise.ToInt32BigEndian ( arr2 , 0 ) ; Bitwise.ToInt64BigEndian ( arr3 , 0 ) ; Bitwise.ToUInt16BigEndian ( arr4 , 0 ) ; Bitwise.ToUInt32BigEndian ( arr5 , 0 ) ; Bitwise.ToUInt64BigEndian ( arr6 , 0 ) ; } var t3 = sw.ElapsedTicks ; var t4 = sw.ElapsedTicks ; for ( int i = 0 ; i < times ; i++ ) { UnsafeAlloc.ToInt16BigEndian ( arr1 , 0 ) ; UnsafeAlloc.ToInt32BigEndian ( arr2 , 0 ) ; UnsafeAlloc.ToInt64BigEndian ( arr3 , 0 ) ; UnsafeAlloc.ToUInt16BigEndian ( arr4 , 0 ) ; UnsafeAlloc.ToUInt32BigEndian ( arr5 , 0 ) ; UnsafeAlloc.ToUInt64BigEndian ( arr6 , 0 ) ; } var t5 = sw.ElapsedTicks ; Console.WriteLine ( $ '' { t1 - t0 } { t3 - t2 } { t5 - t4 } '' ) ; Console.ReadKey ( ) ; } public static string ByteArrayToString ( byte [ ] ba ) { return string.Concat ( ba.Select ( b = > Convert.ToString ( b , 2 ) .PadLeft ( 8 , ' 0 ' ) ) ) ; } } 155554342553454354444354432234234343244322341555543425534-1480130482 // wrong43223423434324432234 class Program { static void Main ( ) { short a = 15555 ; int b = 43425534 ; long c = 54354444354 ; ushort d = 432 ; uint e = 234234 ; ulong f = 34324432234 ; Console.WriteLine ( a ) ; Console.WriteLine ( b ) ; Console.WriteLine ( c ) ; Console.WriteLine ( d ) ; Console.WriteLine ( e ) ; Console.WriteLine ( f ) ; var arr1 = BitConverter.GetBytes ( a ) ; var arr2 = BitConverter.GetBytes ( b ) ; var arr3 = BitConverter.GetBytes ( c ) ; var arr4 = BitConverter.GetBytes ( d ) ; var arr5 = BitConverter.GetBytes ( e ) ; var arr6 = BitConverter.GetBytes ( f ) ; //Console.WriteLine ( ByteArrayToString ( arr1 ) ) ; //Console.WriteLine ( ByteArrayToString ( arr2 ) ) ; //Console.WriteLine ( ByteArrayToString ( arr3 ) ) ; //Console.WriteLine ( ByteArrayToString ( arr4 ) ) ; //Console.WriteLine ( ByteArrayToString ( arr5 ) ) ; //Console.WriteLine ( ByteArrayToString ( arr6 ) ) ; Array.Reverse ( arr1 ) ; Array.Reverse ( arr2 ) ; Array.Reverse ( arr3 ) ; Array.Reverse ( arr4 ) ; Array.Reverse ( arr5 ) ; Array.Reverse ( arr6 ) ; //Console.WriteLine ( ByteArrayToString ( arr1 ) ) ; //Console.WriteLine ( ByteArrayToString ( arr2 ) ) ; //Console.WriteLine ( ByteArrayToString ( arr3 ) ) ; //Console.WriteLine ( ByteArrayToString ( arr4 ) ) ; //Console.WriteLine ( ByteArrayToString ( arr5 ) ) ; //Console.WriteLine ( ByteArrayToString ( arr6 ) ) ; Console.WriteLine ( ToInt16BigEndian ( arr1 , 0 ) ) ; Console.WriteLine ( ToInt32BigEndian ( arr2 , 0 ) ) ; Console.WriteLine ( ToInt64BigEndian ( arr3 , 0 ) ) ; Console.WriteLine ( ToUInt16BigEndian ( arr4 , 0 ) ) ; Console.WriteLine ( ToUInt32BigEndian ( arr5 , 0 ) ) ; Console.WriteLine ( ToUInt64BigEndian ( arr6 , 0 ) ) ; Console.ReadKey ( ) ; } public static string ByteArrayToString ( byte [ ] ba ) { return string.Concat ( ba.Select ( b = > Convert.ToString ( b , 2 ) .PadLeft ( 8 , ' 0 ' ) ) ) ; } public static short ToInt16BigEndian ( byte [ ] buf , int i ) { return ( short ) ( ( buf [ i ] < < 8 ) | buf [ i + 1 ] ) ; } public static int ToInt32BigEndian ( byte [ ] buf , int i ) { return ( buf [ i ] < < 24 ) | ( buf [ i + 1 ] < < 16 ) | ( buf [ i + 2 ] < < 8 ) | buf [ i + 3 ] ; } public static long ToInt64BigEndian ( byte [ ] buf , int i ) { return ( buf [ i ] < < 56 ) | ( buf [ i + 1 ] < < 48 ) | ( buf [ i + 2 ] < < 40 ) | ( buf [ i + 3 ] < < 32 ) | ( buf [ i + 4 ] < < 24 ) | ( buf [ i + 5 ] < < 16 ) | ( buf [ i + 6 ] < < 8 ) | buf [ i + 7 ] ; } public static ushort ToUInt16BigEndian ( byte [ ] buf , int i ) { ushort value = 0 ; for ( var j = 0 ; j < 2 ; j++ ) { value = ( ushort ) unchecked ( ( value < < 8 ) | buf [ j + i ] ) ; } return value ; } public static uint ToUInt32BigEndian ( byte [ ] buf , int i ) { uint value = 0 ; for ( var j = 0 ; j < 4 ; j++ ) { value = unchecked ( ( value < < 8 ) | buf [ j + i ] ) ; } return value ; } public static ulong ToUInt64BigEndian ( byte [ ] buf , int i ) { ulong value = 0 ; for ( var j = 0 ; j < 8 ; j++ ) { value = unchecked ( ( value < < 8 ) | buf [ i + j ] ) ; } return value ; } } | C # Signed & Unsigned Integral to Big Endian Byte Array , and vice versa using Bitwise way with `` best '' performance |
C_sharp : I have a .NET Console App integrated with Entity Framework and Discord Sharp Plus with the following libraries : DSharpPlusDSharpPlus.CommandsNextMicrosoft.EntityFrameworkCore.DesignMicrosoft.EntityFrameworkCore.SqliteMicrosoft.EntityFrameworkCore.ToolsRunning the application without debugging ( Control + F5 in Visual Studio ) works just fine , no crashes issued.However , if I run with debugging , upon accessing my DbContext , I get an errorInvalidOperationException : The Process has no package identity ( 0x80073D54 ) An example being this line : For debugging purposes , if I change SingleOrDefault to ElementAt ( 0 ) , I get the following error : System.InvalidOperationExceptionHResult=0x80131509Message=Processing of the LINQ expression 'DbSet .ElementAtOrDefault ( __p_0 ) ' by 'NavigationExpandingExpressionVisitor ' failed . This may indicate either a bug or a limitation in EF Core . See https : //go.microsoft.com/fwlink/ ? linkid=2101433 for more detailed information.Source=Microsoft.EntityFrameworkCoreStackTrace : at Microsoft.EntityFrameworkCore.Query.Internal.NavigationExpandingExpressionVisitor.VisitMethodCall ( MethodCallExpression methodCallExpression ) This is NOT an UWP app . It is a .NET console application with several class libraries.Here 's my Dbcontext class : <code> Database.Commands.SingleOrDefault ( x = > x.CommandTrigger == name ) private readonly string dbPath = $ '' Data Source= { Environment.GetEnvironmentVariable ( `` YuutaDbPath '' ) } '' ; public DbSet < Guild > Guilds { get ; set ; } // ... // ... protected override void OnConfiguring ( DbContextOptionsBuilder options ) = > options.UseSqlite ( dbPath ) ; protected override void OnModelCreating ( ModelBuilder builder ) { builder.SeedEnumValues// ... . } | .NET Console App with Entity Framework Core : 'The process has no package identity ' only when started without debugging |
C_sharp : On my ASPX page I 've added Dropdownlist.Elements in this list are divided to groups by adding disabled list items : Those list items are grayed , I ca n't select it by mouse or by clicking cursor arrows ( up/down ) .That is correct.But problem is , that after clicking '- ' key this list item is selected . I think that it is Dropdownlist bug , but I need to find some solution for this.How to prevent selecting disabled ListItems by clicking first letter from its title ? Or there is better way to create separators in Dropdownlist ? Edit : I 've checked it after Nico G. comment . This problem happens in IE , not in Firefox . ( I have no other browsers . Two is enought : ) ) <code> ListItem separator = new ListItem ( `` -- -My friends -- - '' , `` '' ) ; separator.Attributes.Add ( `` disabled '' , `` true '' ) ; _ddUsersList.Items.Add ( separator ) ; | Error in Dropdownlist |
C_sharp : I 've written two LINQ queries using the join method . Essentially , if I switch the order of the objects to be joined , the query no longer works and throws the error : '' Unable to create a constant value of type 'Domain.Entities.UsersSitesRole ' . Only primitive types ( 'such as Int32 , String , and Guid ' ) are supported in this context . `` The object privilegesForUser is a List of entities derived from my Entity Framework context ( UsersSiteRole ) , and repository.Child is an IQueryable < Child > from my EF context as well . <code> var foo2 = //works from p in privilegesForUser join c in repository.Child on p.SiteId equals c.Child_SiteID select new { ChildID = c.Child_ChildID , name = c.Child_FirstName , site = c.Child_SiteID , p.PrivilegeLevel } ; var foo3 = //throws exception from c in repository.Child join p in privilegesForUser on c.Child_SiteID equals p.SiteId select new { ChildID = c.Child_ChildID , name = c.Child_FirstName , site = c.Child_SiteID , p.PrivilegeLevel } ; | Why does this LINQ join query work , but this other one does n't ? |
C_sharp : I have the following code : This is a modified example from CLR via C # 4th ed ( pg 138 ) .In the book it says thatwill output `` ( 2 , 2 ) '' because the boxed p will be immediately garbage collected.However , would n't the actual reason for this be the fact that changing the value of a boxed variable only changes the value in the object on the heap , in this case , leaving p untouched ? Why does the boxed p getting garbage collected have anything to do with it ? I believe it has nothing to do with it because in this code : we are boxing p , calling the change method on the boxed p , keeping h alive by using it in Console.WriteLine ( h ) ; , however Console.WriteLine ( p ) ; will still output `` ( 2 , 2 ) '' .Does anyone know why the author wrote that the boxed p being garbage collected is the reason why p is not changed , because it does n't seem to be true at all . <code> //Interface defining a Change methodinternal interface IChangeBoxedPoint { void Change ( Int32 x , Int32 y ) ; } internal struct Point : IChangeBoxedPoint { private Int32 m_x , m_y ; public Point ( Int32 x , Int32 y ) { m_x = x ; m_y = y ; } public void Change ( Int32 x , Int32 y ) { m_x = x ; m_y = y ; } public override string ToString ( ) { return String.Format ( `` ( { 0 } , { 1 } ) '' , m_x.ToString ( ) , m_y.ToString ( ) ) ; } } public class Program { static void Main ( string [ ] args ) { Point p = new Point ( 1 , 1 ) ; Console.WriteLine ( p ) ; // `` ( 1 , 1 ) '' p.Change ( 2 , 2 ) ; Console.WriteLine ( p ) ; // `` ( 2 , 2 ) '' Object o = p ; Console.WriteLine ( o ) ; // `` ( 2 , 2 ) '' ( ( Point ) o ) .Change ( 3 , 3 ) ; Console.WriteLine ( o ) ; // `` ( 2 , 2 ) '' //Boxes p , changes the boxed object and discards it ( ( IChangeBoxedPoint ) p ) .Change ( 4 , 4 ) ; Console.WriteLine ( p ) ; // `` ( 2 , 2 ) '' IChangeBoxedPoint h = ( ( IChangeBoxedPoint ) p ) ; h.Change ( 4 , 4 ) ; //Boxed p is not yet garbage collected Console.WriteLine ( p ) ; // `` ( 2 , 2 ) '' Console.WriteLine ( h ) ; // '' ( 4 , 4 ) '' //After this line boxed p is garbage collected //Changes the boxed object and shows it ( ( IChangeBoxedPoint ) o ) .Change ( 5 , 5 ) ; Console.WriteLine ( o ) ; // `` ( 5 , 5 ) '' Console.Read ( ) ; } } ( ( IChangeBoxedPoint ) p ) .Change ( 4 , 4 ) ; Console.WriteLine ( p ) ; // `` ( 2 , 2 ) '' IChangeBoxedPoint h = ( ( IChangeBoxedPoint ) p ) ; h.Change ( 4 , 4 ) ; //Boxed p is not yet garbage collectedConsole.WriteLine ( p ) ; // `` ( 2 , 2 ) '' Console.WriteLine ( h ) ; // //After this line boxed p is garbage collected | Changing a struct after boxing it |
C_sharp : I am trying to read foreign characters from an .ini file.This is the method I am usingI am using Encoding.ASCII but apparently GetPrivateProfileString is n't . The bytes coming out of it need encoding probably . How can I do that ? Edit : ExampleThis will print : Tavar ? instead of Tavaré <code> [ DllImport ( `` kernel32 '' ) ] public static extern int GetPrivateProfileString ( string Section , int Key , string Value , [ MarshalAs ( UnmanagedType.LPArray ) ] byte [ ] Result , int Size , string FileName ) ; public static string [ ] GetEntryNames ( string section , string iniPath ) { for ( int maxsize = 500 ; true ; maxsize *= 2 ) { byte [ ] bytes = new byte [ maxsize ] ; int size = Imports.GetPrivateProfileString ( section , 0 , `` '' , bytes , maxsize , iniPath ) ; if ( size < maxsize - 2 ) { string entries = Encoding.ASCII.GetString ( bytes , 0 , size - ( size > 0 ? 1 : 0 ) ) ; Console.WriteLine ( `` Entries : `` + entries.Split ( new char [ ] { '\0 ' } ) [ 3 ] ) ; return entries.Split ( new char [ ] { '\0 ' } ) ; } } } | File read foreign characters |
C_sharp : Are there any C # specifications that state how implicit conversions of terms of integral types ( e.g. , int ) to terms of double are supposed to work ? If so , can someone tell me the algorithm or direct me to it ? C # 6.0 draft specification states “ the value of a real literal of type float or double is determined by using the IEEE ‘ round to nearest ’ mode ” under Lexical structure - > Grammars - > Lexical grammar - > Lexical analysis - > Tokens - > Literals - > Real literals ; however I wasn ’ t able to find anything about how implicit conversions work.The only thing I found under Conversions - > Implicit conversions - > Implicit numeric conversions in the same specification was “ conversions from int , uint , long , or ulong to float and from long or ulong to double may cause a loss of precision , but will never cause a loss of magnitude. ” I do know that implicit conversions don ’ t follow the same algorithm that real literals do as the below program illustrates* : EditThe above code may be more “ complicated ” than it needs to be . Here is another program that should hopefully clarify what I am asking.AddendumAs The General and mjwills stated in the comments , this is almost certainly due to the extended precision format that some ISAs like x86 offer . As to why the .NET Core compiler relies on the extended format to convert the ulong to a double but doesn ’ t do the same for the real literal is beyond me . Not sure if this is technically a “ bug ” , but it would be nice if both did the same thing . One can be compliant with the above specification and still use the extended format since IEEE 754-2019 explicitly allows for more than 64-bits of precision . Anyway , the ulong value can fit entirely in the 64-bit significand of x86 ’ s extended format thus leading to no rounding.TL ; DR ( aka Edit 2 ) I ’ ll preface this edit with the fact that I am fundamentally and philosophically against the notion that what I am about to write is necessary or even desirable . I believe technical questions that are specific to a particular programming language like this one still “ fit ” in Stack Overflow and not any of the other Stack Exchange sites ( e.g. , Computer Science , Theoretical Computer Science , Mathematics and Math Overflow—for things like homotopy type theory ) . This means that wanting to know the nitty-gritty details of something—even if one may ( incorrectly ) perceive such things as leading to a violation of “ best practices ” —is still a worthwhile question . If there exists a more fundamental problem , then a separate question can be made concerning it.BackgroundI am creating a 128-bit unsigned integer type , U128 , at my job where we write in VB.NET . I decided to implement the ability to explicitly cast U128 terms to Double ( i.e. , double in C # parlance ) terms . IEEE 754 binary64 and binary32 are rather trivial formats as they are almost identical to how base-10 real numbers are formatted—of course they must be made into finite sequences of bits and have biased exponents . Anyway , I first implemented it in Rust since Rust has a native 128-bit unsigned integer type , u128 ; and The Rustonomicon explicitly states how casts from u128 terms to f64 terms behave . This allowed me to test my algorithm with Rust ’ s ; and unsurprisingly due to the trivial nature of the algorithm—it is ≈ 12 lines of code—my implementation matched Rust ’ s for several edge cases and 1 billion randomly generated numbers—no , I did not take the time to formally verify that my algorithm was correct.I then ported my algorithm to VB.NET—knowing how much more popular C # is here , I rewrote it in C # as well and confirmed it had the same behavior—but I wanted to be confident that nothing got lost in translation . The best I could do was to compare casts of ULong ( ulong in C # ) terms to Double terms with casts of the equivalent ULongs as U128s to Doubles . Sure enough I was dismayed when I discovered 10648738977740919977UL was being cast differently than the equivalent U128 . I ( correctly ) assumed there was a problem with the rounding—FYI , the C # specification does not say how to round numbers that lie perfectly between two numbers ; but as expected , it rounds to even . When I compared the first byte—I am using a little-endian CPU—of the Double that my cast created with that of Rust ’ s , I found that mine was correct . At this point I assumed there was something “ fishy ” with VB.NET ( and later confirmed in C # ) since I typically trust Rust more and as previously stated the algorithm is rather trivial.Fortunately , I was not aware of the ( unfortunate ) quirk that C # allows for programs to use extended precision capabilities on CPUs that have them including non-compliant ones like x86-based CPUs that only have 80-bits of precision . Had I known that , I likely would have dropped it.It was not until I examined the first byte of the Double term , 10648738977740919977R ( 10648738977740919977d in C # ) , that I was truly befuddled as I found that it did agree with my algorithm . How could this be ? I used the same exact machine compiled with the same compiler for the same platform . Finally , I correctly surmised that there is likely a difference in behavior in how the lexical parser treats real literals with how it treats integral literals that are cast to Doubles . To test this theory , I hacked up the program in the initial post ( in VB.NET at the time ) .At this point , I assumed that implicit casts were using a different algorithm ( perhaps for efficiency reasons since one has to track 3 additional bits to know how to properly round ) . That is why my question was formulated the way it was . I wanted to know the algorithm so that my algorithm would align with it ( even though my initial algorithm is ( very likely ) technically correct per IEEE 754 ) .Luckily with the eventual help of mjwills , The General , and NetMage , it was discovered that it likely lied with the non-compliant extended precision capabilities of my CPU ; although the fact this happens at compilation time is fundamentally different than previous posts that highlighted runtime discrepancies.I encourage everyone to take the time to read the amazing answer and comments by tannergooding in the link of the answer I eventually posted ( including forking over the $ 15 to read the formal proof about when extended precision abilities are OK and the requirements of such ) . * Compiled with Microsoft Visual C # Compiler version 3.7.0-6.20459 for .NET Core 3.1 on Windows 10 Pro 18363.1139 on an Intel Core i7-6600U CPU . <code> using System ; using System.Diagnostics ; namespace App { internal static class Program { internal static void Main ( ) { Debug.Assert ( GetFirstByte ( 10648738977740919977 ) ! = GetFirstByte ( 10648738977740919977d ) ) ; } private static byte GetFirstByte ( double val ) { return BitConverter.GetBytes ( val ) [ 0 ] ; } } } using System ; using System.Diagnostics ; namespace App { internal static class Program { internal static void Main ( ) { Debug.Assert ( 10648738977740919977 ! = 10648738977740919977d ) ; } } } | How does C # implicitly cast terms of integral types to terms of double ? |
C_sharp : My class has a method which produces a Task < int > object using a TaskCompletionSource < int > . Then it does some asynchronous operations and sets the result . I need to know whether I can trust the task 's ContinueWith method or not : Can the caller of CalculateAsync method do something with the produced task and prevent its continuation from running ? <code> public Task < int > CalculateAsync ( ) { var source = new TaskCompletionSource ( ) ; DoSomeAsyncStuffAndSetResultOf ( source ) ; source.Task.ContinueWith ( t = > Console.WriteLine ( `` Is this reliable ? `` ) ) ; return source.Task ; } | How to cancel a task 's continuation ? |
C_sharp : I am currently cleaning up some of our legacy code base in which we make use of extern methods . The parameter names are all over the place in terms of naming conventions . I 'd like to consolidate them.ExampleCan I safely rename new_status to newStatus or will that break the contract ? ReSharper suggests it as a change , but I 'd like to verify it . I was not able to find documentation on it ( for or against it ) .I am not asking if renaming the method name itself is possible , just the parameter definitions.ReferencesAlias for function <code> [ DllImport ( `` customdll '' , CallingConvention = CallingConvention.Cdecl ) ] public static extern void SetStatus ( int new_status ) ; | Is it safe to rename extern method parameters in C # ? |
C_sharp : Does there exist a standard pattern for yield returning all the items within an Enumerable ? More often than I like I find some of my code reflecting the following pattern : The explicit usage of a foreach loop solely to return the results of an Enumerable reeks of code smell to me . Obviously I could abandon the use of yield return increasing the complexity of my code by explicitly building an Enumerable and adding the result of each standard yield return to it as well as adding a the range of the results of the methodReturningEnumerable . This would be unfortunate , as such I was hoping there exists a better way to manage the yield return pattern . <code> public IEnumerable < object > YieldReturningFunction ( ) { ... [ logic and various standard yield return ] ... foreach ( object obj in methodReturningEnumerable ( x , y , z ) ) { yield return obj ; } } | What is the proper pattern for handling Enumerable objects with a yield return ? |
C_sharp : I want to know is there a better/easier way to load users by birthday.I have a User instance , which has properties , including this one : public DateTime ? BirthDate { get ; set ; } What I want to do is to load that users who has bdays from one date to another : I do n't care about birthday year , for example , if I have 3 users with birthdays : DateTime ( 1991 , 3 , 20 ) ; DateTime ( 1990 , 4 , 25 ) ; DateTime ( 1989 , 3 , 10 ) ; LoadUsersByBirthday ( new DateTime ( 2990 , 3 , 1 ) , new DateTime ( 3013 , 4 , 15 ) ) should return 2 users - 1st and 3rd.My method looks like this : It works , but is there a better/easier way to do this ? <code> public IEnumerable < User > LoadUsersByBirthday ( DateTime from , DateTime into ) public IEnumerable < User > LoadUsersByBirthday ( DateTime from , DateTime into ) { var days = DateTime.DaysInMonth ( from.Year , from.Month ) ; var u1 = _unit.User.Load ( u = > ( ( DateTime ) ( u.BirthDate ) ) .Month == from.Month & & ( ( DateTime ) ( u.BirthDate ) ) .Day > = from.Day & & ( ( DateTime ) ( u.BirthDate ) ) .Day < = days ) ; var u2 = _unit.User.Load ( u = > ( ( DateTime ) ( u.BirthDate ) ) .Month > from.Month & & ( ( DateTime ) ( u.BirthDate ) ) .Month < into.Month ) ; var u3 = _unit.User.Load ( u = > ( ( DateTime ) ( u.BirthDate ) ) .Month == into.Month & & ( ( DateTime ) ( u.BirthDate ) ) .Day < = into.Day ) ; return u1.Concat ( u2 ) .Concat ( u3 ) ; } | Load users by birthday |
C_sharp : I 'm experimenting with switch statement pattern matching , and I 'm looking for a way to return false if either value in a two value tuple is zero . This is the code I 'm trying : In VSCode 1.47 and dotnetcore 3.14 I get a compile-time error : CS8652 : The feature 'type pattern ' is in Preview ` What is the best compatible way to write this code ? <code> static bool IsAnyValueZero ( ( decimal , decimal ) aTuple ) { switch ( aTuple ) { case ( decimal , decimal ) t when t.Item1 == 0 || t.Item2 == 0 : return true ; } return false ; } | How to use C # pattern matching with tuples |
C_sharp : I was wondering how could I use a custom object in more than one panel.I made a panelModified object ( extends from Panel ) and want to place it in two normal panels , so when the object change its status , both panels display the updated information.In my case the `` panelModified '' is a panel with some Buttons and an embeded video in it.Here is the code : it only shows in the panel2 : ( <code> panelPreview = new PanelPreview ( file ) ; ( panelModified object ) panel1.Controls.Add ( panelPreview ) ; panel2.Controls.Add ( panelPreview ) ; | How can I show an object in multiple panels ? |
C_sharp : I have a class of this type : But sometimes I need to use this class as a non generic class , ie the type TResult is void.I ca n't instantiate the class in the following way : Also , I 'd rather not specify the type omitting the angle brackets : I do n't want re-write the whole class because it does the same thing . <code> class A < TResult > { public TResult foo ( ) ; } var a = new A < void > ( ) ; var a = new A ( ) ; | What if T is void in Generics ? How to omit angle brackets |
C_sharp : I stumbled across this article and found it very interesting , so I ran some tests on my own : Test One : Outputs : Test Two : Outputs : According to the article , in Test One all of the lambdas contain a reference to i which causes them to all output 5 . Does that mean I get the expected results in Test Two because a new int is created for each lambda expression ? <code> List < Action > actions = new List < Action > ( ) ; for ( int i = 0 ; i < 5 ; ++i ) actions.Add ( ( ) = > Console.WriteLine ( i ) ) ; foreach ( Action action in actions ) action ( ) ; 55555 List < Action > actions = new List < Action > ( ) ; for ( int i = 0 ; i < 5 ; ++i ) { int j = i ; actions.Add ( ( ) = > Console.WriteLine ( j ) ) ; } foreach ( Action action in actions ) action ( ) ; 01234 | odd lambda behavior |
C_sharp : I 'm trying to connect Chrome extension and my C # application.I 'm using this code https : //stackoverflow.com/a/13953481/3828636Everything is almost working there in only one problem I can send message only 6 times and than my c # app does n't recieve anything . When I re-open my extension ( click on icon ) it works and c # app recieve messages but still only 6 times . What could be a problem ? I tried to send it like this : There is some limit of sending messages by port ? or what ? Thanks for help ! EDIT ! ! I have already made it . The problem was my C # application it was receiving messages but it was n't responsing.It was likeCHROME ( SEND ) - > C # CHROME ( SEND ) - > C # CHROME ( SEND ) - > C # CHROME ( SEND ) - > C # CHROME ( SEND ) - > C # CHROME ( SEND ) - > C # BLOCKED ( because to many sends without response ) but it should be like : CHROME ( SEND ) - > C # C # ( RESPONSE ) - > CHROMECHROME ( SEND ) - > C # C # ( RESPONSE ) - > CHROMECHROME ( SEND ) - > C # C # ( RESPONSE ) - > CHROMECHROME ( SEND ) - > C # C # ( RESPONSE ) - > CHROMECHROME ( SEND ) - > C # C # ( RESPONSE ) - > CHROME <code> function send ( data ) { var data = new FormData ( ) ; var xhr = new XMLHttpRequest ( ) ; xhr.open ( 'POST ' , listener , true ) ; xhr.onload = function ( ) { } ; xhr.send ( data ) ; } | Communication JQuery and C # |
C_sharp : Executing a UWP application in DEBUG works perfectly.Using exactly the same code compiled in RELEASE crashes with this error message when executing this code ( it 's using Dapper 1.5.1 and System.Data.SQLite 1.0.109.2 ) The application is UWP configured as below . Furthermore , the faulting code is a .NET Standard 2.0 Class LibraryWhy is it crashing on RELEASE only and how to fix it ? <code> System.PlatformNotSupportedException : 'Dynamic code generation is not supported on this platform . ' using ( var c = NewConnection ( ) ) { var sql = @ '' update settings set `` '' value '' '' = @ SetDate where `` '' key '' '' = 'week_date ' '' ; c.Execute ( sql , new { SetDate = date } ) ; // < = throws PlatformNotSupportedException // only on RELEASE not in DEBUG } | PlatformNotSupportedException throws when using Dapper with WP |
C_sharp : I 'm trying to debug ( hit breakpoint ) a python script which is executed through a new process from C # .I have installed Child Process Debugging Power tool as that tool supposedly allows one to do that.According to its documentation it requires two things : The parent process must be debugged with the native debugging enigneThe parent process must launch the child process using either the CreateProcess or CreateProcessAsUser Win32 APIs.My process is created as follows : And as far as I am aware , as long as I use the process should be started with CreateProcess . ( Req . 2 ) In my project I have also enabled native code debugging . ( Req.1 ) I have also included both python.pdb and python36.pdb in my symbols list.However it seems I 'm unable to find python3.pdbThis was not included when I installed python with debugging symbols and I do not seem to find it anywhere else.I am using visual studio 2017 , no breakpoints are hit . <code> ProcessStartInfo startInfo = new ProcessStartInfo ( ) ; Process p = new Process ( ) ; startInfo.CreateNoWindow = true ; startInfo.UseShellExecute = false ; startInfo.RedirectStandardOutput = false ; startInfo.RedirectStandardError = true ; startInfo.RedirectStandardInput = false ; ... p.StartInfo = startInfo ; p.EnableRaisingEvents = true ; p.Start ( ) ; UseShellExecute = false ; 'python.exe ' ( Win32 ) : Loaded ' C : \ ... \Python36\python.exe ' . Symbols loaded . 'python.exe ' ( Win32 ) : Loaded ' C : \ ... \Python36\python36.dll ' . Symbols loaded . 'python.exe ' ( Win32 ) : Loaded ' C : \ ... \python3.dll ' . Can not find or open the PDB file . | Mixed mode Debugging Python/C # using Child Process Debugging Power Tool |
C_sharp : ** I have 36 of these case statements each one for another for a different picture box ; how do I group them all into one case statement so my code can be more efficient** <code> private void makeMoleVisable ( int mole , PictureBox MoleHill ) { switch ( mole ) { case 1 : if ( p01.Image == pmiss.Image & & MoleHill.Image == pHill.Image ) { molesmissed ++ ; } p01.Image = MoleHill.Image ; break ; case 2 : if ( p02.Image == pmiss.Image & & MoleHill.Image == pHill.Image ) { molesmissed++ ; } p02.Image = MoleHill.Image ; break ; | How do I merge all the cases into One ? |
C_sharp : The following code works if Cassandra and the code are on the same machine : Assuming a username and password is needed if the code is on one machine and cassandra is on a different machine ( different ip address ) ? So I have tried : I get the following error message : The iptables on the node ( the cassandra server ) is currently set as follows : Note 1 : Both the machine with the app and the machine with cassandra installed can be pinged and tracerouted in both directions.Note 2 : I have tested the username and password and can log into the cassandra server without any issues when tried directly on the server.Note 3 : Cassandra is running in a VM which I just created today . The VM is a guest machine on the host machine which runs the code.Note 4 : Both the Host OS and Guest OS are Linux . <code> using System ; using Cassandra ; namespace CassandraInsertTest { class Program { static void Main ( string [ ] args ) { var cluster = Cluster.Builder ( ) .AddContactPoint ( `` 127.0.0.1 '' ) .Build ( ) ; var session = cluster.Connect ( `` test_keyspace '' ) ; session.Execute ( `` INSERT INTO test_table ( id , col1 , col2 ) VALUES ( 1 , 'data1 ' , 'data2 ' ) '' ) ; Console.WriteLine ( $ '' Finished '' ) ; Console.ReadKey ( ) ; } } } var cluster = Cluster.Builder ( ) .AddContactPoint ( `` 192.168.0.18 '' ) < - the ip address for the cassandra node .WithPort ( 9042 ) .WithCredentials ( `` username to log into the cassandra node '' , '' password to log into the cassandra node '' ) .Build ( ) ; userone @ desktop : ~/Desktop/vsc $ dotnet runUnhandled exception . Cassandra.NoHostAvailableException : All hosts tried for query failed ( tried 192.168.0.18:9042 : SocketException 'Connection refused ' ) at Cassandra.Connections.ControlConnection.Connect ( Boolean isInitializing ) at Cassandra.Connections.ControlConnection.InitAsync ( ) at Cassandra.Tasks.TaskHelper.WaitToCompleteAsync ( Task task , Int32 timeout ) at Cassandra.Cluster.Cassandra.SessionManagement.IInternalCluster.OnInitializeAsync ( ) at Cassandra.ClusterLifecycleManager.InitializeAsync ( ) at Cassandra.Cluster.Cassandra.SessionManagement.IInternalCluster.ConnectAsync [ TSession ] ( ISessionFactory ` 1 sessionFactory , String keyspace ) at Cassandra.Cluster.ConnectAsync ( String keyspace ) at Cassandra.Tasks.TaskHelper.WaitToComplete ( Task task , Int32 timeout ) at Cassandra.Tasks.TaskHelper.WaitToComplete [ T ] ( Task ` 1 task , Int32 timeout ) at Cassandra.Cluster.Connect ( String keyspace ) at HelloWorld.Program.Main ( String [ ] args ) in /home/userone/Desktop/vsc/Program.cs : line 17userone @ desktop : ~/Desktop/vsc $ node1 @ node1 : ~ $ sudo iptables -S-P INPUT ACCEPT-P FORWARD ACCEPT-P OUTPUT ACCEPT-A INPUT -i lo -j ACCEPT-A IMPUT -m conntrack -- ctstate RELATED , ESTABLISHED -j ACCEPT-A INPUT -p tcp -m tcp -- dport 22 -j ACCEPT-A INPUT -p tcp -m tcp -- dport 80 -j ACCEPT-A INPUT -s 192.168.0.73/32 -p tcp -m multiport -- dports 7000,7001,7199,9042,9160,9142 -m state -- state NEW , ESTABLISHED -j ACCEPTnode1 @ node1 : ~ $ | How do I connect to a Cassandra VM |
C_sharp : I have set up a VirtualPathProvider and it is working fine for direct url calls like http : // ... /home/index in the address bar.However , I would like this to work for the Html helper too , but right now it is ignoring the VirtualPathProvider for the html helper calls in the view : Is there a way to solve this problem ? In addtion I have an override for the WebViewPage so I would be able to override the initialization for helpers , but I have n't got a clue with what or how.Edit : I have tried this at two computers and , oddly enough , it works on another computer.So the question would actually become : Why does the VirtualPathProvider works on one and fails for 50 % on another computer ? But then this question would then become somewhat to vague , speculative even.Nonetheless I am not happy with this but it seems I would have to reinstall some things . : ( <code> public class HomeController { public ActionResult Index ( ) { // This triggers MyVirtualPathProvider functionallity when called via // the browsers address bar or anchor tag click for that matter . // But it does not trigger MyVirtualPathProvider for 'in-view ' calls like // @ { Html.RenderAction ( `` index '' , `` home '' ) ; } return View ( ) ; } } public class MyVirtualPathProvider : VirtualPathProvider { public override System.Web.Hosting.VirtualFile GetFile ( string virtualPath ) { // This method gets hit after the Controller call for return View ( ... ) ; if ( MyCondition ) return MyVirtualFileHandler.Get ( virtualPath ) ; return base.GetFile ( virtualPath ) ; } public override bool FileExists ( string virtualPath ) { // This method gets hit after the Controller call for return View ( ... ) ; if ( MyCondition ) return true ; return base.FileExists ( virtualPath ) ; } } @ { Html.RenderAction ( `` index '' , `` home '' ) ; } | Html helper does not use custom VirtualPathProvider |
C_sharp : This is a followup to this question : Cast < int > .Cast < int ? > applied on generic enum collection results in invalid cast exceptionWhy is that Gender [ ] is IEnumerable < int > returns true in the generic case ? Especially when they are not type compatible ? It had tripped me in the question I linked ! I think this question is the crux of the issue of the linked question.For someone interested , this is a corner case with arrays ( not really enums ) . Follow Eric Lippert 's blog article in the answer to know more of this edge case . This does n't happen with List < T > for instance : <code> enum Gender { Male , Female } Gender g = Gender.Male ; bool b = g is int ; // false , alright no issuesb = new [ ] { g } is IEnumerable < int > ; // false , alright no issuesb = Is < Gender , int > ( g ) ; //false , alright no issuesb = Is < Gender [ ] , IEnumerable < int > > ( new [ ] { g } ) ; // true , why on earth ! ! ! static bool Is < S , T > ( S s ) { return s is T ; } IEnumerable < int > c = new [ ] { Gender.Male } ; //not compilable b = Is < List < Gender > , IEnumerable < int > > ( new List < Gender > { g } ) ; // false , rightly | enum [ ] is IEnumerable < int > returns true in a generic method |
C_sharp : I think my logic is flawed ... .in a loop I have : this loop updates approximately once per second ... .the problem I have is that seconds always ends up with a zero ( 0 ) value . this is because the ItemPos value is always higher after first loop than elapsed.TotalSeconds . So for example : if 3 seconds passWhat am I doing wrong ? <code> int seconds = ( int ) ( elapsed.TotalSeconds / ItemPos ) * ( Count - ItemPos ) ; ItemCount = 20 , so 3/20 = 0.15 - rounds to zero ... . 0 * anything = 0 ... ... | Estimated time remaining , what am I missing ? |
C_sharp : I was working through the MSDN tutorial for Crystal Reports , and I get to the Binding the Embedded Report to the CrystalReportViewer Control step : When I try the build , it tells me that I am missing my using declaration for Hierarchical_Grouping class . This brings up two questions for me ... What is the namespace for this class definition ? Is there an easy way of determining the namespace of a given class ? In another answer I saw the 'ALT , SHIFT , F10 ' and the 'CTRL , [ period ] ' suggestions for intellisense , but they do n't work in my Visual Studio . I 'm sure I have done something ridiculously stupid ... .sorry in advance ... .Here 's the code for the form : <code> using System ; using System.Collections.Generic ; using System.ComponentModel ; using System.Data ; using System.Drawing ; using System.Text ; using System.Windows.Forms ; using CrystalDecisions.CrystalReports.Engine ; using CrystalDecisions.Shared ; namespace CrystalTest3 { public partial class Form1 : Form { private Hierarchical_Grouping hierarchicalGroupingReport ; public Form1 ( ) { InitializeComponent ( ) ; } private void ConfigureCrystalReports ( ) { hierarchicalGroupingReport = new Hierarchical_Grouping ( ) ; crystalReportViewer.ReportSource = hierarchicalGroupingReport ; } private void Form1_Load ( object sender , EventArgs e ) { ConfigureCrystalReports ( ) ; } } } | Missing Using directive for hierarchical_grouping in MSDN crystal reports tutorial |
C_sharp : Run enumeration of IAsyncEnumerable twice not possible ? Once CountAsync has been run , the await foreach wo n't enumerate any item . Why ? It seems there is no Reset method on the AsyncEnumerator.Source of data <code> var count = await itemsToImport.CountAsync ( ) ; await foreach ( var importEntity in itemsToImport ) { // wo n't run } private IAsyncEnumerable < TEntity > InternalImportFromStream ( TextReader reader ) { var csvReader = new CsvReader ( reader , Config ) ; return csvReader.GetRecordsAsync < TEntity > ( ) ; } | Run enumeration of IAsyncEnumerable twice not possible ? |
C_sharp : My answer to one of the question on SO was commented by Valentin Kuzub , who argues that inlining a property by JIT compiler will cause the reflection to stop working . The case is as follows : Fuzz function accepts a lambda expression and uses reflection to find the property . It is a common practice in MVC in HtmlHelper extensions.I do n't think that the reflection will stop working even if the Bar property gets inlined , as it is a call to Bar that will be inlined and typeof ( Foo ) .GetProperty ( `` Bar '' ) will still return a valid PropertyInfo.Could you confirm this please or my understanding of method inlining is wrong ? <code> class Foo { public string Bar { get ; set ; } public void Fuzz < T > ( Expression < Func < T > > lambda ) { } } Fuzz ( x = > x.Bar ) ; | Property / Method inlining and impact on Reflection |
C_sharp : I have a 123MB big intarray , and it is basically used like this : eval ( ) is called a lot ( ~50B times ) with different c and I would like to know if ( and how ) I could speed it up . I already use a unsafe function with an fixed array that makes use of all the CPUs . It 's a C # port of the TwoPlusTwo 7 card evaluator by RayW . The C++ version is insignificantly faster.Can the GPU be used to speed this up ? <code> private static int [ ] data = new int [ 32487834 ] ; static int eval ( int [ ] c ) { int p = data [ c [ 0 ] ] ; p = data [ p + c [ 1 ] ] ; p = data [ p + c [ 2 ] ] ; p = data [ p + c [ 3 ] ] ; p = data [ p + c [ 4 ] ] ; p = data [ p + c [ 5 ] ] ; return data [ p + c [ 6 ] ] ; } | Speeding up array lookup after traversing ? |
C_sharp : I 've found very strange C # compiler behavior for following code : In last line assert fails with following message : I understand why test fails : p2 = new SqlParameter ( `` @ p '' , 0 ) ; is resolved as SqlParameter ( string , SqlDbType ) and for other cases as SqlParameter ( string , object ) . But I do n't understand why this happens . For me it looks like a bug , but I ca n't believe that C # compiler could have such kind of bug.Any reasons for this ? P.S . It seems to be a problem for any method overload with enum parameter and 0 value ( SqlDbType is enum ) . <code> var p1 = new SqlParameter ( `` @ p '' , Convert.ToInt32 ( 1 ) ) ; var p2 = new SqlParameter ( `` @ p '' , 1 ) ; Assert.AreEqual ( p1.Value , p2.Value ) ; // PASS var x = 0 ; p1 = new SqlParameter ( `` @ p '' , Convert.ToInt32 ( x ) ) ; p2 = new SqlParameter ( `` @ p '' , x ) ; Assert.AreEqual ( p1.Value , p2.Value ) ; // PASS p1 = new SqlParameter ( `` @ p '' , Convert.ToInt32 ( 0 ) ) ; p2 = new SqlParameter ( `` @ p '' , 0 ) ; Assert.AreEqual ( p1.Value , p2.Value ) ; // FAIL ! ? Expected : 0 But was : null | Strange C # compiler behavior ( overload resolution ) |
C_sharp : I have a few jobs executed one after the other via ContinueJobWith < MyHandler > ( parentJobId , x = > x.DoWork ( ) ) .However , the second job is not getting processed and always sits in Awaiting state : The job itself is like this : Why this can happen and where to check for resultion ? We are using Autofac as DI container , but we have our own JobActivator implementation because we have to deal with multitenancy.We are using SQL Server 2019 for storage.Hangfire version is 1.7.10This is MVC 5 applicationI 've not seen any errors/exceptions in any logs or during debuggingAfter going through this I 've added this to our Autofac registrationThis made no difference.This is how the jobs are executed : All the parameters are either int , bool or string . If I enqueue the awaiting jobs by hand , they are executed without issues.I 've added Hangfire logging , but could not see any issues there : server starts , stops , jobs change status , but could not see any obvious errors there.What other things I should consider or where/how should I debug this ? <code> builder.RegisterType < BackgroundJobStateChanger > ( ) .As < IBackgroundJobStateChanger > ( ) .InstancePerLifetimeScope ( ) ; var parentJobId = _backgroundJobClient.Schedule < Handler > ( h = > h.ConvertCertToTraining ( certId , command.SetUpOneToOneRelationship ) , TimeSpan.FromSeconds ( 1 ) ) ; var filesCopyJObId = _backgroundJobClient.ContinueJobWith < Handler > ( parentJobId , h = > h.CopyAttachedFiles ( ) ) ; _backgroundJobClient.ContinueJobWith < Handler > ( filesCopyJObId , h = > h.NotifyUser ( command.CertificationToBeConvertedIds , _principal.GetEmail ( ) ) ) ; | Hangfire ContinueWithJob is stuck in awaiting state , though parent job has succeeded |
C_sharp : Is it possible somehow to define a constant that says what datatype to use for certain variables , similar to generics ? So in a certain class I would have something like the following : From the principle it should do the same as generics but I do n't want to write the datatype every time the constructor for this class is called . It should simply guarantee that for two ( or more ) variables the same datatype is used . <code> MYTYPE = System.String ; // some other code hereMYTYPE myVariable = `` Hello '' ; | C # : Declaring a constant variable for datatype to use |
C_sharp : I made an winform application that can detect , set and toggle IPv4 settings using C # . When the user wants to get IP automatically from DHCP I call Automatic_IP ( ) : Automatic_IP : And in the Getip method I extract the current IP address , subnet , gateway and the DNS regardless of the fact that all these could be manually set or automatically assigned by DHCP and update those values in the labels using the Update_current_data ( ) method.Getip : But the problem is I can not detect if the current IP is manually set or automatically assigned , though I can select select automatically from DHCP from the Automatic_IP method . The ManagementObject.InvokeMethod ( `` EnableDHCP '' , null ) ; can easily set it to obtain IP address automatically but I have no way to check if IP is set automatically or manually when the Application first starts.I did some digging and found similar posts like this . Although a very similar post exists here but this is about DNS and not IP settings . Basically I want to find which option is selected : <code> private void Automatic_IP ( ) { ManagementClass mctemp = new ManagementClass ( `` Win32_NetworkAdapterConfiguration '' ) ; ManagementObjectCollection moctemp = mctemp.GetInstances ( ) ; foreach ( ManagementObject motemp in moctemp ) { if ( motemp [ `` Caption '' ] .Equals ( _wifi ) ) //_wifi is the target chipset { motemp.InvokeMethod ( `` EnableDHCP '' , null ) ; break ; } } MessageBox.Show ( `` IP successfully set automatically. '' , '' Done ! `` , MessageBoxButtons.OK , MessageBoxIcon.Information ) ; Getip ( ) ; //Gets the current IP address , subnet , DNS etc Update_current_data ( ) ; //Updates the current IP address , subnets etc into a labels } public bool Getip ( ) { ManagementClass mc = new ManagementClass ( `` Win32_NetworkAdapterConfiguration '' ) ; ManagementObjectCollection moc = mc.GetInstances ( ) ; foreach ( ManagementObject mo in moc ) { if ( ! chipset_selector.Items.Contains ( mo [ `` Caption '' ] ) ) chipset_selector.Items.Add ( mo [ `` Caption '' ] ) ; if ( mo [ `` Caption '' ] .Equals ( _wifi ) ) { ipadd = ( ( string [ ] ) mo [ `` IPAddress '' ] ) [ 0 ] ; subnet = ( ( string [ ] ) mo [ `` IPSubnet '' ] ) [ 0 ] ; gateway = ( ( string [ ] ) mo [ `` DefaultIPGateway '' ] ) [ 0 ] ; dns = ( ( string [ ] ) mo [ `` DNSServerSearchOrder '' ] ) [ 0 ] ; break ; } } } | Detecting if `` Obtain IP address automatically '' is selected in windows settings |
C_sharp : I 'm developing a game using XNA and C # and was attempting to avoid calling new struct ( ) type code each frame as I thought it would freak the GC out . `` But wait , '' I said to myself , `` struct is a value type . The GC should n't get called then , right ? '' Well , that 's why I 'm asking here.I only have a very vague idea of what happens to value types . If I create a new struct within a function call , is the struct being created on the stack ? Will it simply get pushed and popped and performance not take a hit ? Further , would there be some memory limit or performance implications if , say , I need to create many instances in a single call ? Take , for instance , this code : Rectangle in this case is a struct . What happens when that new Rectangle is created ? What are the implications of having to repeat that line many times ( say , thousands of times ) ? Is this Rectangle created , a copy sent to the Draw method , and then discarded ( meaning no memory getting eaten up the more Draw is called in that manner in the same function ) ? P.S . I know this may be pre-mature optimization , but I 'm mostly curious and wish to have a better understanding of what is happening . <code> spriteBatch.Draw ( tex , new Rectangle ( x , y , width , height ) , Color.White ) ; | What happens when value types are created ? |
C_sharp : I saw the following code , Based on my understanding , I think the code should be rewritten as follows : Is that correct ? Based on http : //msdn.microsoft.com/en-us/library/scekt9xw % 28v=vs.80 % 29.aspxAn is expression evaluates to true if the provided expression is non-null , and the provided object can be cast to the provided type without causing an exception to be thrown . I think the extra checking for null is NOT necessary at all . In other words , that code `` obj ! = null '' should never be hit at all.Thank you// Updated //Output results : <code> public override bool Equals ( object obj ) { // From the book http : //www.amazon.co.uk/Pro-2010-NET-4-0-Platform/dp/1430225491 // Page 254 ! if ( obj is Person & & obj ! = null ) ... } public override bool Equals ( object obj ) { if ( obj is Person ) ... } using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; namespace ConsoleApplication2 { class Employee { public static void CheckIsEmployee ( object obj ) { if ( obj is Employee ) { Console.WriteLine ( `` this is an employee '' ) ; } else if ( obj == null ) { Console.WriteLine ( `` this is null '' ) ; } else { Console.WriteLine ( `` this is Not an employee '' ) ; } } } class NotEmployee { } class Program { static void Main ( string [ ] args ) { Employee e = new Employee ( ) ; Employee.CheckIsEmployee ( e ) ; Employee f = null ; Employee.CheckIsEmployee ( f ) ; NotEmployee g = new NotEmployee ( ) ; Employee.CheckIsEmployee ( g ) ; } } } this is an employeethis is nullthis is Not an employee | C # -- Is this checking necessary `` obj is Person & & obj ! = null '' |
C_sharp : I have two similar queries theoretically returning the same results : This request returns 0 items , even though it is supposed to return one.The following is a rewrite of the latter but with a call to the ToList ( ) method . This request works and returns the item expected in the first query ! Note : SessionManagement.Db.Linq < Item > ( false ) is a generic Linq to Nhibernate method with the boolean attribute determining if the request must be executed in the cache ( true ) or the database ( false ) . There is supposedly nothing wrong in this method as it works normally in many other parts of the solution . The mapping of Item is nothing fancy : no bags and the following parameters : lazy= '' false '' schema= '' dbo '' mutable= '' false '' polymorphism= '' explicit '' Why is this so ? Edit : The generated sql request of requestNoWorking ends with : ( Item.Group_ID is not null ) and Item.Group_ID= @ p0 ' , N ' @ p0 int ' , @ p0=11768 The generated sql request of requestWorking is roughly a select * from dbo.Items <code> var requestNotWorking = SessionManagement.Db.Linq < Item > ( false ) .Where ( i = > i.Group ! = null & & i.Group.Id == methodParameter ) .ToList ( ) ; var requestWorking = SessionManagement.Db.Linq < Item > ( false ) .ToList ( ) .Where ( i = > i.Group ! = null & & i.Group.Id == methodParameter ) .ToList ( ) ; | Unexpected Linq Behavior - ToList ( ) |
C_sharp : I am using HTML Agility pack in Xamarin forms to scrape data from a website . When a condition returns true , I want to send a push notification to all users . However , this data is changing a lot and I think it would cost a lot of internet data and maybe battery , if the device with this app is constantly collecting the data in the background to check a certain condition.This is a piece of the code to give you an idea : So I thought it might be a good idea to let only one device use this code and check if the condition is true and then only send the push notification to all users . I 've made this image to give you a better idea about what I mean.I thought it might be a good idea to use firebase messaging to send push notifications to all users , but how or what do I use to have only one device checking the C # ? Should I use a website with the C # code that is running 24/7 ( is this possible ? ) , or something else ? So ... how do I run C # code 24/7 ? EDIT : I found out about 'Firebase functions ' . Would this work for me ? I 'd have to change to javascript so I rather stick to C # . <code> var url = `` https : //www.goal.com/en-us/live-scores '' ; var httpClient = new HttpClient ( ) ; var html = await httpClient.GetStringAsync ( url ) ; var htmlDocument = new HtmlDocument ( ) ; htmlDocument.LoadHtml ( html ) ; var voetbalWedstrijdenHTML = htmlDocument.DocumentNode.Descendants ( `` div '' ) .Where ( node = > node.GetAttributeValue ( `` class '' , `` '' ) .Equals ( `` main-content '' ) ) .ToList ( ) ; | Use code on one device and show 'result ' with others using push notifications |
C_sharp : Can I write a hash code function for the following comparer logic ? Two instances of My are equal if at least two properites from ( A , B , C ) match.The Equals part is simple , but I 'm stumped on the hash code part , and part of me is thinking it might not be possible.UPDATE : In addition to the correct answer by Reed Copsey , a very important point about the general usefulness of a fuzzy comparer is clearly stated by Ethan Brown - please see his answer as well for a full understanding of what underlies this Question/Answer . <code> class MyOtherComparer : IEqualityComparer < My > { public bool Equals ( My x , My y ) { if ( Object.ReferenceEquals ( x , y ) ) return true ; if ( Object.ReferenceEquals ( x , null ) || Object.ReferenceEquals ( y , null ) ) return false ; int matches = 0 ; if ( x.A == y.A ) matches++ ; if ( x.B == y.B ) matches++ ; if ( x.C == y.C ) matches++ ; // match on two out of three return ( matches > 1 ) } // If Equals ( ) returns true for a pair of objects // then GetHashCode ( ) must return the same value for these objects . public int GetHashCode ( My x ) { // ? ? ? } } | Is it possible to write a hash code function for an comparer that matches many-to-many ? |
C_sharp : The .NET reference source shows the implementation of NextBytes ( ) as : InternalSample provides a value in [ 0 , int.MaxValue ) , as evidenced by it 's doc comment and the fact that Next ( ) , which is documented to return this range , simply calls InternalSample . My concern is that , since InternalSample can produce int.MaxValue different values , and that number is not evenly divisible by 256 , then we should have some slight bias in the resulting bytes , with some values ( in this case just 255 ) occurring less frequently than others.My question is : Is this analysis correct or is the method in fact unbiased ? If the bias exists , is it strong enough to matter for any real application ? FYI I know Random should not be used for cryptographic purposes ; I 'm thinking about it 's valid use cases ( e. g. simulations ) . <code> for ( int i=0 ; i < buffer.Length ; i++ ) { buffer [ i ] = ( byte ) ( InternalSample ( ) % ( Byte.MaxValue+1 ) ) ; } | Is Random.NextBytes biased ? |
C_sharp : I 'm currently writing a CLR profiler , and I came across something very odd . When throwing two different exceptions , one from the try clause and one from the catch clause , the CLR notifies me of the same instruction pointer.More specifically : I 'm registered to receive the ExceptionThrown callbackvirtual HRESULT STDMETHODCALLTYPE ExceptionThrown ( ObjectID thrownObjectId ) ; While inside that callback , I start a DoStackSnapshot on the current thread ( https : //docs.microsoft.com/en-us/dotnet/framework/unmanaged-api/profiling/icorprofilerinfo2-dostacksnapshot-method ) . The CLR calls my method for every frame : HRESULT stackSnapshotCallback ( FunctionID funcId , UINT_PTR ip , COR_PRF_FRAME_INFO , ULONG32 , BYTE context [ ] , void *clientData ) However , if I have an exception thrown from a try clause and the corresponding catch clause ( code examples are below ) , I receive the SAME ip for both . I 'll also mention that this is not a case of a rethrow , when this is expected , but a brand new exception which can even occur deep in the catch 's call stack.Upon researching this more and digging deep in the CoreCLR code , I could not find a reason for this to happen , which is why I 'm asking this here.I 'll also mention that this is VERY easily reproduce able in plain C # debugger , which I find quite shocking . I have used .Net Framework 4.5 , but this also happened on 4.6 and 4.7.I believe that if I understand why the following C # code behaves this way , I might understand why the CLR is doing this aswell.This code : Produces this result : Inside catch , instruction : 13. line : 54Outer catch , instruction : 13. line : 54I will also mention that the exception objects thrown do have the correct stack traces . So , for example , if I initiate the StackTrace objects like this : I do receive the expected result . The code above is also acting odd during profiling : both exceptions throw share the same instruction pointer.Below is the IL code that matches the C # code ( just to validate that this is n't a case of rethrow . Removed the prints for clarity ) : Any help will be extremely appreciated . Thanks ! <code> try { try { throw new Exception ( `` A '' ) ; } catch ( Exception ) { StackTrace st = new StackTrace ( true ) ; StackFrame sf = st.GetFrame ( 0 ) ; Console.WriteLine ( `` Inside catch , instruction : `` + sf.GetILOffset ( ) + `` . line : `` + sf.GetFileLineNumber ( ) ) ; throw new Exception ( `` B '' ) ; } } catch ( Exception ) { StackTrace st = new StackTrace ( true ) ; StackFrame sf = st.GetFrame ( 0 ) ; Console.WriteLine ( `` Outer catch , instruction : `` + sf.GetILOffset ( ) + `` . line : `` + sf.GetFileLineNumber ( ) ) ; } catch ( Exception e ) { StackTrace st = new StackTrace ( e ) ; private static void Main ( string [ ] args ) { /* 00005284 00 */ nop try { /* 00005285 00 */ nop try { /* 00005286 00 */ nop /* 00005287 72 CF 0F 00 70 */ ldstr `` A '' /* 0000528C 73 8E 00 00 0A */ newobj System.Exception : :.ctor ( string ) // returns void /* 00005291 7A */ throw } catch ( System.Exception ) { /* 00005292 26 */ pop /* 00005293 00 */ nop /* 00005294 72 D3 0F 00 70 */ ldstr `` B '' /* 00005299 73 8E 00 00 0A */ newobj System.Exception : :.ctor ( string ) // returns void /* 0000529E 7A */ throw } } catch ( System.Exception ) { /* 0000529F 26 */ pop /* 000052A0 00 */ nop /* 000052A1 00 */ nop /* 000052A2 DE 00 */ leave_s loc_32 } loc_32 : /* 000052A4 28 13 01 00 0A */ call System.Console : :Read ( ) // returns int /* 000052A9 26 */ pop /* 000052AA 2A */ ret } | CLR Profiling : DoStackSnapshot after a throw inside a catch block gives wrong instruction pointer |
C_sharp : I 'm building a message dispatch map in C # and mostly just playing around with some different approaches . I am curious about a performance difference I am measuring , but it 's not obvious why from looking at the IL.The message map : I then have a class hierarchy of Messages , similar to EventArgs in WPF , for example : and observer classes with handler functions : I am measuring 2 ways of adding & invoking handlers . I am wrapping the delegate call so I can get a bit of conceptual type safety and therein lies the perf difference.Approach 1 : listener callsApproach 2 : listener callsBoth approaches build a MessageHandler delegate that makes a cast and the same method call , but calling the delegates built using approach # 2 is a wee bit slower even though the generated IL looks identical . Is it extra runtime overhead in casting to a generic type ? Is it the type constraint ? I would expect the JITted delegates to be the same once the generic type is resolved . Thanks for any info . <code> delegate void MessageHandler ( Message message ) ; AddHandler ( Type t , MessageHandler handler ) { /* add 'handler ' to messageMap invocation list */ } delegate void GenericMessageHandler < T > ( T message ) ; AddHandler < T > ( GenericMessageHandler < T > handler ) where T : Message { AddHandler ( typeof ( T ) , e = > { handler ( ( T ) e ) ; } ) ; } Dictionary < Type , MessageHandler > messageMap ; public class Message { } public class VelocityUpdateMessage : Message void HandleVelocityUpdate ( VelocityUpdateMessage message ) { ... } AddHandler ( typeof ( VelocityUpdateMessage ) , e = > { HandleVelocityUpdate ( ( VelocityUpdateMessage ) e ) ; } ) ; AddHandler < VelocityUpdateMessage > ( HandleVelocityUpdate ) ; | Why is casting to a generic type slower than an explicit cast in C # ? |
C_sharp : I am trying to derive a class from ObservableCollection and I need to run just a single line of code each and every time any instance of this class is deserialized . My thought was to do this : But I do n't have access to those base methods related to serialization . Am I forced to re-write all of the serialization manually ? <code> [ Serializable ] public class ObservableCollection2 < T > : ObservableCollection < T > , ISerializable { public ObservableCollection2 ( ) : base ( ) { } public ObservableCollection2 ( SerializationInfo info , StreamingContext context ) : base ( info , context ) { // Put additional code here . } void ISerializable.GetObjectData ( SerializationInfo info , StreamingContext context ) { base.GetObjectData ( info , context ) ; } } | How can I run code in a C # class definition each time any instance of the class is deserialized ? |
C_sharp : In MVC3 , we could use the CanvasAuthorize Attribute ( in old FaceBook version ) properties like LoginDisplayMode , ReturnUrlPath , CancelUrlPath.How can we use them in Latest version 6.4 ? We have [ FacebookAuthorize ( `` Permissions '' ) ] in the MVC4 . But , how we could use other properties like LoginDisplayMode , ReturnUrlPath , CancelUrlPath . as mentioned above ? I have gone through this article at GitHub . But no help so farI have read this article suggested by Prabir . But no help so far <code> [ CanvasAuthorize ( Permissions = `` '' , LoginDisplayMode = `` popup '' , ReturnUrlPath = `` Some Url '' , CancelUrlPath = `` Some Url '' ) ] public ActionResult Index ( ) { return View ( ) ; } | What is the substitute of CanvasAuthorizeAttribute in FaceBook C # SDK 6.4 version |
C_sharp : Assume I have a classNow I want to filter duplicates in list of such audio 's by similarity ( not EXACT match ) condition . Basicaly it 's Levenstein distance with treshold correction by string total length . The problem is , general tip about IEqualityComparer is `` Always implement both GetHashCode and Compare '' . I obviuosly ca n't calc distance between strings in GetHashCode because it 's not a compare method at all . However in this case even similar audio 's will return different hashes and Distinct ( ) will treat it as different objects and compare ( ) method does not fired.I tried to force GetHashCode always returns 0 , so Compare called for each-to-each object in collection , but this is slow . So , finally , a question : is there anything I can do with .net out of the box or should I search some good algorithm for filtering ? <code> public class Audio { public string artist { get ; set ; } public string title { get ; set ; } // etc . } | .net Distinct ( ) and complex conditons |
C_sharp : I want my View to be as follows : This leads me to believe I need a Model that contains a list of another Model . So in a project containing nothing but this I would have : Is this correct or is there a better way ? <code> @ model MyProgram.Models.DocumentList @ { ViewBag.Title = `` View1 '' ; } @ foreach ( MyProgram.Models.Document doc in Model.GetDocs ( ) ) { < p > doc.Content < /p > } /Model/DocumentList.cs/Model/Document.cs | Simple best practices for ASP.NET models |
C_sharp : I understand that .NET is multi-threaded and that is a good thing , but I continually run into issues when I have a background worker for example that is updating some control on my form and I have to do : My question is why is this not built into the framework - surely if I am trying to update a DataGridView it should be intelligent enough to know when the update is from another thread and it could do all the above itself ? <code> Private Sub SetRowCellBoolValueThreadSafe ( ByVal row As Integer , ByVal col As Integer , ByVal value As Boolean ) If dgvDatabase.InvokeRequired Then Dim d As New SetRowCellBoolValueCallback ( AddressOf SetRowCellBoolValue ) Me.Invoke ( d , New Object ( ) { row , col , value } ) Else SetRowCellBoolValue ( row , col , value ) End IfEnd SubDelegate Sub SetRowCellBoolValueCallback ( ByVal row As Integer , ByVal col As Integer , ByVal value As Boolean ) Private Sub SetRowCellBoolValue ( ByVal row As Integer , ByVal col As Integer , ByVal value As Boolean ) dgvDatabase.Rows ( row ) .Cells ( col ) .Value = valueEnd Sub | Why is n't Invoke via Delegate built into .NET |
C_sharp : I have a LinqToEntities query that double produces a subquery when creating the SQL . This causes the result set to come back with 0-3 results , every time the query is run . The subquery on its own produces a single random result ( as it should ) . What is going on here ? The LINQ query : Produce this SQL : EDIT : So changing the subquery to this works , but I have no idea why <code> from jpj in JobProviderJobswhere jpj.JobID == 4725 & & jpj.JobProviderID == ( from jp2 in JobProviderJobs where jp2.JobID == 4725 orderby Guid.NewGuid ( ) select jp2.JobProviderID ) .FirstOrDefault ( ) select new { JobProviderID = jpj.JobProviderID } SELECT [ Filter2 ] . [ JobID ] AS [ JobID ] , [ Filter2 ] . [ JobProviderID1 ] AS [ JobProviderID ] FROM ( SELECT [ Extent1 ] . [ JobID ] AS [ JobID ] , [ Extent1 ] . [ JobProviderID ] AS [ JobProviderID1 ] , [ Limit1 ] . [ JobProviderID ] AS [ JobProviderID2 ] FROM [ dbo ] . [ JobProviderJob ] AS [ Extent1 ] LEFT OUTER JOIN ( SELECT TOP ( 1 ) [ Project1 ] . [ JobProviderID ] AS [ JobProviderID ] FROM ( SELECT NEWID ( ) AS [ C1 ] , [ Extent2 ] . [ JobProviderID ] AS [ JobProviderID ] FROM [ dbo ] . [ JobProviderJob ] AS [ Extent2 ] WHERE 4725 = [ Extent2 ] . [ JobID ] ) AS [ Project1 ] ORDER BY [ Project1 ] . [ C1 ] ASC ) AS [ Limit1 ] ON 1 = 1 WHERE 4725 = [ Extent1 ] . [ JobID ] ) AS [ Filter2 ] LEFT OUTER JOIN ( SELECT TOP ( 1 ) [ Project2 ] . [ JobProviderID ] AS [ JobProviderID ] FROM ( SELECT NEWID ( ) AS [ C1 ] , [ Extent3 ] . [ JobProviderID ] AS [ JobProviderID ] FROM [ dbo ] . [ JobProviderJob ] AS [ Extent3 ] WHERE 4725 = [ Extent3 ] . [ JobID ] ) AS [ Project2 ] ORDER BY [ Project2 ] . [ C1 ] ASC ) AS [ Limit2 ] ON 1 = 1WHERE [ Filter2 ] . [ JobProviderID1 ] = ( CASE WHEN ( [ Filter2 ] . [ JobProviderID2 ] IS NULL ) THEN 0 ELSE [ Limit2 ] . [ JobProviderID ] END ) ( from jp2 in JobProviderJobs where jp2.JobID == 4725 orderby Guid.NewGuid ( ) select jp2 ) .FirstOrDefault ( ) .JobProviderID | LinqToEntities produces incorrect SQL ( Doubled Subquery ) |
C_sharp : If I include outside reference inside where predicate then memory does not get releases.Let 's say I have a List < object > then if I write a where predicate like this : Even If I make myList = null or predicate = null , it is not releasing memory . I have List < object > itemsource binded to DataGrid . I also make it 's ItemSource null , disposing DataGrid , DataGrid null . . I also have analyzed this issue with ANTS Memory Profiler 7.4 . It also shows me that because of wherepredicate it is holding reference.If I change my wherepredicate like this in dispose ( ) , then memory is getting released.that means removing reference in WherePredicate . <code> List < object > myList = new List < object > ( ) ; ... myList.add ( object ) ; ... Expression < Func < object , bool > > predicate = p = > myList.Contains ( p ) ; Expression < Func < object , bool > > predicate = p = > p.id == 0 ; | Where predicates does not releases memory |
C_sharp : I built an application that can also be ran as a service ( using a -service ) switch . This works perfectly with no issues when I 'm running the service from a command prompt ( I have something set up that lets me debug it from a console when not being ran as a true service ) . However , when I try to run it as a true service then use my application to open the existing memory map , I get the error ... Unable to find the specified file.How I run it as a service or in console : In my application I have a service side and an application side . The application 's purpose is just to control the service . I do all the controlling using memory mapping files and it seems to work great and suits my needs . However , when I run the application as a true service I see from my debug logs it is creating the memory map file with the correct name and access settings . I can also see the file getting created where it should be . Everything seems to working exactly the same in the service as it does when I debug via console . However , my application ( when ran as an application instead of the service ) tells me it can not find the memory map file . I have it toss the file name path in the error as well so I know it 's looking in the right place.How I open the memory map ( where the error is thrown ) : Note : The service is running as the same account as I run Visual Studio in . As an example the image below shows my task manager , the services.msc gui and my currently identified account.How can I get my client application to see the memory map file after the service creates it ? Why does it work when I run it as a console service and not when I run it as a true service ? <code> [ STAThread ] static void Main ( string [ ] args ) { //Convert all arguments to lower args = Array.ConvertAll ( args , e = > e.ToLower ( ) ) ; //Create the container object for the settings to be stored Settings.Bag = new SettingsBag ( ) ; //Check if we want to run this as a service bool runAsService = args.Contains ( `` -service '' ) ; //Check if debugging bool debug = Environment.UserInteractive ; //Catch all unhandled exceptions as well if ( ! debug || debug ) { Application.SetUnhandledExceptionMode ( UnhandledExceptionMode.CatchException ) ; AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException ; } if ( runAsService ) { //Create service array ServiceBase [ ] ServicesToRun ; ServicesToRun = new ServiceBase [ ] { new CRSService ( ) } ; //Run services in interactive mode if needed if ( debug ) RunInteractive ( ServicesToRun ) ; else ServiceBase.Run ( ServicesToRun ) ; } else { //Start the main gui Application.EnableVisualStyles ( ) ; Application.SetCompatibleTextRenderingDefault ( false ) ; Application.Run ( new MainGUI ( ) ) ; } } m_mmf = MemoryMappedFile.OpenExisting ( m_sMapName , MemoryMappedFileRights.ReadWrite ) ; | Using memory maps with a service |
C_sharp : I have many working Entity Framework Scalar Function 's . However , when I try to return a 'truthy ' value through a scalar function I get the following exception : The specified method 'Boolean svfn_CanCloneDocument ( Int32 , System.String ) ' on the type 'ETC.Operations.DbClient.DbClient.Data.DbClientContext ' can not be translated into a LINQ to Entities store expression.The scalar function works when run using in SQL MANAGEMENT STUDIOChanging the RETURN TYPE does n't seem to work.I have tried changing the RETURN TYPE to ... intobjectboolWhy is this failing ? THE CALLING LOOKS LIKE : THE LET FUNCTION LOOKS LIKE : THE SQL LOOKS LIKE : <code> public IQueryable < ShakeoutDataItem > Query ( ) { var uow = UnitOfWork as DbClientUnitOfWork ; var dbContext = UnitOfWork.DbContext as DbClientContext ; var query = ( from document in dbContext.vDocumentStatus join shakeout in uow.Shakeout on document.DocumentId equals shakeout.DocumentId join shakeoutDetail in uow.ShakeoutDetail on shakeout.Id equals shakeoutDetail.ShakeoutId join meter in uow.Meter on shakeoutDetail.MeterId equals meter.Id join product in uow.Product on shakeout.ProductId equals product.Id into productLEFTJOIN from product in productLEFTJOIN.DefaultIfEmpty ( ) // THIS FAILS let cloneable = dbContext.svfn_CanCloneDocument ( document.DocumentId , `` SHAKEOUT '' ) select new ShakeoutDataItem ( ) { // Other fields LEFT OUT for BREVITY CanClone = cloneable } ) ; return query.OrderBy ( x = > x.DocumentCreatedDate ) .ThenBy ( x = > x.SchedulingBatch ) ; } [ Function ( FunctionType.ComposableScalarValuedFunction , nameof ( svfn_CanCloneDocument ) , Schema = `` dbo '' ) ] [ return : Parameter ( DbType = `` bit '' ) ] public bool svfn_CanCloneDocument ( int documentId , string documentTypeShortName ) { ObjectParameter documentIdParameter = new ObjectParameter ( `` documentId '' , documentId ) ; ObjectParameter documentTypeShortNameParameter = new ObjectParameter ( `` documentTypeShortName '' , documentTypeShortName ) ; return this.ObjectContext ( ) .ExecuteFunction < bool > ( nameof ( this.svfn_CanCloneDocument ) , documentIdParameter , documentTypeShortNameParameter ) .SingleOrDefault ( ) ; } CREATE FUNCTION [ dbo ] . [ svfn_CanCloneDocument ] ( @ DocumentId INT , @ DocumentTypeShortName NVARCHAR ( 50 ) ) RETURNS BITASBEGIN /* Name : [ dbo ] . [ svfn_CanCloneDocument ] Creation Date : 02/02/2019 Purpose : Retrieves the Full Name for given User.Id or returns NULL Input Parameters : @ DocumentId = The Id for the DOCUMENT record @ DocumentTypeShortName = The Short Name for the DOCUMENT TYPE record Format : @ DocumentId = 1 @ DocumentTypeShortName = SHAKEOUT */ DECLARE @ Value BIT = CAST ( 0 AS BIT ) ; -- NOTE : They are going to have more DOCUMENT TYPES later-on . If the rules for Cloneable are the same ... simplify this function IF ( @ DocumentTypeShortName = 'SHAKEOUT ' ) BEGIN DECLARE @ Id INT = ( SELECT TOP 1 Id FROM [ dbo ] . [ tvfn_ListDocumentDescendants ] ( @ DocumentId ) WHERE Id < > @ DocumentId ORDER BY Id DESC ) ; -- CAN CLONE When no Descendants Exist SELECT @ Value = ( CASE WHEN @ Id IS NULL THEN CAST ( 1 AS BIT ) ELSE CAST ( 0 AS BIT ) END ) END -- Return the result of the function RETURN @ ValueEND | Bit-Bool on a Entity Framework Scalar Function Throws ' can not be translated ' Exception |
C_sharp : Let 's have two code snippets : A : B : In case A the CLR will not even call the Bar ctor ( unless it is debug build or the debugger is attached ) , however in case B it is called under all circumstances.The thing is that in Bar constructor one can have calls that will make this instance reachable from elsewhere - most typically events subscriptions.So : Why are the cases A and B evaluated differently ? Why the CLR is not calling Bar ctor at all in case A - as itshould not evaluate it as garbage until ctor is finished and instanceis assigned to the appropriate field ? <code> public class Foo { private static Bar _unused = new Bar ( ) ; } public class Foo { private static Bar _unused ; static Foo ( ) { _unused = new Bar ( ) ; } } | Why CLR optimizing away unused static field with initialization ? |
C_sharp : So I have been playing around with C # lately and I do n't understand output formatting.OutputMy expected output was index i holds number Number [ i ] . So can anyone explain what to change , or link me with a good C # page on output formatting topic.I know there is a way to do it in 2 lines . <code> using System ; namespace Arrays { class Program { static void Main ( ) { Random r = new Random ( ) ; int [ ] Numbers = new int [ 10 ] ; for ( int i = 0 ; i < Numbers.Length ; i++ ) { Numbers [ i ] = r.Next ( 101 ) ; } for ( int i = 0 ; i < Numbers.Length ; i++ ) { Console.WriteLine ( `` index { 0 } holds number { 0 } '' , i , Numbers [ i ] ) ; } } } } | Simple C # output |
C_sharp : I 've been playing around with optional parameters and came accross the following scenario.If I have a method on my class where all the parameters are optional I can write the following code : If I then create an interface such as : If I make the Test class implement this interface then it wo n't compile as it says interface member A ( ) from IAInterface is n't implement . Why is it that the interface implementation not resolved as being the method with all optional parameters ? <code> public class Test { public int A ( int foo = 7 , int bar = 6 ) { return foo*bar ; } } public class TestRunner { public void B ( ) { Test test = new Test ( ) ; Console.WriteLine ( test.A ( ) ) ; // this recognises I can call A ( ) with no parameters } } public interface IAInterface { int A ( ) ; } | When interface method has no parameters why is n't the implementation recognised of a method with all optional parameters ? |
C_sharp : I am trying to implement a caching mechanism for enumerating collections safely , and I am checking if all modifications of the built-in collections are triggering an InvalidOperationException to be thrown by their respective enumerators . I noticed that in the .NET Core platform the Dictionary.Remove and Dictionary.Clear methods are not triggering this exception . Is this a bug or a feature ? Example with Remove : Output : [ 1 , Hello ] removed : True [ 2 , World ] removed : True Count : 0 Example with Clear : Output : [ 1 , Hello ] Count : 0 The expected exception is : InvalidOperationException : Collection was modified ; enumeration operation may not execute . ... as is thrown by the method Add , and by the same methods in .NET Framework..NET Core 3.0.0 , C # 8 , VS 2019 16.3.1 , Windows 10 <code> var dictionary = new Dictionary < int , string > ( ) ; dictionary.Add ( 1 , `` Hello '' ) ; dictionary.Add ( 2 , `` World '' ) ; foreach ( var entry in dictionary ) { var removed = dictionary.Remove ( entry.Key ) ; Console.WriteLine ( $ '' { entry } removed : { removed } '' ) ; } Console.WriteLine ( $ '' Count : { dictionary.Count } '' ) ; var dictionary = new Dictionary < int , string > ( ) ; dictionary.Add ( 1 , `` Hello '' ) ; dictionary.Add ( 2 , `` World '' ) ; foreach ( var entry in dictionary ) { Console.WriteLine ( entry ) ; dictionary.Clear ( ) ; } Console.WriteLine ( $ '' Count : { dictionary.Count } '' ) ; | Dictionary methods Remove and Clear ( .NET Core ) modify the collection during enumeration . No exception thrown |
C_sharp : I am writing a simple Memoize helper that allows caching method results instead of computing them every time . However , when I try to pass a method into Memoize , the compiler ca n't determine the type arguments . Are n't they obvious from my method signature ? Is there a way around this ? Sample code : Error message : <code> using System ; using System.Collections.Concurrent ; public static class Program { public static Func < T , V > Memoize < T , V > ( Func < T , V > f ) { var cache = new ConcurrentDictionary < T , V > ( ) ; return a = > cache.GetOrAdd ( a , f ) ; } // This is the method I wish to memoize public static int DoIt ( string a ) = > a.Length ; static void Main ( ) { // This line fails to compile ( see later for error message ) var cached1 = Memoize ( DoIt ) ; // This works , but is ugly ( and does n't scale to lots of type parameters ) var cached2 = Memoize < string , int > ( DoIt ) ; } } error CS0411 : The type arguments for method 'Program.Memoize < T , V > ( Func < T , V > ) ' can not be inferred from the usage . Try specifying the type arguments explicitly . | Why do I have to explicitly specify my type arguments for Func parameters ? |
C_sharp : Running an empty for-loop with large numbers of iterations , I 'm getting wildly different numbers in how long it takes to run : The above will run in around 200ms on my machine , but if I increase it to 1000000001 , then it takes 4x as long ! Then if I make it 1000000002 , then it 's down to 200ms again ! This seems to happen for an even number of iterations . If I go for ( var i = 1 ; i < 1000000001 , ( note starting at 1 instead of 0 ) then it 's 200ms . Or if I do i < = 1000000001 ( note less than or equal ) then it 's 200ms . Or ( var i = 0 ; i < 2000000000 ; i += 2 ) as well.This appears only to be on x64 , but on all .NET versions up to ( at least ) 4.0 . Also it appears only when in release mode with debugger detached.UPDATE I was thinking that this was likely due to some clever bit shifting in the jit , but the following seems to disprove that : if you do something like create an object inside that loop , then that takes about 4x as long too : This takes around 1 second on my machine , but then increasing by 1 to 1000000001 it takes 4 seconds . That 's an extra 3000ms , so it could n't really be due to bit shifting , as that would have shown up as a 3000ms difference in the original problem too . <code> public static class Program { static void Main ( ) { var sw = new Stopwatch ( ) ; sw.Start ( ) ; for ( var i = 0 ; i < 1000000000 ; ++i ) { } sw.Stop ( ) ; Console.WriteLine ( sw.ElapsedMilliseconds ) ; } } public static class Program { static void Main ( ) { var sw = new Stopwatch ( ) ; sw.Start ( ) ; object o = null ; for ( var i = 0 ; i < 1000000000 ; i++ ) { o = new object ( ) ; } sw.Stop ( ) ; Console.WriteLine ( o ) ; // use o so the compiler wo n't optimize it out Console.WriteLine ( sw.ElapsedMilliseconds ) ; } } | for-loop performance oddity in .NET x64 : even-number-iteration affinity ? |
C_sharp : I am trying to enumerate a large IEnumerable once , and observe the enumeration with various operators attached ( Count , Sum , Average etc ) . The obvious way is to transform it to an IObservable with the method ToObservable , and then subscribe an observer to it . I noticed that this is much slower than other methods , like doing a simple loop and notifying the observer on each iteration , or using the Observable.Create method instead of ToObservable . The difference is substantial : it 's 20-30 times slower . It is what it is , or am I doing something wrong ? Output : .NET Core 3.0 , C # 8 , System.Reactive 4.3.2 , Windows 10 , Console App , Release builtUpdate : Here is an example of the actual functionality I want to achieve : Output : Count : 10,000,000 , Sum : 49,999,995,000,000 , Average : 4,999,999.5The important difference of this approach compared to using standard LINQ operators , is that the source enumerable is enumerated only once.One more observation : using ToObservable ( Scheduler.Immediate ) is slightly faster ( about 20 % ) than ToObservable ( ) . <code> using System ; using System.Diagnostics ; using System.Linq ; using System.Reactive.Disposables ; using System.Reactive.Linq ; using System.Reactive.Subjects ; using System.Reactive.Threading.Tasks ; public static class Program { static void Main ( string [ ] args ) { const int COUNT = 10_000_000 ; Method1 ( COUNT ) ; Method2 ( COUNT ) ; Method3 ( COUNT ) ; } static void Method1 ( int count ) { var source = Enumerable.Range ( 0 , count ) ; var subject = new Subject < int > ( ) ; var stopwatch = Stopwatch.StartNew ( ) ; source.ToObservable ( ) .Subscribe ( subject ) ; Console.WriteLine ( $ '' ToObservable : { stopwatch.ElapsedMilliseconds : # ,0 } msec '' ) ; } static void Method2 ( int count ) { var source = Enumerable.Range ( 0 , count ) ; var subject = new Subject < int > ( ) ; var stopwatch = Stopwatch.StartNew ( ) ; foreach ( var item in source ) subject.OnNext ( item ) ; subject.OnCompleted ( ) ; Console.WriteLine ( $ '' Loop & Notify : { stopwatch.ElapsedMilliseconds : # ,0 } msec '' ) ; } static void Method3 ( int count ) { var source = Enumerable.Range ( 0 , count ) ; var subject = new Subject < int > ( ) ; var stopwatch = Stopwatch.StartNew ( ) ; Observable.Create < int > ( o = > { foreach ( var item in source ) o.OnNext ( item ) ; o.OnCompleted ( ) ; return Disposable.Empty ; } ) .Subscribe ( subject ) ; Console.WriteLine ( $ '' Observable.Create : { stopwatch.ElapsedMilliseconds : # ,0 } msec '' ) ; } } ToObservable : 7,576 msecLoop & Notify : 273 msecObservable.Create : 511 msec var source = Enumerable.Range ( 0 , 10_000_000 ) .Select ( i = > ( long ) i ) ; var subject = new Subject < long > ( ) ; var cntTask = subject.Count ( ) .ToTask ( ) ; var sumTask = subject.Sum ( ) .ToTask ( ) ; var avgTask = subject.Average ( ) .ToTask ( ) ; source.ToObservable ( ) .Subscribe ( subject ) ; Console.WriteLine ( $ '' Count : { cntTask.Result : # ,0 } , Sum : { sumTask.Result : # ,0 } , Average : { avgTask.Result : # ,0.0 } '' ) ; | Why is IEnumerable.ToObservable so slow ? |
C_sharp : I have : How I make it , as MyBook to inherit the top-level Book namespace , instead of Company 's ? <code> namespace Book { ... } ... ... namespace Company { public class Book { } ... ... ... ... ... ... public class MyBook : Book.smth { } } | When same-named namespaces exist ( in current scope ) , how to refer any of them ? |
C_sharp : I have a working solution for WP8.0 . But I needed to upgrade to get access to WNS . I have succeeded in adding WNS to the upgrade solution in the main menu works . But after Upgrading to wp8.1 ( silverlight ) , I have had some weird errors , that only happens on runtime . As an example it happens in the following usercontrol : Where the events are binded to my VM , the commands in the VM are defined as RelayCommand . As stated this was a working solution with no errors . I updated and still no errors when compiling . I have no code behind the view , but the error occurs in the line below marked with ERROR ( in the *.g.cs file ) The error refers to the line in < i : Interaction.Triggers > in the above xaml code.I have tried uninstalling and installing several packages with no success.I have tried to search around , and found ideas for including Mode=Oneway , and some stating error in the xaml parser . I am at a complete loss.Hope somebody can help ! The errorThis error is displayed everywhere I use i : interaction . I have looked for a way to find an wp8.1 version of System.Windows.Interactivity But have not been able to do so . I have therefore made sure that the MVVMLight tools are updated : Information based on the CommentDifference in new app.config Is a new addition.Difference in new WMAppManifest.xmlNotificationService= '' WNS '' Because I have set it up and it worksNEWOLDI have removed the capabilities I did not use anymore . And added in the new Package.appxmanifest for WP8.1I have per the other question also problem with the AGHost.exe , but I have not tried to delete it as I thought the below was mandatory. Can not find any other issue in this file.AssemblyInfo.cs and AppManifest.xml are the same . Looking at the reference folder the references seems okay , and are updated for wp8.1 ( those that could ) ExtraIf I copy the xaml code ( i.e path with interaction ) into another page that worked . Then it fails with the same error , during the xaml parsing for the page that worked without the snippet . New UpdateIt seems that upon my upgrade something got damaged in the solutions and the projects . The following I has found , is that I can get the code up and working in a new project.The code works if I run and deploy the project.If I on the other hand use the same project , that worked when deployed , now navigate to it from another project `` /BC_Creator ; component/MainPage.xaml '' Then the above error occurs again . My only idea now is to try and create completely new projects and copy-pasting the code into new files . Since importing them still does not seem to work . WTF has happend : S <code> < UserControlxmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' xmlns : i= '' clr-namespace : System.Windows.Interactivity ; assembly=System.Windows.Interactivity '' xmlns : cmd= '' clr-namespace : GalaSoft.MvvmLight.Command ; assembly=GalaSoft.MvvmLight.Platform '' xmlns : View= '' clr-namespace : ShieldGenerator.View '' xmlns : phone= '' clr-namespace : Microsoft.Phone.Controls ; assembly=Microsoft.Phone '' x : Class= '' ShieldGenerator.View.MoveableShieldGear '' mc : Ignorable= '' d '' Canvas.Left= '' { Binding Gear.x } '' Canvas.Top= '' { Binding Gear.y } '' Canvas.ZIndex= '' { Binding Gear.z } '' > < Path Data= '' { Binding Gear.Path } '' Fill= '' { Binding Gear.Color } '' Stretch= '' Fill '' UseLayoutRounding= '' False '' Height= '' { Binding Gear.Height } '' Width= '' { Binding Gear.Width } '' Opacity= '' { Binding Gear.Opacity } '' > < Path.RenderTransform > < TransformGroup > < ScaleTransform ScaleX= '' { Binding Gear.Scale } '' ScaleY= '' { Binding Gear.Scale } '' CenterX= '' { Binding Gear.CenterX } '' CenterY= '' { Binding Gear.CenterY } '' / > < RotateTransform Angle= '' { Binding Gear.Rotate } '' CenterX= '' { Binding Gear.CenterX } '' CenterY= '' { Binding Gear.CenterY } '' / > < SkewTransform AngleX= '' { Binding Gear.SkewX } '' AngleY= '' { Binding Gear.SkewY } '' CenterX= '' { Binding Gear.CenterX } '' CenterY= '' { Binding Gear.CenterY } '' / > < /TransformGroup > < /Path.RenderTransform > < i : Interaction.Triggers > < i : EventTrigger EventName= '' ManipulationStarted '' > < cmd : EventToCommand Command= '' { Binding MouseDownGearCommand } '' PassEventArgsToCommand= '' True '' / > < /i : EventTrigger > < i : EventTrigger EventName= '' ManipulationDelta '' > < cmd : EventToCommand Command= '' { Binding MouseGearMoveCommand , Mode=OneWay } '' PassEventArgsToCommand= '' True '' / > < /i : EventTrigger > < i : EventTrigger EventName= '' ManipulationCompleted '' > < cmd : EventToCommand Command= '' { Binding MouseUpGearCommand } '' PassEventArgsToCommand= '' True '' / > < /i : EventTrigger > < i : EventTrigger EventName= '' DoubleTap '' > < cmd : EventToCommand Command= '' { Binding DoubleTapCommand } '' PassEventArgsToCommand= '' True '' / > < /i : EventTrigger > < /i : Interaction.Triggers > < /Path > < /UserControl > namespace ShieldGenerator.View { public partial class MoveableShieldGear : System.Windows.Controls.UserControl { private bool _contentLoaded ; /// < summary > /// InitializeComponent /// < /summary > [ System.Diagnostics.DebuggerNonUserCodeAttribute ( ) ] public void InitializeComponent ( ) { if ( _contentLoaded ) { return ; } _contentLoaded = true ; System.Windows.Application.LoadComponent ( this , new System.Uri ( `` /ShieldGenerator ; component/View/MoveableShieldGear.xaml '' , System.UriKind.Relative ) ) ; //ERROR } } } < Capabilities > < Capability Name= '' ID_CAP_NETWORKING '' / > < Capability Name= '' ID_CAP_MEDIALIB_AUDIO '' / > < Capability Name= '' ID_CAP_WEBBROWSERCOMPONENT '' / > < Capability Name= '' ID_CAP_MEDIALIB_PHOTO '' / > < /Capabilities > < Capabilities > < Capability Name= '' ID_CAP_NETWORKING '' / > < Capability Name= '' ID_CAP_MEDIALIB_AUDIO '' / > < Capability Name= '' ID_CAP_MEDIALIB_PLAYBACK '' / > < Capability Name= '' ID_CAP_SENSORS '' / > < Capability Name= '' ID_CAP_WEBBROWSERCOMPONENT '' / > < Capability Name= '' ID_CAP_MEDIALIB_PHOTO '' / > < Capability Name= '' ID_CAP_PUSH_NOTIFICATION '' / > < Capability Name= '' ID_CAP_IDENTITY_USER '' / > < /Capabilities > < Capabilities > < Capability Name= '' internetClientServer '' / > < Capability Name= '' musicLibrary '' / > < Capability Name= '' picturesLibrary '' / > < Applications > < Application Id= '' xd82c080dy903dy47f4yba02y5a36d745c72bx '' Executable= '' AGHost.exe '' EntryPoint= '' StartUp/FirstPage.xaml '' > < m3 : VisualElements DisplayName= '' XXXXX '' Square150x150Logo= '' Assets\SquareTile150x150.png '' Square44x44Logo= '' Assets\Logo.png '' Description= '' XXXX '' ForegroundText= '' light '' BackgroundColor= '' # 464646 '' ToastCapable= '' true '' > < m3 : DefaultTile Square71x71Logo= '' Assets\SquareTile71x71.png '' > < /m3 : DefaultTile > < m3 : SplashScreen Image= '' Assets\Splashscreen.png '' / > < /m3 : VisualElements > < /Application > < /Applications > < Capabilities > < Capability Name= '' internetClientServer '' / > < Capability Name= '' musicLibrary '' / > < Capability Name= '' picturesLibrary '' / > < /Capabilities > < Extensions > < Extension Category= '' windows.activatableClass.inProcessServer '' > < InProcessServer > < Path > AgHostSvcs.dll < /Path > < ActivatableClass ActivatableClassId= '' AgHost.BackgroundTask '' ThreadingModel= '' both '' / > < /InProcessServer > < /Extension > < /Extensions > | xaml parse error on interaction triggers wp8.1 ( silverlight ) |
C_sharp : what 's the difference for the following two ways to define namespace ? in some where I may have Both need to do the same to use class AA by using A.B.C ; Can I use C.AA a ; to specify the AA class in C namespace or I have to use the fall namespace convention : A.B.C.AA a ; to avoid possbile confliction ? <code> namespace A.B.C { public class AA { } } namespace A { namespace B { namesapce C { public class AA { } } } } namespace A { //some classes } namespace A.B { //some classes } namespace A { namespace B { //some classes } } | C # namespace questions |
C_sharp : I 'm trying to create an extension VSPackage for VS2017 ( in C # ) which would convert binary data to XML , opens that in the default VS XML editor and XML language service , and then converts it back to binary upon saving.However , I have troubles to line out which steps would be required for this . I thought of the following for now when creating a new editor in the editor factory : Create new text bufferFeed it with converted XML dataCreate core editorFeed it with the text bufferRight now my attempt looks like this : When I try to explicitly open a file with my editor , it states `` The file can not be opened with the selected editor . Please choose another editor . '' The message does n't make sense to me , I tried to open XML data with the XML editor , but it somehow still tries to open a text editor with the binary data.I 'm stuck here , I did all I could think of to feed it converted data . Apparently this way is not the right one.How could I add steps inbetween to fetch the binary data , quickly convert it to XML , then feed it to the XML editor ? How would I store it back as binary when the XML editor saves the file ? Is it possible at all to reuse the XML editor and language services for this ? I 'm sorry if these questions require lengthy answers ; I 'd be happy already if I could get pointed in the right direction or to some already open-sourced extension doing something similar ( converting file data before displaying it in a VS code editor ) . <code> private MyPackage _package ; // Filled via constructorprivate IServiceProvider _serviceProvider ; // Filled via SetSitepublic int CreateEditorInstance ( uint grfCreateDoc , string pszMkDocument , string pszPhysicalView , IVsHierarchy pvHier , uint itemid , IntPtr punkDocDataExisting , out IntPtr ppunkDocView , out IntPtr ppunkDocData , out string pbstrEditorCaption , out Guid pguidCmdUI , out int pgrfCDW ) { // Initialize and validate parameters . ppunkDocView = IntPtr.Zero ; ppunkDocData = IntPtr.Zero ; pbstrEditorCaption = String.Empty ; pguidCmdUI = Guid.Empty ; pgrfCDW = 0 ; VSConstants.CEF createDocFlags = ( VSConstants.CEF ) grfCreateDoc ; if ( ! createDocFlags.HasFlag ( VSConstants.CEF.OpenFile ) & & ! createDocFlags.HasFlag ( VSConstants.CEF.Silent ) ) return VSConstants.E_INVALIDARG ; if ( punkDocDataExisting ! = IntPtr.Zero ) return VSConstants.VS_E_INCOMPATIBLEDOCDATA ; // Create a sited IVsTextBuffer storing the converted data with the XML data and language service set . IVsTextLines textLines = _package.CreateComInstance < VsTextBufferClass , IVsTextLines > ( ) ; SiteObject ( textLines ) ; string xmlText = BinaryXmlData.GetXmlString ( pszMkDocument ) ; textLines.InitializeContent ( xmlText , xmlText.Length ) ; ErrorHandler.ThrowOnFailure ( textLines.SetLanguageServiceID ( ref Guids.XmlLanguageServiceGuid ) ) ; // Instantiate a sited IVsCodeWindow and feed it with the text buffer . IVsCodeWindow codeWindow = _package.CreateComInstance < VsCodeWindowClass , IVsCodeWindow > ( ) ; SiteObject ( codeWindow ) ; codeWindow.SetBuffer ( textLines ) ; // Return the created instances to the caller . ppunkDocView = Marshal.GetIUnknownForObject ( codeWindow ) ; ppunkDocData = Marshal.GetIUnknownForObject ( textLines ) ; return VSConstants.S_OK ; } private void SiteObject ( object obj ) { ( obj as IObjectWithSite ) ? .SetSite ( _serviceProvider ) ; } // -- - CreateComInstance is a method on my package -- -- internal TInterface CreateComInstance < TClass , TInterface > ( ) { Guid guidT = typeof ( TClass ) .GUID ; Guid guidInterface = typeof ( TInterface ) .GUID ; TInterface instance = ( TInterface ) CreateInstance ( ref guidT , ref guidInterface , typeof ( TInterface ) ) ; if ( instance == null ) throw new COMException ( $ '' Could not instantiate { typeof ( TClass ) .Name } / { typeof ( TInterface ) .Name } . `` ) ; return instance ; } | VSX : How can I reuse the existing XML editor to handle binary files converted to XML ? |
C_sharp : I have a byte array that looks something like this : My end goal is to split this array into sub array 's anytime I see the sequence { 0x13 , 0x10 } . So my desired result on the example array would be : Ideally , I would also need to know that the final array , { 0x75 , 0x3a , 0x13 } , did not end with the search sequence so that I could work with that as a special case.Any thoughts on the best approach ? <code> byte [ ] exampleArray = new byte [ ] { 0x01 , 0x13 , 0x10 , 0xe2 , 0xb9 , 0x13 , 0x10 , 0x75 , 0x3a , 0x13 } ; { 0x01 } { 0xe2 , 0xb9 } { 0x75 , 0x3a , 0x13 } | How to properly search and parse an array using a sequence of elements as the target |
C_sharp : I 'm in a situation where two calls at the same time write to the session ( of an asp.net core application running on the old framework ) , and one of the session variables gets overwritten.Given the following controller code , assume that the long session gets called first , 200 ms later the short session gets called , and 800 ms later ( when the long session is done ) the result of both sessions gets called.The result of the final call ( TestBothSessions ) is `` A : , B : true '' .The question is then : Is there something I missed to make the session work ( aka , return `` A : true , B : true '' ) ? Obviously , I could remove the delay and all is fine , but in the real application there 's a call that potentially can take some time , and I prefer not to write the session variable at a later time ( I guess I could with a bit of custom error handling , but then the problem still remains that I no longer trust the asp.net session to work with synchronous calls ) .Edit : The typescript code that calls these endpoints from the browser : <code> [ HttpPost ( `` [ action ] '' ) ] public async Task < IActionResult > TestLongSession ( ) { HttpContext.Session.SetString ( `` testb '' , `` true '' ) ; // If we do this delay BEFORE the session ( `` testb '' ) is set , then all is fine . await Task.Delay ( 1000 ) ; return Ok ( ) ; } [ HttpPost ( `` [ action ] '' ) ] public async Task < IActionResult > TestShortSession ( ) { HttpContext.Session.SetString ( `` testa '' , `` true '' ) ; return Ok ( ) ; } [ HttpGet ( `` [ action ] '' ) ] public async Task < IActionResult > TestResultOfBothSessions ( ) { string a = HttpContext.Session.GetString ( `` testa '' ) ; string b = HttpContext.Session.GetString ( `` testb '' ) ; return Ok ( $ '' A : { a } , B : { b } '' ) ; } this.service.testLongSession ( ) .subscribe ( ( ) = > { this.service.testBothSessions ( ) .subscribe ( ( result : string ) = > { console.log ( result ) ; } ) ; } ) ; setTimeout ( ( ) = > { this.service.testShortSession ( ) .subscribe ( ) ; } , 200 ) ; | ASP.NET session is overwritten |
C_sharp : I 'm slowly getting my head around delegates , in that the signature of the delegate must match that of the method it is delegating too.However , please review the following code . I am now stumped at this point , because the delegate returns void ( as that is what SaveToDatabase ( ) is ) but , it 's clearly returning a ThreadStart ... Or is it ? If I were to write my own delegate , I would have no idea how to achieve this because the delegate would have to be void to match the return type of SaveToDatabase ( ) . But it ca n't be ; it would be of type ThreadStart ! My question is , have I totally mis-understood or is this made possible by some .NET trickery ? If I wanted to write this method but create my own delegate , how would I ? <code> public static void Save ( ) { ThreadStart threadStart = delegate { SaveToDatabase ( ) ; } ; new Thread ( threadStart ) .Start ( ) ; } private static void SaveToDatabase ( ) { } | How does the keyword delegate work compared to creating a delegate |
C_sharp : Hello I 'm try to remove special characters from user inputs . At the end I 'm turning it back to a string . My code only removes one special character in the string . Does anyone have any suggestions on a easier way instead <code> public void fd ( ) { string output = `` '' ; string input = Console.ReadLine ( ) ; char [ ] charArray = input.ToCharArray ( ) ; foreach ( var item in charArray ) { if ( ! Char.IsLetterOrDigit ( item ) ) { \\\CODE HERE } } output = new string ( trimmedChars ) ; Console.WriteLine ( output ) ; } | Special characters Regex |
C_sharp : From https : //msdn.microsoft.com/en-us/library/d5x73970.aspx When applying the where T : class constraint , avoid the == and ! = operators on the type parameter because these operators will test for reference identity only , not for value equality . This is the case even if these operators are overloaded in a type that is used as an argument . The following code illustrates this point ; the output is false even though the String class overloads the == operator.Everything is ok until i tried following , with same methodIt outputs 'True ' , s1 and s2 reference different objects in memory even they have same value right ? Am i missing something ? <code> public static void OpTest < T > ( T s , T t ) where T : class { System.Console.WriteLine ( s == t ) ; } static void Main ( ) { string s1 = `` target '' ; System.Text.StringBuilder sb = new System.Text.StringBuilder ( `` target '' ) ; string s2 = sb.ToString ( ) ; OpTest < string > ( s1 , s2 ) ; } static void Main ( ) { string s1 = `` target '' ; string s2 = `` target '' ; OpTest < string > ( s1 , s2 ) ; } | C # generic types equality operator |
C_sharp : How would I get change this snippet to correctly add an instance of A to a List < A > , B to a List < B > , etc . ? The exception is thrown because , while the Add ( ) is found by the binder , it passes in dynamic which fails overload resolution . I prefer not to change the above to use reflection , or at least to minimize that . I do have access to the instance of System.Type for each of A and List < A > . The class or method containing the above code is itself not generic . <code> // someChild 's actual type is Aobject someChild = GetObject ( ) ; // collection 's actual type is List < A > though method below returns objectdynamic list = GetListFromSomewhere ( ... ) ; // code below throws a RuntimeBinderExceptionlist.Add ( somechild ) ; | How to add a T to List < T > where List < T > masquerades as 'dynamic ' and T as 'object ' ? |
C_sharp : To my surprise I have discovered a powerful feature today . Since it looks too good to be true I want to make sure that it is not just working due to some weird coincidence.I have always thought that when my p/invoke ( to c/c++ library ) call expects a ( callback ) function pointer , I would have to pass a delegate on a static c # function . For example in the following I would always reference a delegate of KINSysFn to a static function of that signature.and call my P/Invoke with this delegate argument : But now I just tried and passed a delegate on an instance method and it worked also ! For example : Of course , I understand that inside managed code there is no technical problem at all with packaging a `` this '' object together with an instance method to form the respective delegate.But what surprises me about it , is the fact that the `` this '' object of MySystemFunctor.SystemFunction finds its way also to the native dll , which only accepts a static function and does not incorporate any facility for a `` this '' object or packaging it together with the function.Does this mean that any such delegate is translated ( marshalled ? ) individually to a static function where the reference to the respective `` this '' object is somehow hard coded inside the function definition ? How else could be distinguished between the different delegate instances , for example if I haveThese ca n't all point to the same function . And what if I create an indefinite number of MySystemFunctor objects dynamically ? Is every such delegate `` unrolled '' /compiled to its own static function definition at runtime ? <code> [ UnmanagedFunctionPointer ( CallingConvention.Cdecl ) ] public delegate int KINSysFn ( IntPtr uu , IntPtr fval , IntPtr user_data ) ; [ DllImport ( `` some.dll '' , EntryPoint = `` KINInit '' , ExactSpelling = true , CallingConvention = CallingConvention.Cdecl ) ] public static extern int KINInit ( IntPtr kinmem , KINSysFn func , IntPtr tmpl ) ; public class MySystemFunctor { double c = 3.0 ; public int SystemFunction ( IntPtr u , IntPtr v , IntPtr userData ) { } } // ... var myFunctor = new MySystemFunctor ( ) ; KINInit ( kinmem , myFunctor.SystemFunction , IntPtr.Zero ) ; var myFunctor01 = new MySystemFunctor ( ) ; // ... var myFunctor99 = new MySystemFunctor ( ) ; KINInit ( kinmem , myFunctor01.SystemFunction , IntPtr.Zero ) ; // ... KINInit ( kinmem , myFunctor99.SystemFunction , IntPtr.Zero ) ; | Delegate on instance method passed by P/Invoke |
C_sharp : Is there a way in C # to disable keyword 's functionality in code ? In my case I want to define one of my enum items as float which obviously makes Visual Studio a bit confused : ) <code> public enum ValidationType { email , number , float , range } | C # disable keyword functionality |
C_sharp : What does = > means ? Here 's a code snap : <code> Dispatcher.BeginInvoke ( ( Action ) ( ( ) = > { trace.Add ( response ) ; } ) ) ; | What does '= > ' mean ? |
C_sharp : I have the below method where I need to check for some certain strings which could be in any case and then remove them . Just wondered if there was a better performing way ? <code> private void MyMethod ( string Filter ) { //need to remove < Filter > and < /Filter > case in-sensitive var result = Filter.ToLower ( ) .Replace ( `` < filter > '' , '' '' ) ; result = Filter.ToLower ( ) .Replace ( `` < /filter > , '' '' ) ; ... ... ... ... ... ... ... ... ... } | Out of curiosity - is there a better performing approach to do this string replace ? |
C_sharp : Can anyone think of good Resharper pattern that will detect the following bug : I 've tried creating a pattern but I ca n't work out how to quickly handle all types of arithmetic ( e.g . + , - , * etc ) , and any nullable type ( e.g . Nullable < int > , Nullable < decimal > , Nullable < double > etc ) . Also I ca n't handle commutativity ( e.g . it should detect x + y as well as y + x ) .Note that I do n't necessarily need to detect whether or not x is actually null : just whether or not it is a nullable type . I want to force developers to write : x.Value + y.Value . <code> decimal ? x = null ; decimal ? y = 6M ; var total = x + y ; Console.WriteLine ( total ) ; // Result is null | Resharper pattern to detect arithmetic with nullable types |
C_sharp : This is homework ! ! ! Please do not interpret this as me asking for someone to code for me.My Program : http : //pastebin.com/SZP2dS8D This is my first OOP . The program works just fine without user input ( UI ) , but the implementation of it renders my design partially ineffective . I am not using a List collection because of assignment restrictions . My main goal is to have everything running from the Transcript class . Here are some issues I am running into : Allowing the user to add new course without having to create a new instance of Transcripteach timeAssociating the Courses added to a specific QuarterHere is some pseudo code to show what I am trying to accomplish . I have been experimenting with it , but have yet to succeed . MY QUESTION [ S ] : Should I keep the Transcript class , or discard it ? With the current functionality of creating a new course , is it possible to keep it this way while using UI , or do I need to head back to the chalk board and reconfigure ? Hopefully this is coherent and not too broad . If clarification is needed please ask and I will me more than happy to provide more details . <code> Please enter the quarter : ( user input ) Would you like to add a course ? while ( true ) Enter Course/Credits/Grade//new Course information populated with user input transcript.AddCourse.to specific Quarter ( ( Fall 2013 ) new Course ( `` Math 238 '' , 5 , 3.9 ) ) ; transcript.AddCourse.to specific Quarter ( ( Fall 2013 ) new Course ( `` Phys 223 '' , 5 , 3.8 ) ) ; transcript.AddCourse.to specific Quarter ( ( Fall 2013 ) new Course ( `` Chem 162 '' , 5 , 3.8 ) ) ; | C # : Bad design of class ( first OOP ) |
C_sharp : In my BL ( will be a public API ) , I am using ICollection as the return types in my Find methods , like : Note the use of ICollection instead of Collection < > .Now in my GUI , I need to cast the results back to Collection , like : This is because I need to use some Collection < > specific methods on my returned list , which I can not do with ICollection < > .Is this the correct usage ? Or should I simply change the return type from Collection < > instead to ICollection < > in order to avoid this casting ? Secondly , I did not use IEnumerable because it is more generic than ICollection and does not even have simple properties like Count . And I really don ’ t see a point in generalizing the return types here . Am I missing something important ? <code> public static ICollection < Customer > FindCustomers ( ) { Collection < Customer > customers = DAL.GetCustomers ( ) ; return customers ; } Collection < Customer > customers = ( Collection < Customer > ) BL.FindCustomers ( ) ; | Question regarding return types with collections |
C_sharp : I have the following in my controller ; This only occurs 4 times but it bugs me that I have the code repeated 4 times.I then have a BaseController that then grabs the parameters and does stuff with them ; I 'd like to be able to do away with the Post ActionResult 's and have a single one in a base controller say.Is this even possible ? <code> public ActionResult CocktailLoungeBarAttendant ( ) { return View ( ) ; } [ HttpPost ] public ActionResult cocktailLoungebarattendant ( string name , string email , string phone ) { return View ( ) ; } public ActionResult merchandisecoordinator ( ) { return View ( ) ; } [ HttpPost ] public ActionResult merchandisecoordinator ( string name , string email , string phone ) { return View ( ) ; } protected override void OnActionExecuting ( ActionExecutingContext filterContext ) { | Create common ActionResult |
C_sharp : tl ; dr : Overriding a generic iterator method in a constructed derived class results in a BadImageFormatException being thrown when compiled with Visual Studio 2010 ( VS2010 ) , regardless of .NET version ( 2.0 , 3.0 , 3.5 or 4 ) , platform or configuration . The problem is not reproducible in Visual Studio 2012 ( VS2012 ) and above.The contents of the base method ( provided the source compiles ) is irrelevant as it is not executed.How can this be avoided ? Description of problemWhen stepping into the in in Main in the code in the MVCE below ( which would normally move the execution to the iterator method ) , a BadImageFormatException is thrown when the code is compiled in Visual Studio 2010 : but not in Visual Studio 2012 and above : MCVEThings of noteWhen inspecting the code with ILSpy , the compiled IL for ScrappyDoo.GetIEnumerableItems was the same for both the VS2010 and VS2012 binaries : Likewise , the IL for the Main method is the same for both VS2010 and VS2012 binaries : In the binaries compiled by VS2012 , there is a method , < > n__FabricatedMethod4 , which does n't appear in VS2010 : VS2012 : VS2010 : ILSpy is unable to inspect the IL for the 'broken ' method in the VS2010 binaries , and encounters the following exception : Likewise , it is unable to view the contents of the ScrappyDoo.GetIEnumerableItems method as C # and shows a similar exception : When inspecting the binaries with DotPeek , the decompiled code for the VS2010- and VS2012-compiled code differs in the expression of the foreach statement : VS2010 : VS2012 ( note that the decompiled C # is the same as the source , as expected ) : The problem is not resolved by changing the method to a property , or by adding more logic into either the base or the override.Changing the base method to return IEnumerable < object > instead of IEnumerable < T > fixes the problem ( in this contrived case ) , but this is not an acceptable solution.The problem occurs when targeting .NET 2.0 , .NET 3.0 , .NET 3.5 , and .NET 4 in VS2010 . When compiled with VS2012 and above , the target framework version is irrelevant and the code behaves as expected.I 'm aware that Visual Studio does n't compile code - it just invokes MSBuild ( or Roslyn ) , but this problem is still an issue on a machine with VS2010 and VS2012 installed : when running the code in VS2010 the problem persists , and when running in VS2012 it does n't . Upon setting the build output verbosity to Diagnostic , I found that both VS2010 and VS2012 are using the same MSBuild binaries atThe problem does not appear in VS2015 ( using Roslyn to compile ) - the IL is different , but I guess that 's to be expected.I need to use Visual Studio 2010 as , where I work , we do some development on Windows XP which only supports 2010 and below.PEVerify gives the following output for the VS2010-compiled code : whereas for binaries compiled through VS2012 and above , the result is , as expected : When running the VS2010-compiled code from the command prompt results in the following output : My actual questionDoes anybody know why this is , and how it can be avoided ? For my actual use case , the iterator in the base has no items in it so I made the base method abstract and made all the derived classes override it , but that could change at any point , rendering the hack fix useless . <code> public class Program { public static void Main ( string [ ] args ) { foreach ( var item in new ScrappyDoo ( ) .GetIEnumerableItems ( ) ) Console.WriteLine ( item.ToString ( ) ) ; } } public class ScoobyDoo < T > where T : new ( ) { public virtual IEnumerable < T > GetIEnumerableItems ( ) { yield return new T ( ) ; } } public class ScrappyDoo : ScoobyDoo < object > { public override IEnumerable < object > GetIEnumerableItems ( ) { foreach ( var item in base.GetIEnumerableItems ( ) ) yield return item ; } } .method public hidebysig virtual instance class [ mscorlib ] System.Collections.Generic.IEnumerable ` 1 < object > GetIEnumerableItems ( ) cil managed { // Method begins at RVA 0x244c // Code size 21 ( 0x15 ) .maxstack 2 .locals init ( [ 0 ] class MysteryMachine.ScrappyDoo/ ' < GetIEnumerableItems > d__0 ' , [ 1 ] class [ mscorlib ] System.Collections.Generic.IEnumerable ` 1 < object > ) IL_0000 : ldc.i4.s -2 IL_0002 : newobj instance void MysteryMachine.ScrappyDoo/ ' < GetIEnumerableItems > d__0 ' : :.ctor ( int32 ) IL_0007 : stloc.0 IL_0008 : ldloc.0 IL_0009 : ldarg.0 IL_000a : stfld class MysteryMachine.ScrappyDoo MysteryMachine.ScrappyDoo/ ' < GetIEnumerableItems > d__0 ' : : ' < > 4__this ' IL_000f : ldloc.0 IL_0010 : stloc.1 IL_0011 : br.s IL_0013 IL_0013 : ldloc.1 IL_0014 : ret } // end of method ScrappyDoo : :GetIEnumerableItems .method public hidebysig static void Main ( string [ ] args ) cil managed { // Method begins at RVA 0x2050 // Code size 69 ( 0x45 ) .maxstack 2 .entrypoint .locals init ( [ 0 ] object item , [ 1 ] class [ mscorlib ] System.Collections.Generic.IEnumerator ` 1 < object > CS $ 5 $ 0000 , [ 2 ] bool CS $ 4 $ 0001 ) IL_0000 : nop IL_0001 : nop IL_0002 : newobj instance void MysteryMachine.ScrappyDoo : :.ctor ( ) IL_0007 : callvirt instance class [ mscorlib ] System.Collections.Generic.IEnumerable ` 1 < ! 0 > class MysteryMachine.ScoobyDoo ` 1 < object > : :get_GetIEnumerableItems ( ) IL_000c : callvirt instance class [ mscorlib ] System.Collections.Generic.IEnumerator ` 1 < ! 0 > class [ mscorlib ] System.Collections.Generic.IEnumerable ` 1 < object > : :GetEnumerator ( ) IL_0011 : stloc.1 .try { IL_0012 : br.s IL_0027 // loop start ( head : IL_0027 ) IL_0014 : ldloc.1 IL_0015 : callvirt instance ! 0 class [ mscorlib ] System.Collections.Generic.IEnumerator ` 1 < object > : :get_Current ( ) IL_001a : stloc.0 IL_001b : ldloc.0 IL_001c : callvirt instance string [ mscorlib ] System.Object : :ToString ( ) IL_0021 : call void [ mscorlib ] System.Console : :WriteLine ( string ) IL_0026 : nop IL_0027 : ldloc.1 IL_0028 : callvirt instance bool [ mscorlib ] System.Collections.IEnumerator : :MoveNext ( ) IL_002d : stloc.2 IL_002e : ldloc.2 IL_002f : brtrue.s IL_0014 // end loop IL_0031 : leave.s IL_0043 } // end .try finally { IL_0033 : ldloc.1 IL_0034 : ldnull IL_0035 : ceq IL_0037 : stloc.2 IL_0038 : ldloc.2 IL_0039 : brtrue.s IL_0042 IL_003b : ldloc.1 IL_003c : callvirt instance void [ mscorlib ] System.IDisposable : :Dispose ( ) IL_0041 : nop IL_0042 : endfinally } // end handler IL_0043 : nop IL_0044 : ret } // end of method Program : :Main System.NullReferenceException : Object reference not set to an instance of an object . at ICSharpCode.Decompiler.Disassembler.DisassemblerHelpers.WriteTo ( TypeReference type , ITextOutput writer , ILNameSyntax syntax ) at ICSharpCode.Decompiler.Disassembler.DisassemblerHelpers.WriteTo ( TypeReference type , ITextOutput writer , ILNameSyntax syntax ) at ICSharpCode.Decompiler.Disassembler.ReflectionDisassembler.DisassembleMethodInternal ( MethodDefinition method ) at ICSharpCode.ILSpy.TextView.DecompilerTextView.DecompileNodes ( DecompilationContext context , ITextOutput textOutput ) at ICSharpCode.ILSpy.TextView.DecompilerTextView. < > c__DisplayClass31_0. < DecompileAsync > b__0 ( ) ICSharpCode.Decompiler.DecompilerException : Error decompiling System.Collections.Generic.IEnumerable ` 1 < System.Object > MysteryMachine.ScrappyDoo : :GetIEnumerableItems ( ) -- - > System.NullReferenceException : Object reference not set to an instance of an object . // stack trace elided // ISSUE : reference to a compiler-generated methodforeach ( object obj in ( IEnumerable < object > ) this. < > n__FabricatedMethod4 ( ) ) yield return obj ; foreach ( object obj in base.GetIEnumerableItems ( ) ) yield return obj ; C : \Windows\Microsoft.NET\Framework\v4.0.30319 > peverify MysteryMachine2010.exeMicrosoft ( R ) .NET Framework PE Verifier . Version 4.0.30319.0Copyright ( c ) Microsoft Corporation . All rights reserved . [ IL ] : Error : [ MysteryMachine2010.exe : MysteryMachine.ScrappyDoo : : < > n__FabricatedMethod4 ] [ HRESULT 0x8007000B ] - An attempt was made to load a program with an incorrect format . [ IL ] : Error : [ MysteryMachine2010.exe : MysteryMachine.ScrappyDoo+ < getIEnumerableItems > d__0 : :MoveNext ] [ HRESULT 0x8007000B ] - An attempt was made to load a program with an incorrect format.2 Error ( s ) Verifying MysteryMachine2010.exe > peverify `` MysteryMachine2012.exe '' Microsoft ( R ) .NET Framework PE Verifier . Version 4.0.30319.0Copyright ( c ) Microsoft Corporation . All rights reserved.All Classes and Methods in MysteryMachine2012.exe Verified . > MysteryMachine2010.exeUnhandled Exception : System.BadImageFormatException : An attempt was made to load a program with an incorrect format . ( Exception from HRESULT : 0x8007000B ) at MysteryMachine.ScrappyDoo. < getIEnumerableItems > d__0.MoveNext ( ) at MysteryMachine.Program.Main ( String [ ] args ) in MysteryMachine\Program.cs : line 11 | Overriding generic iterator results in BadImageFormatException when compiled with Visual Studio 2010 |
C_sharp : I 've considered 2 cases : Ideone : http : //ideone.com/F8QwHYand : Ideone : http : //ideone.com/hDTcxXThe question is why does order of fields actually matter ? Is there any reason for this or it 's just simply because it is ( such is the design ) .If the reason is just that anonymus types are not supposed to be used this way and you are not supposed to appeal to GetType , then why does compiler re-use a single class in first case and not just generate a new class for each anonymus type declaration ? <code> var a = new { a = 5 } ; var b = new { a = 6 } ; Console.WriteLine ( a.GetType ( ) == b.GetType ( ) ) ; // True var a = new { a = 5 , b = 7 } ; var b = new { b = 7 , a = 6 } ; Console.WriteLine ( a.GetType ( ) == b.GetType ( ) ) ; // False | Why does compiler generate different classes for anonymous types if the order of fields is different |
C_sharp : The following is a simplified version of the problem I 'm having : The comments are the values from the watch window in Visual Studio 2017However if I enter : in the watch window , I get : So how come I can cast it in the watch window and it works , but if I do it in the code it evaluates to null ? <code> var list = new List < int > { 1 , 2 , 3 , 4 , 5 } ; // list Count = 5 System.Collections.Generic.List < int > var obj = list as object ; // obj Count = 5 object { System.Collections.Generic.List < int > } var enumerable = obj as IEnumerable < object > ; // enumerable null System.Collections.Generic.IEnumerable < object > obj as IEnumerable < object > obj as IEnumerable < object > Count = 5 System.Collections.Generic.IEnumerable < object > { System.Collections.Generic.List < int > } | Casting object to IEnumerable < object > |
C_sharp : i ca n't understand the difference between a simple bare and I know I can use it only if i have a +1 overloaded ctor , but I ca n't understand the advantages of defining the parameterless constructor this way . <code> Public ClassName ( ) { } Public ClassName ( ) : this ( null ) { } | When and why should I use ClassName : this ( null ) ? |
C_sharp : Simplified , i have these 2 Extension method : And here is where i use them : I have more GetString ( ) extensions.My try { ... } catch { ... } is getting large and basically i search for ways to shorten it down to 1 catch that calls the extension based on the type of the exception.Is there a way to call the right extension method at runtime ? <code> public static class Extensions { public static string GetString ( this Exception e ) { return `` Standard ! ! ! `` ; } public static string GetString ( this TimeoutException e ) { return `` TimeOut ! ! ! `` ; } } try { throw new TimeoutException ( ) ; } catch ( Exception e ) { Type t = e.GetType ( ) ; //At debugging this a TimeoutException Console.WriteLine ( e.GetString ( ) ) ; //Prints : Standard } | Calling extension method 's overload with derived type |
C_sharp : While removing some obsolete code I came across an unexpected scenario , recreated below : Based in the output it seems that functions deprecated with a warning are permitted to call functions deprecated with an error and the code will execute . My expectation was that I would see a compiler error complaining that the call to HardDeprecatedMethod ( ) from SoftDeprecatedMethod ( ) is not permitted.The observed behavior seems odd to me . Does anyone know if this is the desired behavior ( and if so , why ) , or could this be a flaw in the implementation of the [ Obsolete ] attribute ? <code> class Program { static void Main ( string [ ] args ) { ViableMethod ( ) ; Console.WriteLine ( `` '' ) ; SoftDeprecatedMethod ( ) ; //Compiler warning //HardDeprecatedMethod ( ) ; //Ca n't call that from here , compiler error Console.ReadKey ( true ) ; } public static void ViableMethod ( ) { Console.WriteLine ( `` ViableMethod , calls SoftDeprecatedMethod '' ) ; SoftDeprecatedMethod ( ) ; //Compiler warning //HardDeprecatedMethod ( ) ; //Ca n't call that from here , compiler error } [ Obsolete ( `` soft '' , false ) ] public static void SoftDeprecatedMethod ( ) { Console.WriteLine ( `` SoftDeprecatedMethod , calls HardDeprecatedMethod '' ) ; HardDeprecatedMethod ( ) ; } [ Obsolete ( `` hard '' , true ) ] public static void HardDeprecatedMethod ( ) { Console.WriteLine ( `` HardDeprecatedMethod '' ) ; } } | Deprecation behavior using the [ Obsolete ] attribute |
C_sharp : EDIT : see my update below on my stance on Null in C # 8.0 before giving me options to patterns and suchOriginal questionI am trying to upgrade my base libraries to be `` null enabled '' , aka using the C # 8.0 < Nullable > enable < /Nullable > flag.When trying to work with abstractions , and in specific generics , I ran into some problems . Consider the following code snippet which takes in an Action and converts this to a Func < TResult > . This is pre-nullable-enable : but post-nullable-enable I seem to struggle , since I cant make TResult nullable ( or TResult ? ) as wit would require a constraint of either where TResult : class or where TResult : struct . There is no way I can combine these two constraints to let the compiler know that TResult can be a class or a valuetype . Which at the moment I find annoying - as one should be able to express it does n't matter whether class or struct , it 'll be nullable ( regardless of previous .NET intherited design ) .So , post-nullable-enable I seem to have only one option , and that is code duplication , examples below : Both the code duplication as well as the naming schemes that come with it bother me a lot . I might be misunderstanding proper usage , or maybe I 'm missing another feature of the spec , but how would you solve this ? UPDATE : In fact , I think I 'd rather stick to my own `` null-handling '' implementations than using C # 8.0 's nullable feature . As a `` Void '' object or fleshed out `` Option/Maybe/None '' -solution seems to communicate things better . The only thing I am concerned about is that it is n't very helpful in moving the language forward , training new coders and introduces another third party/non native solutation to a universal provlem we all have dealing with null . Because own implementations of handling with null are great and all , but come up differently in each code base , need to be maintained by the community , and you have various different flavours . So it would be so helpful and hugely beneficial if the language enforced it fully , and if a standard rised . Which I hoped this would be - clearly it is not , and I understand . But I feel this is a missed opportunity.ThxYves <code> public static Func < TResult > ToFunc < TResult > ( this Action action ) = > ( ) = > { action ( ) ; return default ; } ; public static Func < TResult ? > ToFuncClass < TResult > ( this Action action ) where TResult : class = > ( ) = > { action ( ) ; return null ; } ; public static Func < TResult ? > ToFuncStruct < TResult > ( this Action action ) where TResult : struct = > ( ) = > { action ( ) ; return null ; } ; | Generics and Nullable ( class vs struct ) |
C_sharp : When calling a method with a ref or out parameter , you have to specify the appropriate keyword when you call the method . I understand that from a style and code quality standpoint ( as explained here for example ) , but I 'm curious whether there is also a technical need for the keywords to be specified in the caller.For example : <code> static void Main ( ) { int y = 0 ; Increment ( ref y ) ; // Is there any technical reason to include ref here ? } static void Increment ( ref int x ) { x++ ; } | Is there a technical reason for requiring the `` out '' and `` ref '' keywords at the caller ? |
C_sharp : Could someone point out why this could be happening : I am using NHibernate and the Linq provider for it.The code that fails is listed here : Debugging shows that sequence ( which is an IQueryable < T > ) after this contains 2 elements , which were added to the database.I expect the first Where statement to yield all elements from that sequence , but unfortunately it leaves 0 elements. ( WHY ? ? ? ) The second Where statement , on the contrary , actually yields 2 elements as it should work.Here are the NHibernate - > Sqlite queries for the first and second Where statements.Now , if I test the same code with my InMemoryRepository , which stores every entity in a simple list , the ( x = > true ) works absolutelty fine.So - why does this happen when using NHibernate ? Is this a bug or I am doing something wrong ? Thank you . <code> var sequence = session.Query < T > ( ) ; var wtfSequence = sequence.Where ( x = > true ) ; var okaySequence = sequence.Where ( x = > x.Id > 0 ) ; NHibernate : select cast ( count ( * ) as INTEGER ) as col_0_0_ from `` BinaryUnitProxy_IndicatorUnitDescriptor '' binaryunit0_ where @ p0='true ' ; @ p0 = 'True ' [ Type : String ( 0 ) ] NHibernate : select cast ( count ( * ) as INTEGER ) as col_0_0_ from `` BinaryUnitProxy_IndicatorUnitDescriptor '' binaryunit0_ where binaryunit0_.Id > @ p0 ; @ p0 = 0 [ Type : Int32 ( 0 ) ] | C # strange lambda behavior |
C_sharp : I am using Xamarin.Forms and I have 2 pages , one is a List View , the other is a just a view I am using as a filter for the List View . I am currently using Navigation.PushAsync to display this page , my question is , is there away to present it like a side menu ? I know there is Master Detail View which I am already using for the main menu and I dont think I can have 2 Master Details in my app , I tried that approach but it adds an additional navigation.Here is my code.UPDATEIs there away to have 2 details in 1 master to accomplish this ? I really do n't want to use a 3rd party library . <code> public partial class PatientsPage : ContentPage { public PatientsPage ( ) { InitializeComponent ( ) ; ToolbarItems.Add ( new ToolbarItem ( `` Filter '' , `` filter.png '' , ( ) = > { openFilter ( ) ; } ) ) ; } public async void openFilter ( ) { await Navigation.PushAsync ( new PatientFiltersPage ( ) ) ; } } | Xamarin.Forms Navigation.PushAsync as Side Menu |
C_sharp : I am using the debugger to step through my code . The code file I ’ m in has usings at the top , including for exampleIn Visual Studio 2008 this used to apply to the Watch window while debugging , so I could use extension methods such as .First ( ) and .ToArray ( ) in the watch window.For some reason , this has stopped working in Visual Studio 2010 . And it ’ s not just extension methods ; I now have to qualify every type with the full namespace , which is really annoying.What ’ s even weirder is that the IntelliSense inside the Watch window acts as if the usings were present . In other words , it does list .ToArray ( ) for example . But then the Watch window displays the error message ' < type > ' does not contain a definition for 'ToArray ' and no extension method 'ToArray ' accepting a first argument of type ' < type > ' could be found ( are you missing a using directive or an assembly reference ? ) So now I always have to type the really long and annoyingHow do I fix this ? <code> using System.Linq ; System.Linq.Enumerable.ToArray ( blah ) | Watch window stopped accepting some usings |
C_sharp : The following code does n't compile ( error CS0123 : No overload for 'System.Convert.ToString ( object ) ' matches delegate 'System.Converter < T , string > ' ) : however , this does : In c # 4 , co/contra-variant delegates can be assigned to each other , and delegates can be created from co/contra-variant methods , so the ToString ( object ) method can be used as a Converter < T , string > , as T is always guarenteed to be convertable to an object.So , the first example ( method group overload resolution ) should be finding the only applicable method string Convert.ToString ( object o ) , the same as the method call overload resolution . Why is the method group & method call overload resolution producing different results ? <code> class A < T > { void Method ( T obj ) { Converter < T , string > toString = Convert.ToString ; // this does n't work either ( on .NET 4 ) : Converter < object , string > toString2 = Convert.ToString ; Converter < T , string > toString3 = toString2 ; } } class A < T > { void Method ( T obj ) { // o is a T , and Convert.ToString ( o ) is using // string Convert.ToString ( object o ) Converter < T , string > toString = o = > Convert.ToString ( o ) ; } } | How is method group overload resolution different to method call overload resolution ? |
C_sharp : I have csv file with 30 000 lines . I have to select many values based on many conditions , so insted of many loops and `` if 's '' i decided to use linq . I have written class to read csv . It implements IEnumerable to be used with linq . This is my enumerator : It 's working , but it 's slow . Let 's say i want to select max value in column A in range 100 ; 150 row.This will work , but linq searches for max value in 30 000 rows instead of 48.As I said , I could use loop , but only in this example case , conditions are `` brutal '' : ) Is there any way to override linq collection search . Something like : look into query used on my enumerator , look , if any linq conditions in `` where '' contains `` row ID filter '' and give another data based on this . I do n't want to copy part of data to another array/collection and problem is not in my csv reader . Accessing every row by id is fast , only problem is when you access all 30 000 of them . Any help appriciated : - ) <code> class CSVEnumerator : IEnumerator { private CSVReader _csv ; private int _index ; public CSVEnumerator ( CSVReader csv ) { _csv = csv ; _index = -1 ; } public void Reset ( ) { _index = -1 ; } public object Current { get { return new CSVRow ( _index , _csv ) ; } } public bool MoveNext ( ) { return ++_index < _csv.TotalRows ; } } max = ( from CSVRow r in csv where r.ID > 100 & & r.ID < 150 select r ) .Max ( y= > y [ `` A '' ] ) ; | Is possible to change search method in LINQ ? |
C_sharp : When im passing Bmp as stream , function always return , but file saving on disk correctly.When I load bpm from disk , function return correct MD5 . Also passing `` new Bitmap ( int x , int y ) ; '' with different value return same MD5.Why its happening ? Can somebody explain this strange behaviour ? <code> D4-1D-8C-D9-8F-00-B2-04-E9-80-09-98-EC-F8-42-7E public static string GetMD5Hash ( ) { Bitmap Bmp = new Bitmap ( 23 , 46 ) ; // using ( Graphics gfx = Graphics.FromImage ( Bmp ) ) using ( SolidBrush brush = new SolidBrush ( Color.FromArgb ( 32 , 44 , 2 ) ) ) { gfx.FillRectangle ( brush , 0 , 0 , 23 , 46 ) ; } using ( var md5 = MD5.Create ( ) ) { using ( MemoryStream memoryStream = new MemoryStream ( ) ) { Bmp.Save ( memoryStream , System.Drawing.Imaging.ImageFormat.Bmp ) ; \//EDITED : Bmp.Save ( @ '' C : \Test\pizdanadysku.bmp '' ) ; // Here saving file on disk , im getting diffrent solid color return BitConverter.ToString ( md5.ComputeHash ( memoryStream ) ) ; //Always return D4-1D-8C-D9-8F-00-B2-04-E9-80-09-98-EC-F8-42-7E - I noticed that is MD5 of empty 1x1px Bmp file } } } | Problem with counting MD5 from bitmap stream C # |
C_sharp : I 've got the following situation : There are two related types . For this question , I 'll use the following simple types : So that one Person might have multiple Accounts ( i.e. , multiple Accounts would reference the same PersonId ) .In our database , there are tens of thousands of persons , and each have 5-10 accounts on average.I need to retrieve each person 's accounts , assuming they fulfill certain requirements . Afterwards , I need to see if all of this person 's accounts , together , fulfill another condition.In this example , let 's say I need every account with amount < 100 , and that after retrieving one person 's accounts , I need to check if their sum is larger than 1000 . Using a LINQ query is desirable , but ca n't be done using group-by-into keywords , because the Linq-Provider ( LINQ-to-CRM ) does n't support it . In addition , doing the following simple LINQ query to implement listing 3 requirements is also not possible ( please read the inlined comment ) : It is not possible for 2 reasons : a . The Linq-Provider force a call to ToList ( ) before using GroupBy ( ) . b . Trying to actually call ToList ( ) before using GroupBy ( ) results in an out-of-memory exception - since there are tens of thousands of accounts . For efficiency reasons , I do n't want to do the following , since it means tens of thousands retrievals : a. Retrieve all persons.b . Loop through them and retrieve each person 's accounts on each iteration.Will be glad for efficient ideas . <code> public class Person { public Guid Id { get ; set ; } public int status { get ; set ; } } public class Account { public Guid AccountId { get ; set ; } public decimal Amount { get ; set ; } public Guid PersonId { get ; set ; } } var query = from p in personList join a in accountList on p.Id equals a.PersonId where a.Amount < 100 select a ; var groups = query.GroupBy ( a = > a.PersonId ) ; // and now , run in bulks on x groups // ( let x be the groups amount that wo n't cause an out-of-memory exception ) | Retrieving large amount of records under multiple limitations , without causing an out-of-memory exception |
C_sharp : Suppose I have the following : In what situation ( s ) would there be an advantage to using MyClassB over MyClassA ? <code> public class MyElement { } [ Serializable ] [ StructLayout ( LayoutKind.Sequential ) ] struct ArrayElement { internal MyElement Element ; } public class MyClass { internal MyElement ComputeElement ( int index ) { // This method does a lengthy computation . // The actual return value is not so simple . return new MyElement ( ) ; } internal MyElement GetChild ( ref MyElement element , int index ) { if ( element ! = null ) { return element ; } var elem = ComputeElement ( index ) ; if ( Interlocked.CompareExchange ( ref element , elem , null ) ! = null ) { elem = element ; } return elem ; } } public class MyClassA : MyClass { readonly MyElement [ ] children = new MyElement [ 10 ] ; public MyElement GetChild ( int index ) { return GetChild ( ref children [ index ] , index ) ; } } public class MyClassB : MyClass { readonly ArrayElement [ ] children = new ArrayElement [ 10 ] ; public MyElement GetChild ( int index ) { return GetChild ( ref children [ index ] .Element , index ) ; } } | When to use an array of a value type containing a reference types over an array of a reference type ? |
C_sharp : Given the following C # code : The question is : what is causing the type of i to be correctly inferred as an int ? This is not at all obviuous , as array2D is a rectangular array . It does not implement IEnumerable < int > . It also implements a GetEnumerator ( ) method , which returns a System.Collections.IEnumerator . I would therefore expect that i would be of type object . My code is using .net 4.03 . Related SO question : Why do C # Multidimensional arrays not implement IEnumerable ? . <code> int [ , ] array2D = new int [ 10 , 10 ] ; int sum = 0 ; foreach ( var i in array2D ) { sum += i ; } | Why does foreach ( var i in array2D ) work on multidimensional arrays ? |
C_sharp : is it possible to differ the variable I 'm assigning to depending on a condition ? The issue I came across is wanting to do this : Instead ofWhich results in the following error Error CS0131 The left-hand side of an assignment must be a variable , property or indexerSo I was wondering if there was a way to do this to cut down on space used and - in my opinion - make it look a bit neater ? <code> ( bEquipAsSecondary ? currentWeaponOffhand : currentWeaponMainhand ) = weaponToSwitchTo ; if ( bEquipAsSecondary ) { currentWeaponOffhand = weaponToSwitchTo ; } else { currentWeaponMainhand = weaponToSwitchTo ; } | Is there a way to use a ternary operator - or similar method - for picking the variable to assign to ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.