text
stringlengths
46
37.3k
title
stringlengths
12
162
C_sharp : I am trying to add unit-tests for my code where I am using Task from TPL to update values into a database . For unit-test , I am using NUnit and Moq . Here are some code snippets from my project.This is working . But when I add ContinueWith with the service method call like this ... this test code is not working.Test is failed and it shows this error ... System.NullReferenceException : Object reference not set to an instance of an objectStacktrace : atPresenters.UnitTests.DeviceCategoryPresenterTest.InitializeView_Called ( ) [ 0x00241 ] in DeviceCategoryPresenterTest.cs:56 at ( wrapper managed-to-native ) System.Reflection.MonoMethod : InternalInvoke ( System.Reflection.MonoMethod , object , object [ ] , System.Exception & ) at System.Reflection.MonoMethod.Invoke ( System.Object obj , System.Reflection.BindingFlags invokeAttr , System.Reflection.Binder binder , System.Object [ ] parameters , System.Globalization.CultureInfo culture ) [ 0x00038 ] in /private/tmp/source-mono-4.8.0/bockbuild-mono-4.8.0-branch/profiles/mono-mac-xamarin/build-root/mono-x86/mcs/class/corlib/System.Reflection/MonoMethod.cs:305and I am not sure how can I fix it . Please help . Thanks in advance . <code> *//service*public interface IServiceFacade { Task SynchronizeDataset ( string datasetName ) ; } *//The method call I want to test*_ServiceFacade.SynchronizeDataset ( DATASET_NAME ) ; *//In my test , I want to verify if this method is called*mock_IServicesFacade.Setup ( sf = > sf.SynchronizeDataset ( It.IsAny < string > ( ) ) ) .Returns ( It.IsAny < Task > ( ) ) ; presenter.InitializeView ( ) ; mock_IServicesFacade.Verify ( sf = > sf.SynchronizeDataset ( NSUserUtilStrings.DATASET_ACHIEVEMENT ) , Times.Once ( ) ) ; _ServiceFacade.SynchronizeDataset ( DATASET_NAME ) .ContinueWith ( t = > { if ( t.IsFaulted ) { //do something } } ) ;
Unit test is failing when ContinueWith is used with System.Threading.Tasks.Task
C_sharp : This has been driving me nuts all day , as I 've made no changes yet I swear this was working the way I had intended yesterday.I have a WCF 4 REST service defined with the following contract : I also have the following types defined : Yesterday I swear I was able to submit POST data of this form : Today that same batch of XML is causing HTTP 400 errors with the following message : The only XML that seems to work today is the below , and I really really dislike the necessity of adding a namespace plus attribute to describe the subtype of my child DataContract.Does anyone have any ideas as to what I might have touched or what I might need to change in order to get back to the prior simple XML format for deserialization ? Any help would be much appreciated . Thanks ! <code> [ ServiceContract ] public interface IPhoneFeaturesManagementHost { [ OperationContract ] [ WebInvoke ( Method = `` POST '' , UriTemplate = `` /accounts/ { accountNumber } /phoneNumbers/ { phoneNumber } /features/ { featureType } '' , RequestFormat = WebMessageFormat.Xml , ResponseFormat = WebMessageFormat.Xml , BodyStyle = WebMessageBodyStyle.Bare ) ] void UpdateFeatureStatus ( string accountNumber , string phoneNumber , string featureType , FeatureUpdateRequest updateRequest ) ; } [ DataContract ] [ KnownType ( typeof ( One900FeatureUpdateRequest ) ) ] public abstract class FeatureUpdateRequest { [ DataMember ] public FeatureStatus Status { get ; set ; } [ DataMember ] public DateTime EffectiveDate { get ; set ; } public string AccountNumber { get ; set ; } public string PhoneNumber { get ; set ; } public string UserId { get ; set ; } public DateTime Timestamp { get ; set ; } public override string ToString ( ) { return String.Format ( `` Status : { 0 } , Effective Date : { 1 } '' , Status , EffectiveDate ) ; } } [ DataContract ] public class One900FeatureUpdateRequest : FeatureUpdateRequest { [ DataMember ] public bool PerformSwitchUpdate { get ; set ; } } < One900FeatureUpdateRequest > < EffectiveDate > 1999-05-31T11:20:00 < /EffectiveDate > < Status > Enabled < /Status > < PerformSwitchUpdate > true < /PerformSwitchUpdate > < /One900FeatureUpdateRequest > Unable to deserialize XML body with root name 'One900FeatureUpdateRequest ' and root namespace `` ( for operation 'UpdateFeatureStatus ' and contract ( 'IPhoneFeaturesManagementHost ' , 'http : //tempuri.org/ ' ) ) using DataContractSerializer . Ensure that the type corresponding to the XML is added to the known types collection of the service . < FeatureUpdateRequest i : type= '' One900FeatureUpdateRequest '' xmlns : i= '' http : //www.w3.org/2001/XMLSchema-instance '' xmlns= '' http : //schemas.datacontract.org/2004/07/Project.Services.Host '' > < EffectiveDate > 1999-05-31T11:20:00 < /EffectiveDate > < Status > Enabled < /Status > < PerformSwitchUpdate > true < /PerformSwitchUpdate > < /FeatureUpdateRequest >
REST with Polymorphic DataContracts - Deserialization Fails
C_sharp : Below is an implementation of ForEachAsync written by Stephen ToubWhat factors should be considered when specifying a partitionCount ( dop in this case ) ? Does the hardware make a difference ( # of cores , available RAM , etc ) ? Does the type of data/operation influence the count ? My first guess would be to set dop equal to Environment.ProcessorCount for general cases , but my gut tells me that 's probably unrelated . <code> public static Task ForEachAsync < T > ( this IEnumerable < T > source , int dop , Func < T , Task > body ) { return Task.WhenAll ( from partition in Partitioner.Create ( source ) .GetPartitions ( dop ) select Task.Run ( async delegate { using ( partition ) while ( partition.MoveNext ( ) ) await body ( partition.Current ) ; } ) ) ; }
Factors for determining partitionCount for C # Partitioner.GetPartitions ( )
C_sharp : I am trying to do a comparison of a MySqlDateTime object to another MySqlDateTime object , each from two different tables . I am trying to do all of this inside a LINQ query , ex : This gives me a compiler error : Operator '== ' can not be applied to operands of type 'MySql.Data.Types.MySqlDateTime ' and 'MySql.Data.Types.MySqlDateTime'So then I try this : Now it compiles , but I get a run-time error : Specified cast is not valid.Stack Trace : Another example I have tried : Still raises a run-time error : Specified cast is not valid.Another example : Same run-time error : Specified cast is not valid.Somebody said something about `` date '' not being a MySqlDateTime type , for fun , here 's the proof that it is : Run-time exception : Unable to cast object of type 'MySql.Data.Types.MySqlDateTime ' to type 'System.String'.I have tried a few other things and nothing works for me.Any help would be greatly appreciated , Regards , Kyle <code> var prodRowFindQuery = from x in production.AsEnumerable ( ) where x.Field < MySqlDateTime > ( `` date '' ) == row.Field < MySqlDateTime > ( `` date '' ) & & x.Field < String > ( `` device_id3 '' ) == row.Field < String > ( `` device_id3 '' ) select x ; var prodRowFindQuery = from x in production.AsEnumerable ( ) where x.Field < MySqlDateTime > ( `` date '' ) .ToString ( ) == row.Field < MySqlDateTime > ( `` date '' ) .ToString ( ) & & x.Field < String > ( `` device_id3 '' ) == row.Field < String > ( `` device_id3 '' ) select x ; IthacaDbTransferUtil.exe ! IthacaDbTransferUtil.DataTableComparer.CompareTables.AnonymousMethod__0 ( System.Data.DataRow x = { System.Data.DataRow } ) Line 34 C # System.Core.dll ! System.Linq.Enumerable.WhereEnumerableIterator < System.Data.DataRow > .MoveNext ( ) + 0x9c bytes IthacaDbTransferUtil.exe ! IthacaDbTransferUtil.DataTableComparer.CompareTables ( System.Data.DataTable aggregate = { System.Data.DataTable } , System.Data.DataTable production = { System.Data.DataTable } ) Line 39 + 0x8b bytes C # IthacaDbTransferUtil.exe ! IthacaDbTransferUtil.DbTransferWindowViewModel.CopyTestReliability ( ) Line 177 + 0x94 bytes C # IthacaDbTransferUtil.exe ! IthacaDbTransferUtil.DelegateCommand.Execute ( ) Line 78 + 0x1f bytes C # IthacaDbTransferUtil.exe ! IthacaDbTransferUtil.DelegateCommand.System.Windows.Input.ICommand.Execute ( object parameter = null ) Line 158 + 0xa bytes C # PresentationFramework.dll ! System.Windows.Controls.Button.OnClick ( ) + 0xaf bytes PresentationFramework.dll ! System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp ( System.Windows.Input.MouseButtonEventArgs e ) + 0x117 bytes PresentationCore.dll ! System.Windows.RoutedEventArgs.InvokeHandler ( System.Delegate handler , object target ) + 0x56 bytes PresentationCore.dll ! System.Windows.EventRoute.InvokeHandlersImpl ( object source , System.Windows.RoutedEventArgs args , bool reRaised ) + 0x270 bytes PresentationCore.dll ! System.Windows.UIElement.ReRaiseEventAs ( System.Windows.DependencyObject sender = { System.Windows.Controls.Button } , System.Windows.RoutedEventArgs args = { System.Windows.Input.MouseButtonEventArgs } , System.Windows.RoutedEvent newEvent ) + 0x183 bytes PresentationCore.dll ! System.Windows.RoutedEventArgs.InvokeHandler ( System.Delegate handler , object target ) + 0x56 bytes PresentationCore.dll ! System.Windows.EventRoute.InvokeHandlersImpl ( object source , System.Windows.RoutedEventArgs args , bool reRaised ) + 0x270 bytes PresentationCore.dll ! System.Windows.UIElement.RaiseEventImpl ( System.Windows.DependencyObject sender = { System.Windows.Controls.Button } , System.Windows.RoutedEventArgs args = { System.Windows.Input.MouseButtonEventArgs } ) + 0x14e bytes PresentationCore.dll ! System.Windows.UIElement.RaiseTrustedEvent ( System.Windows.RoutedEventArgs args = { System.Windows.Input.MouseButtonEventArgs } ) + 0x64 bytes PresentationCore.dll ! System.Windows.Input.InputManager.ProcessStagingArea ( ) + 0x431 bytes PresentationCore.dll ! System.Windows.Input.InputProviderSite.ReportInput ( System.Windows.Input.InputReport inputReport ) + 0xfd bytes PresentationCore.dll ! System.Windows.Interop.HwndMouseInputProvider.ReportInput ( System.IntPtr hwnd , System.Windows.Input.InputMode mode , int timestamp , System.Windows.Input.RawMouseActions actions , int x , int y , int wheel ) + 0x410 bytes PresentationCore.dll ! System.Windows.Interop.HwndMouseInputProvider.FilterMessage ( System.IntPtr hwnd = 396436 , MS.Internal.Interop.WindowMessage msg = WM_LBUTTONUP , System.IntPtr wParam = 0 , System.IntPtr lParam = 34472260 , ref bool handled = false ) + 0x388 bytes PresentationCore.dll ! System.Windows.Interop.HwndSource.InputFilterMessage ( System.IntPtr hwnd , int msg , System.IntPtr wParam , System.IntPtr lParam , ref bool handled ) + 0x7c bytes WindowsBase.dll ! MS.Win32.HwndWrapper.WndProc ( System.IntPtr hwnd , int msg , System.IntPtr wParam , System.IntPtr lParam , ref bool handled ) + 0x14a bytes WindowsBase.dll ! MS.Win32.HwndSubclass.DispatcherCallbackOperation ( object o ) + 0x80 bytes WindowsBase.dll ! System.Windows.Threading.ExceptionWrapper.InternalRealCall ( System.Delegate callback , object args , int numArgs ) + 0x5e bytes WindowsBase.dll ! MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen ( object source = { System.Windows.Threading.Dispatcher } , System.Delegate method , object args , int numArgs , System.Delegate catchHandler = null ) + 0x47 bytes WindowsBase.dll ! System.Windows.Threading.Dispatcher.LegacyInvokeImpl ( System.Windows.Threading.DispatcherPriority priority , System.TimeSpan timeout , System.Delegate method , object args , int numArgs ) + 0x2bc bytes WindowsBase.dll ! MS.Win32.HwndSubclass.SubclassWndProc ( System.IntPtr hwnd , int msg , System.IntPtr wParam , System.IntPtr lParam ) + 0x140 bytes [ Native to Managed Transition ] [ Managed to Native Transition ] WindowsBase.dll ! System.Windows.Threading.Dispatcher.PushFrameImpl ( System.Windows.Threading.DispatcherFrame frame ) + 0x112 bytes PresentationFramework.dll ! System.Windows.Application.RunInternal ( System.Windows.Window window ) + 0x17a bytes PresentationFramework.dll ! System.Windows.Application.Run ( ) + 0x67 bytes IthacaDbTransferUtil.exe ! IthacaDbTransferUtil.App.Main ( ) + 0x77 bytes C # [ Native to Managed Transition ] [ Managed to Native Transition ] Microsoft.VisualStudio.HostingProcess.Utilities.dll ! Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly ( ) + 0x5a bytes mscorlib.dll ! System.Threading.ExecutionContext.RunInternal ( System.Threading.ExecutionContext executionContext , System.Threading.ContextCallback callback , object state , bool preserveSyncCtx ) + 0x285 bytes mscorlib.dll ! System.Threading.ExecutionContext.Run ( System.Threading.ExecutionContext executionContext , System.Threading.ContextCallback callback , object state , bool preserveSyncCtx ) + 0x9 bytes mscorlib.dll ! System.Threading.ExecutionContext.Run ( System.Threading.ExecutionContext executionContext , System.Threading.ContextCallback callback , object state ) + 0x57 bytes mscorlib.dll ! System.Threading.ThreadHelper.ThreadStart ( ) + 0x51 bytes [ Native to Managed Transition ] var prodRowFindQuery = from x in production.AsEnumerable ( ) where Convert.ToDateTime ( x.Field < MySqlDateTime > ( `` date '' ) ) == Convert.ToDateTime ( row.Field < MySqlDateTime > ( `` date '' ) ) & & x.Field < String > ( `` device_id3 '' ) == row.Field < String > ( `` device_id3 '' ) select x ; var prodRowFindQuery = from x in production.AsEnumerable ( ) where x.Field < DateTime > ( `` date '' ) == row.Field < DateTime > ( `` date '' ) & & x.Field < String > ( `` device_id3 '' ) == row.Field < String > ( `` device_id3 '' ) select x ; var prodRowFindQuery = from x in production.AsEnumerable ( ) where x.Field < String > ( `` date '' ) == row.Field < String > ( `` date '' ) & & x.Field < String > ( `` device_id3 '' ) == row.Field < String > ( `` device_id3 '' ) select x ;
MySqlDateTime in LINQ Query
C_sharp : I 'm not sure if there is a pattern that should be used here but here is the situation : I have a number of concrete classes that implement an interface : I have another class that checks input to determine if ShouldPerformAction should be execute . The rub is that new checks are added fairly frequently . The interface for the checking class is defined as follows : Finally I currently have the concrete classes call each of the checker methods with the data specific to that concrete class : Now each time I add a new check , I have to refactor the concrete classes to include the new check . Each concrete class passes different properties to the checking method so subclasses the concrete classes is not an option . Any ideas on how this could be implemented in a cleaner manner ? <code> public interface IPerformAction { bool ShouldPerformAction ( ) ; void PerformAction ( ) ; } public interface IShouldPerformActionChecker { bool CheckA ( string a ) ; bool CheckB ( string b ) ; bool CheckC ( int c ) ; // etc ... } public class ConcreteClass : IPerformAction { public IShouldPerformActionCheck ShouldPerformActionChecker { get ; set ; } public string Property1 { get ; set ; } public string Property2 { get ; set ; } public int Property3 { get ; set ; } public bool ShouldPerformAction ( ) { return ShouldPerformActionChecker.CheckA ( this.Property1 ) || ShouldPerformActionChecker.CheckB ( this.Property2 ) || ShouldPerformActionChecker.CheckC ( this.Property3 ) ; } public void PerformAction ( ) { // do something class specific } }
Design pattern question for maintainability
C_sharp : The code below works fine , just wondering if there 's a more elegant way of achieving the same thing ? The dates below should be valid , anything other than that should not:1/12/20171/12/2017 11:101/12/2017 11:10:3015/5/201715/5/2017 11:1015/5/2017 11:10:301/5/20171/5/2017 11:101/5/2017 11:10:3025/12/201725/12/2017 11:1025/12/2017 11:10:30In other words : it should work with 1 and 2 digits days/months , and it should work with and without time , including or not seconds . <code> var validDateTimeFormats = new [ ] { `` d/MM/yyyy '' , `` d/MM/yyyy HH : mm '' , `` d/MM/yyyy HH : mm : ss '' , `` dd/M/yyyy '' , `` dd/M/yyyy HH : mm '' , `` dd/M/yyyy HH : mm : ss '' , `` d/M/yyyy '' , `` d/M/yyyy HH : mm '' , `` d/M/yyyy HH : mm : ss '' , `` dd/MM/yyyy '' , `` dd/MM/yyyy HH : mm '' , `` dd/MM/yyyy HH : mm : ss '' } ; DateTime dateTime ; if ( DateTime.TryParseExact ( dateTimeStr , validDateTimeFormats , CultureInfo.InvariantCulture , DateTimeStyles.None , out dateTime ) ) { // My logic }
C # DateTime.TryParseExact with optional parameters
C_sharp : Consider the following code : By running this code , we are able to change the contents of a string without an exception occuring . We did not have to declare any unsafe code to do so . This code is clearly very dodgy ! My question is simply this : Do you think that an exception should be thrown by the code above ? [ EDIT1 : Note that other people have tried this for me , and some people get different results - which is n't too suprising given the nastyness of what I 'm doing ... ; ) ] [ EDIT2 : Note that I 'm using Visual Studio 2010 on Windows 7 Ultimate 64 bit ] [ EDIT3 : Made the test string const , just to make it even more dodgy ! ] <code> using System ; using System.Runtime.InteropServices ; namespace Demo { class Program { static void Main ( string [ ] args ) { const string test = `` ABCDEF '' ; // Strings are immutable , right ? char [ ] chars = new StringToChar { str=test } .chr ; chars [ 0 ] = ' X ' ; // On an x32 release or debug build or on an x64 debug build , // the following prints `` XBCDEF '' . // On an x64 release build , it prints `` ABXDEF '' . // In both cases , we have changed the contents of 'test ' without using // any 'unsafe ' code ... Console.WriteLine ( test ) ; } } [ StructLayout ( LayoutKind.Explicit ) ] public struct StringToChar { [ FieldOffset ( 0 ) ] public string str ; [ FieldOffset ( 0 ) ] public char [ ] chr ; } }
Should changing the contents of a string like this cause an exception ?
C_sharp : I 'm generating some code via Cecil . The code generates without error , but when I try to load the assembly I get : An unhandled exception of type 'System.InvalidProgramException ' occurred in DataSerializersTest.exe Additional information : Common Language Runtime detected an invalid program.Here is the generated IL : The equivalent C # code looks like this : I 've worked through the IL several times and it makes sense to me . It 's not the same as what the C # compiler produces for the above C # code , but I 'd like to understand what 's wrong with the IL I 've generated . Can anyone tell me ? <code> .method public static class Data.FooData Read ( class [ mscorlib ] System.IO.BinaryReader input ) cil managed { // Method begins at RVA 0x3a58 // Code size 60 ( 0x3c ) .maxstack 3 .locals ( [ 0 ] class Data.FooData , [ 1 ] valuetype [ System.Runtime ] System.Nullable ` 1 < int32 > ) IL_0000 : newobj instance void Data.FooData : :.ctor ( ) IL_0005 : stloc.0 IL_0006 : ldloc.0 IL_0007 : ldarg.0 IL_0008 : callvirt instance bool [ System.IO ] System.IO.BinaryReader : :ReadBoolean ( ) IL_000d : ldc.i4.0 IL_000e : ceq IL_0010 : brtrue.s IL_001f IL_0012 : ldarg.0 IL_0013 : callvirt instance int32 [ System.IO ] System.IO.BinaryReader : :ReadInt32 ( ) IL_0018 : newobj instance void valuetype [ System.Runtime ] System.Nullable ` 1 < int32 > : :.ctor ( ! 0 ) IL_001d : br.s IL_0028 IL_001f : nop IL_0020 : ldloca.s 1 IL_0022 : initobj valuetype [ System.Runtime ] System.Nullable ` 1 < int32 > IL_0028 : nop IL_0029 : callvirt instance void Data.FooData : :set_I ( valuetype [ System.Runtime ] System.Nullable ` 1 < int32 > ) IL_002e : ldloc.0 IL_002f : ldarg.0 IL_0030 : callvirt instance string [ System.IO ] System.IO.BinaryReader : :ReadString ( ) IL_0035 : callvirt instance void Data.FooData : :set_Name ( string ) IL_003a : ldloc.0 IL_003b : ret } // end of method FooDataReader : :Read public static FooData Read ( BinaryReader input ) { var result = new FooData ( ) ; if ( input.ReadBoolean ( ) ) { result.I = input.ReadInt32 ( ) ; } else { result.I = null ; } result.Name = input.ReadString ( ) ; return result ; }
What is wrong with this CIL ?
C_sharp : I have an application where the parent object has a method to perform validations and every child overrides the method to perform extra validations . Something like : I added a new `` IsDisabled '' property that when true the method will not perform any validations.I also want that for every child , if the `` IsDisabled '' property is true , the extra verifications are n't performed . What is the better pattern to use here ? <code> class Parent { virtual void DoValidations ( Delegate addErrorMessage ) { //do some validations } } class Child : Parent { override void DoValidations ( Delegate addErrorMessage ) { base.DoValidations ( addErrorMessage ) ; //the parent method is always called //do some extra validations } } class Parent { boolean IsDisabled ; virtual void DoValidations ( Delegate addErrorMessage ) { if ( IsDisabled ) return ; //do some validations } }
Conditionally block method override
C_sharp : My boss just told me that he learned about fast VB6 algorithms from a book and that the shortest way to write things is not necessarily the fastest ( e.g . builtin methods are sometimes way slower than selfwritten ones because they do all kinds of checking or unicode conversions which might not be necessary in your case ) .Now I wonder , is there a website with info on fast different constructs are in various languages , esp . Java/C # /Python/… ( also C++ but there are so many compilers which probably differ a lot ) .E.g . is there a difference betweenandAnother example : is a = a * 4 maybe compiled to the same code as a < < = 2 ? I could test this myself , of course , writing both then running them 100000 times and comparing the runtime , but I 'd also like to learn about new ways to write things , maybe even things that I had n't considered before . Thanks for your answers ! <code> if ( a ( ) ) b ( ) ; a ( ) & & b ( ) ;
Speed of different constructs in programming languages ( Java/C # /C++/Python/… )
C_sharp : In assigning event handlers to something like a context MenuItem , for instance , there are two acceptable syntaxes : ... and ... I also note that the same appears to apply to this : ... and ... Is there any particular advantage for the second ( explicit ) over the first ? Or is this more of a stylistic question ? <code> MenuItem item = new MenuItem ( `` Open Image '' , btnOpenImage_Click ) ; MenuItem item = new MenuItem ( `` Open Image '' , new EventHandler ( btnOpenImage_Click ) ) ; listView.ItemClick += listView_ItemClick ; listView.ItemClick += new ItemClickEventHandler ( listView_ItemClick ) ;
Is there a benefit to explicit use of `` new EventHandler '' declaration ?
C_sharp : In VB6 there are local static variables that keep their values after the exit of procedure . It 's like using public vars but on local block . For example : After 10 calls , x will be 10 . I tried to search the same thing in .NET ( and even Java ) but there was none . Why ? Does it break the OOP model in some way , and is there a way to emulate that . <code> sub count ( ) static x as integerx = x + 1end sub
VB6 's private static in C # ?
C_sharp : I have the following code ( simplified for posting purposes ) .The idea is that when DoRequest call is made , SomeDataObject will get some data and raise either the Ready or Error events ( details not important ! ) . If data is available , then the ItemCount indicates how many items are available.I am new to Rx and can not find any comparable example . So is it possible to convert this into Rx so that IObservable < string > is returned instead of Task < List < string > > using Observable.Create somehow ? RegardsAlan <code> public class SomeDataObject { public delegate void ReadyEventHandler ; public delegate void ErrorEventHandler ; public event ReadyEventHandler Ready ; public event ErrorEventHandler Error ; ... } pubic class ConsumerClass { private SomeDataObject dataObject ; private Task < List < string > > GetStrings ( ) { List < string > results = new List < string > ( ) ; var tcs = new TaskCompletionSource < List < string > > ( ) ; SomeDataObject.ReadyEventHandler ReadyHandler = null ; SomeDataObject.ErrorEventHandler ErrorHandler = null ; ReadyHandler += ( ) = > { for ( int i =0 ; i < dataObject.ItemCount ; i++ ) results.Add ( dataObject [ i ] .ToString ( ) ) ; tcs.TrySetResult ( results ) ; } ErrorHandler += ( ) { tcs.TrySetException ( new Exception ( `` oops ! `` ) ; } dataObject.Ready += ReadyHandler ; dataObject.Error += ErrorHandler ; dataObject.DoRequest ( ) ; } }
Convert Event based code to Rx
C_sharp : TL ; DR : Why is wrapping the System.Numerics.Vectors type expensive , and is there anything I can do about it ? Consider the following piece of code : This will JIT into ( x64 ) : and x86 : Now , if I wrap this in a struct , e.g.and change GetIt , e.g.the JITted result is still exactly the same as when using the native types directly ( the AddThem , and the SomeWrapper overloaded operator and constructor are all inlined ) . As expected.Now , if I try this with the SIMD-enabled types , e.g . System.Numerics.Vector4 : it is JITted into : However , if I wrap the Vector4 in a struct ( similar to the first example ) : my code is now JITted into a whole lot more : It looks like the JIT has now decided for some reason it ca n't just use the registers , and instead uses temporary variables , but I ca n't understand why . First I thought it might be an alignment issue , but then I ca n't understand why it is first loading both into xmm0 and then deciding to round trip to memory.What is going on here ? And more importantly , can I fix it ? The reason that I would like to wrap the structure like this is that I have a lot of legacy code that uses an API whose implementation would benefit from some SIMD goodness.EDIT : So , after some digging around in the coreclr source , I found out that it is actually nothing special about the System.Numerics classes . I just have to add the System.Numerics.JitIntrinsic attribute to my methods . The JIT will then replace my implementation with its own . JitIntrinsic is private ? No problem , just copy+paste it . The original question still remains though ( even if I now have a workaround ) . <code> [ MethodImpl ( MethodImplOptions.NoInlining ) ] private static long GetIt ( long a , long b ) { var x = AddThem ( a , b ) ; return x ; } private static long AddThem ( long a , long b ) { return a + b ; } 00007FFDA3F94500 lea rax , [ rcx+rdx ] 00007FFDA3F94504 ret 00EB2E20 push ebp 00EB2E21 mov ebp , esp 00EB2E23 mov eax , dword ptr [ ebp+10h ] 00EB2E26 mov edx , dword ptr [ ebp+14h ] 00EB2E29 add eax , dword ptr [ ebp+8 ] 00EB2E2C adc edx , dword ptr [ ebp+0Ch ] 00EB2E2F pop ebp 00EB2E30 ret 10h public struct SomeWrapper { public long X ; public SomeWrapper ( long X ) { this.X = X ; } public static SomeWrapper operator + ( SomeWrapper a , SomeWrapper b ) { return new SomeWrapper ( a.X + b.X ) ; } } private static long GetIt ( long a , long b ) { var x = AddThem ( new SomeWrapper ( a ) , new SomeWrapper ( b ) ) .X ; return x ; } private static SomeWrapper AddThem ( SomeWrapper a , SomeWrapper b ) { return a + b ; } [ MethodImpl ( MethodImplOptions.NoInlining ) ] private static Vector4 GetIt ( Vector4 a , Vector4 b ) { var x = AddThem ( a , b ) ; return x ; } 00007FFDA3F94640 vmovupd xmm0 , xmmword ptr [ rdx ] 00007FFDA3F94645 vmovupd xmm1 , xmmword ptr [ r8 ] 00007FFDA3F9464A vaddps xmm0 , xmm0 , xmm1 00007FFDA3F9464F vmovupd xmmword ptr [ rcx ] , xmm0 00007FFDA3F94654 ret public struct SomeWrapper { public Vector4 X ; [ MethodImpl ( MethodImplOptions.AggressiveInlining ) ] public SomeWrapper ( Vector4 X ) { this.X = X ; } [ MethodImpl ( MethodImplOptions.AggressiveInlining ) ] public static SomeWrapper operator+ ( SomeWrapper a , SomeWrapper b ) { return new SomeWrapper ( a.X + b.X ) ; } } [ MethodImpl ( MethodImplOptions.NoInlining ) ] private static Vector4 GetIt ( Vector4 a , Vector4 b ) { var x = AddThem ( new SomeWrapper ( a ) , new SomeWrapper ( b ) ) .X ; return x ; } 00007FFDA3F84A02 sub rsp,0B8h 00007FFDA3F84A09 mov rsi , rcx 00007FFDA3F84A0C lea rdi , [ rsp+10h ] 00007FFDA3F84A11 mov ecx,1Ch 00007FFDA3F84A16 xor eax , eax 00007FFDA3F84A18 rep stos dword ptr [ rdi ] 00007FFDA3F84A1A mov rcx , rsi 00007FFDA3F84A1D vmovupd xmm0 , xmmword ptr [ rdx ] 00007FFDA3F84A22 vmovupd xmmword ptr [ rsp+60h ] , xmm0 00007FFDA3F84A29 vmovupd xmm0 , xmmword ptr [ rsp+60h ] 00007FFDA3F84A30 lea rax , [ rsp+90h ] 00007FFDA3F84A38 vmovupd xmmword ptr [ rax ] , xmm0 00007FFDA3F84A3D vmovupd xmm0 , xmmword ptr [ r8 ] 00007FFDA3F84A42 vmovupd xmmword ptr [ rsp+50h ] , xmm0 00007FFDA3F84A49 vmovupd xmm0 , xmmword ptr [ rsp+50h ] 00007FFDA3F84A50 lea rax , [ rsp+80h ] 00007FFDA3F84A58 vmovupd xmmword ptr [ rax ] , xmm0 00007FFDA3F84A5D vmovdqu xmm0 , xmmword ptr [ rsp+90h ] 00007FFDA3F84A67 vmovdqu xmmword ptr [ rsp+40h ] , xmm0 00007FFDA3F84A6E vmovdqu xmm0 , xmmword ptr [ rsp+80h ] 00007FFDA3F84A78 vmovdqu xmmword ptr [ rsp+30h ] , xmm0 00007FFDA3F84A7F vmovdqu xmm0 , xmmword ptr [ rsp+40h ] 00007FFDA3F84A86 vmovdqu xmmword ptr [ rsp+20h ] , xmm0 00007FFDA3F84A8D vmovdqu xmm0 , xmmword ptr [ rsp+30h ] 00007FFDA3F84A94 vmovdqu xmmword ptr [ rsp+10h ] , xmm0 00007FFDA3F84A9B vmovups xmm0 , xmmword ptr [ rsp+20h ] 00007FFDA3F84AA2 vmovups xmm1 , xmmword ptr [ rsp+10h ] 00007FFDA3F84AA9 vaddps xmm0 , xmm0 , xmm1 00007FFDA3F84AAE lea rax , [ rsp ] 00007FFDA3F84AB2 vmovupd xmmword ptr [ rax ] , xmm0 00007FFDA3F84AB7 vmovdqu xmm0 , xmmword ptr [ rsp ] 00007FFDA3F84ABD vmovdqu xmmword ptr [ rsp+70h ] , xmm0 00007FFDA3F84AC4 vmovups xmm0 , xmmword ptr [ rsp+70h ] 00007FFDA3F84ACB vmovupd xmmword ptr [ rsp+0A0h ] , xmm0 00007FFDA3F84AD5 vmovupd xmm0 , xmmword ptr [ rsp+0A0h ] 00007FFDA3F84ADF vmovupd xmmword ptr [ rcx ] , xmm0 00007FFDA3F84AE4 add rsp,0B8h 00007FFDA3F84AEB pop rsi 00007FFDA3F84AEC pop rdi 00007FFDA3F84AED ret
Expensive to wrap System.Numerics.VectorX - why ?
C_sharp : I have this bank ATM mock-up app which implements some Domain-Driven Design architecture and Unit of Work pattern . This app have 3 basic functions : Check balanceDepositWithdrawThese are the project layers : ATM.Model ( Domain model entity layer ) ATM.Persistence ( Persistence Layer ) ATM.ApplicationService ( Application layer ) ATM.ConsoleUICoreI could check balance successfully . For option 2 , I can execute `` Deposit '' option without any error . But in the database , my balance balance is not being updated . Transaction is also not added into the db.If I put back context.SaveChanges ( ) ; in UpdateBankAccount method , it works . It returns 1 . But , I use UoW to perform SaveChanges ( ) . The SaveChanges ( ) did executed in UoW Commit method but the database did n't reflect its changes . The UoW Commit method SaveChanges returns 0.Complete code can be found on Github repository . <code> namespace ATM.Model { public class BankAccount { public int Id { get ; set ; } public string AccountName { get ; set ; } public decimal Balance { get ; set ; } public decimal CheckBalance ( ) { return Balance ; } public void Deposit ( int amount ) { // Domain logic Balance += amount ; } public void Withdraw ( int amount ) { // Domain logic //if ( amount > Balance ) // { // throw new Exception ( `` Withdraw amount exceed account balance . `` ) ; // } Balance -= amount ; } } } namespace ATM.Model { public class Transaction { public int Id { get ; set ; } public int BankAccountId { get ; set ; } public DateTime TransactionDateTime { get ; set ; } public TransactionType TransactionType { get ; set ; } public decimal Amount { get ; set ; } } public enum TransactionType { Deposit , Withdraw } } namespace ATM.Persistence.Context { public class AppDbContext : DbContext { protected override void OnConfiguring ( DbContextOptionsBuilder optionsBuilder ) { optionsBuilder.UseSqlServer ( @ '' [ connstring ] '' ) ; } public DbSet < BankAccount > BankAccounts { get ; set ; } public DbSet < Transaction > Transactions { get ; set ; } } } namespace ATM.Persistence.Repository { public class RepositoryBankAccount { public AppDbContext context { get ; } public RepositoryBankAccount ( ) { context = new AppDbContext ( ) ; } public BankAccount FindById ( int bankAccountId ) { return context.BankAccounts.Find ( bankAccountId ) ; } public void AddBankAccount ( BankAccount account ) { context.BankAccounts.Add ( account ) ; } public void UpdateBankAccount ( BankAccount account ) { context.Entry ( account ) .State = EntityState.Modified ; } } } namespace ATM.Persistence.Repository { public class RepositoryTransaction { private readonly AppDbContext context ; public RepositoryTransaction ( ) { context = new AppDbContext ( ) ; } public void AddTransaction ( Transaction transaction ) { context.Transactions.Add ( transaction ) ; } } } namespace ATM.Persistence.UnitOfWork { public class UnitOfWork : IUnitOfWork { private readonly AppDbContext db ; public UnitOfWork ( ) { db = new AppDbContext ( ) ; } private RepositoryBankAccount _BankAccounts ; public RepositoryBankAccount BankAccounts { get { if ( _BankAccounts == null ) { _BankAccounts = new RepositoryBankAccount ( ) ; } return _BankAccounts ; } } private RepositoryTransaction _Transactions ; public RepositoryTransaction Transactions { get { if ( _Transactions == null ) { _Transactions = new RepositoryTransaction ( ) ; } return _Transactions ; } } public void Dispose ( ) { db.Dispose ( ) ; } public int Commit ( ) { return db.SaveChanges ( ) ; } public void Rollback ( ) { db .ChangeTracker .Entries ( ) .ToList ( ) .ForEach ( x = > x.Reload ( ) ) ; } } } namespace ATM.ApplicationService { public class AccountService { private readonly UnitOfWork uow ; public AccountService ( ) { uow = new UnitOfWork ( ) ; } public void DepositAmount ( BankAccount bankAccount , int amount ) { bankAccount.Deposit ( amount ) ; uow.BankAccounts.UpdateBankAccount ( bankAccount ) ; var transaction = new Transaction ( ) { BankAccountId = bankAccount.Id , Amount = amount , TransactionDateTime = DateTime.Now , TransactionType = TransactionType.Deposit } ; uow.Transactions.AddTransaction ( transaction ) ; try { uow.Commit ( ) ; } catch { uow.Rollback ( ) ; } finally { uow.Dispose ( ) ; } } public void WithdrawAmount ( BankAccount bankAccount , int amount ) { bankAccount.Withdraw ( amount ) ; uow.BankAccounts.UpdateBankAccount ( bankAccount ) ; //repoBankAccount.UpdateBankAccount ( bankAccount ) ; var transaction = new Transaction ( ) { BankAccountId = bankAccount.Id , Amount = amount , TransactionDateTime = DateTime.Now , TransactionType = TransactionType.Withdraw } ; uow.Transactions.AddTransaction ( transaction ) ; try { uow.Commit ( ) ; } catch { uow.Rollback ( ) ; } finally { uow.Dispose ( ) ; } } public decimal CheckBalanceAmount ( int bankAccountId ) { BankAccount bankAccount = uow.BankAccounts.FindById ( bankAccountId ) ; return bankAccount.CheckBalance ( ) ; } } } namespace ATM.ConsoleUICore { class Program { static void Main ( ) { AccountService accountService = new AccountService ( ) ; RepositoryBankAccount repoBankAccount = new RepositoryBankAccount ( ) ; var bankAccount = repoBankAccount.FindById ( 2 ) ; Console.WriteLine ( `` 1 . Check balance '' ) ; Console.WriteLine ( `` 2 . Deposit '' ) ; Console.WriteLine ( `` 3 . Withdraw '' ) ; Console.WriteLine ( `` Enter option : `` ) ; string opt = Console.ReadLine ( ) ; switch ( opt ) { case `` 1 '' : Console.WriteLine ( $ '' Your balance is $ { bankAccount.CheckBalance ( ) } '' ) ; break ; case `` 2 '' : // User to input amount . // Data validation to make sure amount is greater than zero . // Pass the input amount to Application layer . accountService.DepositAmount ( bankAccount , 50 ) ; // After getting the operation status from Application service layer . // Print operation status here : Either success or fail Console.WriteLine ( `` Deposit successfully '' ) ; break ; case `` 3 '' : break ; default : break ; } } } }
Why the database data is not being updated but object did and without error ?
C_sharp : In C++ , you can write code like this : But , you ca n't do something like this in C # : Is there any reason why ? I know it could be accomplished through reflection ( generic Add with objects and then run type checking over it all ) , but that 's inefficient and does n't scale well . So , again , why ? <code> template < class T > T Add ( T lhs , T rhs ) { return lhs + rhs ; } public static T Add < T > ( T x , T y ) where T : operator+ { return x + y ; }
Why cant you require operator overloading in generics
C_sharp : My web app currently allows users to upload media one-at-a-time using the following : The media then gets posted to a WebApi controller : Which then does something along the lines of : This is working great for individual uploads , but how do I go about modifying this to support batched uploads of multiple files through a single streaming operation that returns an array of uploaded filenames ? Documentation/examples on this seem sparse . <code> var fd = new FormData ( document.forms [ 0 ] ) ; fd.append ( `` media '' , blob ) ; // blob is the image/video $ .ajax ( { type : `` POST '' , url : '/api/media ' , data : fd } ) [ HttpPost , Route ( `` api/media '' ) ] public async Task < IHttpActionResult > UploadFile ( ) { if ( ! Request.Content.IsMimeMultipartContent ( `` form-data '' ) ) { throw new HttpResponseException ( HttpStatusCode.UnsupportedMediaType ) ; } string mediaPath = await _mediaService.UploadFile ( User.Identity.Name , Request.Content ) ; return Ok ( mediaPath ) ; } public async Task < string > UploadFile ( string username , HttpContent content ) { var storageAccount = new CloudStorageAccount ( new StorageCredentials ( accountName , accountKey ) , true ) ; CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient ( ) ; CloudBlobContainer imagesContainer = blobClient.GetContainerReference ( `` container- '' + user.UserId ) ; var provider = new AzureStorageMultipartFormDataStreamProvider ( imagesContainer ) ; await content.ReadAsMultipartAsync ( provider ) ; var filename = provider.FileData.FirstOrDefault ( ) ? .LocalFileName ; // etc } public class AzureStorageMultipartFormDataStreamProvider : MultipartFormDataStreamProvider { private readonly CloudBlobContainer _blobContainer ; private readonly string [ ] _supportedMimeTypes = { `` images/png '' , `` images/jpeg '' , `` images/jpg '' , `` image/png '' , `` image/jpeg '' , `` image/jpg '' , `` video/webm '' } ; public AzureStorageMultipartFormDataStreamProvider ( CloudBlobContainer blobContainer ) : base ( `` azure '' ) { _blobContainer = blobContainer ; } public override Stream GetStream ( HttpContent parent , HttpContentHeaders headers ) { if ( parent == null ) throw new ArgumentNullException ( nameof ( parent ) ) ; if ( headers == null ) throw new ArgumentNullException ( nameof ( headers ) ) ; if ( ! _supportedMimeTypes.Contains ( headers.ContentType.ToString ( ) .ToLower ( ) ) ) { throw new NotSupportedException ( `` Only jpeg and png are supported '' ) ; } // Generate a new filename for every new blob var fileName = Guid.NewGuid ( ) .ToString ( ) ; CloudBlockBlob blob = _blobContainer.GetBlockBlobReference ( fileName ) ; if ( headers.ContentType ! = null ) { // Set appropriate content type for your uploaded file blob.Properties.ContentType = headers.ContentType.MediaType ; } this.FileData.Add ( new MultipartFileData ( headers , blob.Name ) ) ; return blob.OpenWrite ( ) ; } }
Batched Media Upload to Azure Blob Storage through WebApi
C_sharp : The C # specification ( ECMA-334 and ISO/IEC 23270 ) has a paragraph about the atomicity of reads and writes : 12.5 Atomicity of variable references Reads and writes of the following data types shall be atomic : bool , char , byte , sbyte , short , ushort , uint , int , float , and reference types . In addition , reads and writes of enum types with an underlying type in the previous list shall also be atomic . Reads and writes of other types , including long , ulong , double , and decimal , as well as user-defined types , need not be atomic.But I have a hard time imagining that to be always true . For example , I can layout a struct using the StructLayout attribute , and force the fields to be unaligned : Now when I do this , I would think the write to the int is not atomic , since it is not aligned to the natural boundary : So , is it definitely atomic ( like the specification says ) , or is it not guaranteed to be atomic ( e.g . on x86 ) ? Either way , do you have any sources to back this up ? <code> // sizeof ( MyStruct ) == 9 [ StructLayout ( LayoutKind.Sequential , Pack = 1 ) ] struct MyStruct { public byte pad ; // Offset : 0 public int value1 ; // Offset : 1 public int value2 ; // Offset : 5 } MyStruct myStruct = new MyStruct ( ) ; myStruct.value1 = 20 ;
Are reads and writes to unaligned fields in .NET definitely atomic ?
C_sharp : Ok this looks like a major fundamental bug in .NET : Consider the following simple program , which purposely tries to connect to a non-existent database : Run this program and set breakpoints on the catch blocks . The DBConnection object will attempt to connect for 15 seconds ( on both threads ) , then it will throw an error . Inspect the exception 's stack trace , and the stack trace will have TWO call stacks intermingled , as follows : You may have to try it several times to get this to happen , but I 'm getting this to happen right now on my machine . How is this possible ? This should be totally impossible at the VM level . It looks like the DBConnection.Open ( ) function is simultaneously throwing the same exception on two threads at once , or something bizarre like that . <code> class Program { static void Main ( string [ ] args ) { Thread threadOne = new Thread ( GetConnectionOne ) ; Thread threadTwo = new Thread ( GetConnectionTwo ) ; threadOne.Start ( ) ; threadTwo.Start ( ) ; } static void GetConnectionOne ( ) { try { using ( SqlConnection conn = new SqlConnection ( `` Data Source=.\\wfea ; Initial Catalog=zc ; Persist Security Info=True ; Trusted_Connection=yes ; '' ) ) { conn.Open ( ) ; } } catch ( Exception e ) { File.AppendAllText ( `` ConnectionOneError.txt '' , e.Message + `` \n '' + e.StackTrace + `` \n '' ) ; } } static void GetConnectionTwo ( ) { try { using ( SqlConnection conn = new SqlConnection ( `` Data Source=.\\wfea ; Initial Catalog=zc ; Persist Security Info=True ; Trusted_Connection=yes ; '' ) ) { conn.Open ( ) ; } } catch ( Exception e ) { File.AppendAllText ( `` ConnectionTwoError.txt '' , e.Message + `` \n '' + e.StackTrace + `` \n '' ) ; } } } at System.Data.ProviderBase.DbConnectionPool.CreateObject ( DbConnection owningObject ) at System.Data.ProviderBase.DbConnectionFactory.GetConnection ( DbConnection owningConnection ) at System.Data.ProviderBase.DbConnectionClosed.OpenConnection ( DbConnection outerConnection , DbConnectionFactory connectionFactory ) at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest ( DbConnection owningObject ) at System.Data.ProviderBase.DbConnectionPool.GetConnection ( DbConnection owningObject ) at System.Data.SqlClient.SqlConnection.Open ( ) at ZoCom2Test.Program.GetConnectionOne ( ) in C : \src\trunk\ZTest\Program.cs : line 38at System.Data.ProviderBase.DbConnectionFactory.GetConnection ( DbConnection owningConnection ) at System.Data.ProviderBase.DbConnectionClosed.OpenConnection ( DbConnection outerConnection , DbConnectionFactory connectionFactory ) at System.Data.SqlClient.SqlConnection.Open ( ) at ZoCom2Test.Program.GetConnectionTwo ( ) in C : \src\trunk\ZTest\Program.cs : line 54
Connection Pool returns Same Exception Instance to Two Threads Using the Same Bad Connection String ?
C_sharp : I have declared the following Enum : and i want to retrieve the enum object from is value : Call Examples : I would also like to use linq or lambda , only if they can give better or equals performance . <code> public enum AfpRecordId { BRG = 0xD3A8C6 , ERG = 0xD3A9C6 } private AfpRecordId GetAfpRecordId ( byte [ ] data ) { ... } byte [ ] tempData = new byte { 0xD3 , 0xA8 , 0xC6 } ; AfpRecordId tempId = GetAfpRecordId ( tempData ) ; //tempId should be equals to AfpRecordId.BRG
Get Enum name based on the Enum value
C_sharp : Small background : I 'm the only programmer for this company . I 'm working with pre-existing frameworks.That said , the company has a dll ( Database.dll ) which contains `` all the database interactions I need '' . As in , it has a Query ( ) , Update ( ) , Insert ( ) , etc . Now , the project I 'm writing sets a reference to Database.dll . My project accepts zero user input . The closest thing to user input is a dropdown box that the user can select a date from . Not having much experience with it , I 'm curious if I still need to worry about SQL injections ? And if so , would a query written likebe sufficient as a parameterized query ? Keep in mind , all of the query execution is handled by the pre-existing Query ( ) that I 'm told I have to use , and ca n't edit . EDITThis program is a WinForm application . <code> var query = string.Format ( `` SELECT timestamp FROM table1 WHERE date = \ '' { 0 } \ '' AND measured_dist = bit_loc AND rop > 0 '' , Date ) )
When to worry about SQL injection protection
C_sharp : I have some logic for Task and Task < T > . Is there any way to avoid duplicating code ? My current code is following : <code> public async Task < SocialNetworkUserInfo > GetMe ( ) { return await WrapException ( ( ) = > new SocialNetworkUserInfo ( ) ) ; } public async Task AuthenticateAsync ( ) { await WrapException ( ( ) = > _facebook.Authenticate ( ) ) ; } public async Task < T > WrapException < T > ( Func < Task < T > > task ) { try { return await task ( ) ; } catch ( FacebookNoInternetException ex ) { throw new NoResponseException ( ex.Message , ex , true ) ; } catch ( FacebookException ex ) { throw new SocialNetworkException ( `` Social network call failed '' , ex ) ; } } public async Task WrapException ( Func < Task > task ) { try { await task ( ) ; } catch ( FacebookNoInternetException ex ) { throw new NoResponseException ( ex.Message , ex , true ) ; } catch ( FacebookException ex ) { throw new SocialNetworkException ( `` Social network call failed '' , ex ) ; } }
Avoiding duplicate methods for Task and Task < T >
C_sharp : I have : A structA class containing the structWhen I now instantiate my class , I assume that the struct lives on the heap.If I now do something likewill it be passed as value ? If not , is there any reason not to make the struct into a class instead ? <code> struct Data { int a ; int b ; } class Packet { Data DataStruct ; } SomeClass.Process ( new Packet ( ) .DataStruct ) ; SomeClass.Process ( new Packet ( ) .DataStruct.a ) ;
Are structs within classes passed as value ?
C_sharp : I 'm going to preface this question with the statement : I know the following is bad design , but refactoring is not currently an option , ideally it should be done using interceptors.I am working on upgrading castle from 1.6 ( I think ) to 3.3 which unfortunately involves some syntax changes , I 've got everything compiling now but some of my tests around the service container are n't working.I have a repository that has several implementations to provide different functionality , the repository is only ever used with all of the different implementations inline , here are the basics of the code : The Castle Windsor registrations : The RepositoryRegistration method : The base interface : The implementations : And finally here is the error I 'm getting in my test : Castle.MicroKernel.Handlers.HandlerException : Ca n't create component 'AccountRepositoryFeedEntryDecorator ' as it has dependencies to be satisfied . 'AccountRepositoryFeedEntryDecorator ' is waiting for the following dependencies : - Component 'Shaw.Services.CustomerManagement.Host.Repositories.Sql.Decorators.AccountRepositoryAuthorizationDecorator ' ( via override ) which was registered but is also waiting for dependencies . 'Shaw.Services.CustomerManagement.Host.Repositories.Sql.Decorators.AccountRepositoryAuthorizationDecorator ' is waiting for the following dependencies : - Service 'AccountRepositoryFeedEntryDecorator ' which was registered but is also waiting for dependencies.At first glance it appears there is some kind of circular dependency happening , but I ca n't really see how . So the question in two parts , what is the difference between the component and service dependency specifications in the error message , any guesses as to what is going wrong.If it matters here is the original registration before the upgrade : <code> RepositoryRegistration < IAccountRepository , AccountRepositoryFeedEntryDecorator > ( ) .DependsOn ( Dependency.OnComponent ( `` decoratedRepository '' , typeof ( AccountRepositoryAuthorizationDecorator ) ) ) , RepositoryRegistration < AccountRepositoryAuthorizationDecorator > ( ) .DependsOn ( Dependency.OnComponent ( `` decoratedRepository '' , typeof ( AccountRepositoryMaskingDecorator ) ) ) , RepositoryRegistration < AccountRepositoryMaskingDecorator > ( ) .DependsOn ( Dependency.OnComponent ( `` decoratedRepository '' , typeof ( AccountRepository ) ) ) , RepositoryRegistration < AccountRepository > ( ) ) ; private static ComponentRegistration < TRepository > RepositoryRegistration < TRepository , TConcreteRepository > ( ) where TConcreteRepository : TRepository where TRepository : class { return Component .For < TRepository > ( ) .ImplementedBy < TConcreteRepository > ( ) .Named ( typeof ( TConcreteRepository ) .Name ) ; } public interface IAccountRepository { string Create ( Account account ) ; void Update ( Account account ) ; Account Get ( string accountId ) ; } public class AccountRepositoryFeedEntryDecorator : IAccountRepository { private readonly IAccountRepository decoratedRepository ; public AccountRepositoryFeedEntryDecorator ( IAccountRepository decoratedRepository ) { this.decoratedRepository = decoratedRepository ; } string Create ( Account account ) { //Add Entry To Feed return decoratedRepository.Create ( account ) ; } ; void Update ( Account account ) { //Add Entry To Feed return decoratedRepository.Udpate ( account ) ; } Account Get ( string accountId ) ; { //Add Entry To Feed return decoratedRepository.Get ( accountId ) ; } } public class AccountRepositoryAuthorizationDecorator : IAccountRepository { private readonly IAccountRepository decoratedRepository ; public AccountRepositoryAuthorizationDecorator ( IAccountRepository decoratedRepository ) { this.decoratedRepository = decoratedRepository ; } string Create ( Account account ) { //Ensure User Is Authorized return decoratedRepository.Create ( account ) ; } ; void Update ( Account account ) { //Ensure User Is Authorized return decoratedRepository.Udpate ( account ) ; } Account Get ( string accountId ) ; { //Ensure User Is Authorized return decoratedRepository.Get ( accountId ) ; } } public class AccountRepositoryMaskingDecorator : IAccountRepository { private readonly IAccountRepository decoratedRepository ; public AccountRepositoryMaskingDecorator ( IAccountRepository decoratedRepository ) { this.decoratedRepository = decoratedRepository ; } string Create ( Account account ) { //Mask Sensitive Information return decoratedRepository.Create ( account ) ; } ; void Update ( Account account ) { //Mask Sensitive Information return decoratedRepository.Udpate ( account ) ; } Account Get ( string accountId ) ; { //Mask Sensitive Information return decoratedRepository.Get ( accountId ) ; } } public class AccountRepository : IAccountRepository { string Create ( Account account ) { //Create account and return details } ; void Update ( Account account ) { //Update account and return details } Account Get ( string accountId ) ; { //Return Account } } RepositoryRegistration < IAccountRepository , AccountRepositoryFeedEntryDecorator > ( ) .ServiceOverrides ( new { decoratedRepository = typeof ( AccountRepositoryAuthorizationDecorator ) .Name } ) , RepositoryRegistration < AccountRepositoryAuthorizationDecorator > ( ) .ServiceOverrides ( new { decoratedRepository = typeof ( AccountRepositoryMaskingDecorator ) .Name } ) , RepositoryRegistration < AccountRepositoryMaskingDecorator > ( ) .ServiceOverrides ( new { decoratedRepository = typeof ( AccountRepository ) .Name } ) , RepositoryRegistration < AccountRepository > ( )
What is the difference between a Component and a Service dependency ?
C_sharp : I 'm implementing sortable columns on my Kendo grid and the user-expected behaviour is to allow multiple columns to be sorted at the same time.Naturally , I 'm starting off by writing a unit test to be able to verify that the sorting is ( by default ) first by Ref ascending , then Name ascending.Test suppliers in question are here : Then I go and ask the test for my sorted suppliers.Fluent assertions I know has the BeInAscendingOrder and BeInDescendingOrder methods , however even after looking through the documentation and following possibly related questions I could n't see an example of chaining sorting methods.My current test verification is like this : I was expecting the verification to work a bit like LINQ where it has OrderBy ( x = > x.Ref ) .ThenBy ( x = > x.Name ) .However when running the test , it is failing because it is expecting the collection to be ordered ascending by Name ( the final sort assertion ) .Is there a way to tell Fluent Assertions that the sorts should be applied in conjunction with one another and not just in sequence ? <code> _context.Suppliers.Add ( new Supplier { Ref = `` abc '' , Name = `` steve '' } ) ; _context.Suppliers.Add ( new Supplier { Ref = `` abc '' , Name = `` bob '' } ) ; _context.Suppliers.Add ( new Supplier { Ref = `` cde '' , Name = `` ian '' } ) ; _context.Suppliers.Add ( new Supplier { Ref = `` fgh '' , Name = `` dan '' } ) ; results.Should ( ) .HaveCount ( 4 ) .And.BeInAscendingOrder ( x = > x.Ref ) .And.BeInAscendingOrder ( x = > x.Name ) ;
How to verify that multiple sorts have been applied to a collection ?
C_sharp : I have a method that queries a rest API where I do a mapping from JSON to an object . Since the query string and object type I pass to this method always have to match I wanted to include the query string as a static string . <code> public class Root { public static string Query ; } public class RootObject : Root , IRootObject { public D d { get ; set ; } public static new string Query = `` AccountSet '' ; } public interface IRootObject { D d { get ; } } public class RestClass { public void Connect < T > ( ) where T : Root , IRootObject { T.Query < -- fails ( not actual code . Just to show my problem ) } }
How can i associate a static string with an object type C #
C_sharp : This question inspired me to ask the following question . Does the DllImport attribute always loads the specific DLL even when you 're not calling/using the method.For example when you have the following code : Now when the application is started the AllocConsole will never be fired but will the dll be loaded anyway ? <code> static class Program { [ DllImport ( `` kernel32.dll '' ) ] static extern bool AllocConsole ( ) ; static void Main ( ) { if ( true ) { //do some things , for example starting the service . } else { AllocConsole ( ) ; } } }
Is the DllImport attribute always loading the unmanaged DLL
C_sharp : I want to create a card trick game using C # . I 've designed Picture Boxes on the form to be the cards ( backside ) . I also created a Click method for each of the pictures that creates a random number between 0 , 51 and use the number to set an image from an ImageList . My problem is that sometimes I get the same numbers ( example : two Jacks of Spades ) , how can I prevent that ? ! ( I mean if , for example , I got ( 5 ) , I may get another ( 5 ) ) <code> Random random = new Random ( ) ; int i = random.Next ( 0 , 51 ) ; pictureBox1.Image = imageList1.Images [ i ] ;
An issue in designing a Card Trick Game using C #
C_sharp : I often find that attributes can be too large.Sometimes it feels like the attributes take up more of the screen than the code.It can make it hard to spot the method names.Also , they are not reusable , so you can end up repeating your values a lot.To counter this I considered creating my own attribute class , which inherits from the requiredattribute , and just sets all the properties to the defaults I need.However , in most cases attributes are sealed , putting a stop to my schemes.Is there any alternative to large attributes ? As a random example of what I 'm talking about : <code> [ SoapDocumentMethod ( `` http : //services.acme.co.uk/account/Web/GetCustomerDetails/GetCustomerDetails '' , RequestNamespace = `` http : //services.acme.co.uk/account/Web '' , ResponseNamespace = `` http : //services.acme.co.uk/account/Web '' , Use = SoapBindingUse.Literal , ParameterStyle = SoapParameterStyle.Wrapped ) ] public Response GetCustomerDetails ( Request request ) { // ... }
Is there an alternative to large messy attributes ?
C_sharp : I 'm using MongoDb 2.6.10 and using C # Driver 1.9.2 . The server has a replicaset of two servers.My documents are of the format . itemId is unique.Then I have code to remove a favorite of the formAfter each time , I check that result.DocumentsAffected is equal to 1 . Once in a while , the value comes back as 0 . When I go into MongoDB myself , I can find the document matching the itemID , and I can see the favoriteId that it tried to remove in the array is still there . result.OK is true , and there 's no error information.What could cause this to fail ? <code> { `` itemID '' : 2314 , `` Favorites '' : [ 1 , 24 , 26 , 34 ] } var query = Query.EQ ( `` itemID '' , itemId ) ; var result = collection.Update ( query , Update.Pull ( `` Favorites '' , favoriteIdToRemove ) ) ;
Mongo update response says no document updated , but the document is there
C_sharp : This was originally a much more lengthy question , but now I have constructed a smaller usable example code , so the original text is no longer relevant.I have two projects , one containing a single struct with no members , named TestType . This project is referenced by the main project , but the assembly is not included in the executable directory . The main project creates a new app-domain , where it registers the AssemblyResolve event with the name of the included assembly . In the main app-domain , the same event is handled , but it loads the assembly from the project resources , manually.The new app-domain then constructs its own version of TestType , but with more fields than the original one . The main app-domain uses the dummy version , and the new app-domain uses the generated version.When calling methods that have TestType in their signature ( even simply returning it is sufficient ) , it appears that it simply destabilizes the runtime and corrupts the memory.I am using .NET 4.5 , running under x86.DummyAssembly : Main project : While both TestMethod1 and TestMethod2 should print 4 , the first one accesses some weird parts of the memory , and seems to corrupt the call stack well enough to influence the call to the second method . If I remove the call to the first method , everything is fine.If I run the code under x64 , the first method throws NullReferenceException.The amount of fields of both structs seems to be important . If the second struct is larger in total than the first one ( if I generate only one field or none ) , everything also works fine , same if the struct in DummyAssembly contains more fields . This leads me to believe that the JITter either incorrectly compiles the method ( not using the generated assembly ) , or that the incorrect native version of the method gets called . I have checked that typeof ( TestType ) returns the correct ( generated ) version of the type.All in all , I am not using any unsafe code , so this should n't happen . <code> using System ; [ Serializable ] public struct TestType { } using System ; using System.Reflection ; using System.Reflection.Emit ; internal sealed class Program { [ STAThread ] private static void Main ( string [ ] args ) { Assembly assemblyCache = null ; AppDomain.CurrentDomain.AssemblyResolve += delegate ( object sender , ResolveEventArgs rargs ) { var name = new AssemblyName ( rargs.Name ) ; if ( name.Name == `` DummyAssembly '' ) { return assemblyCache ? ? ( assemblyCache = TypeSupport.LoadDummyAssembly ( name.Name ) ) ; } return null ; } ; Start ( ) ; } private static void Start ( ) { var server = ServerObject.Create ( ) ; //prints 155680 server.TestMethod1 ( `` Test '' ) ; //prints 0 server.TestMethod2 ( `` Test '' ) ; } } public class ServerObject : MarshalByRefObject { public static ServerObject Create ( ) { var domain = AppDomain.CreateDomain ( `` TestDomain '' ) ; var t = typeof ( ServerObject ) ; return ( ServerObject ) domain.CreateInstanceAndUnwrap ( t.Assembly.FullName , t.FullName ) ; } public ServerObject ( ) { Assembly genAsm = TypeSupport.GenerateDynamicAssembly ( `` DummyAssembly '' ) ; AppDomain.CurrentDomain.AssemblyResolve += delegate ( object sender , ResolveEventArgs rargs ) { var name = new AssemblyName ( rargs.Name ) ; if ( name.Name == `` DummyAssembly '' ) { return genAsm ; } return null ; } ; } public TestType TestMethod1 ( string v ) { Console.WriteLine ( v.Length ) ; return default ( TestType ) ; } public void TestMethod2 ( string v ) { Console.WriteLine ( v.Length ) ; } } public static class TypeSupport { public static Assembly LoadDummyAssembly ( string name ) { var stream = Assembly.GetExecutingAssembly ( ) .GetManifestResourceStream ( name ) ; if ( stream ! = null ) { var data = new byte [ stream.Length ] ; stream.Read ( data , 0 , data.Length ) ; return Assembly.Load ( data ) ; } return null ; } public static Assembly GenerateDynamicAssembly ( string name ) { var ab = AppDomain.CurrentDomain.DefineDynamicAssembly ( new AssemblyName ( name ) , AssemblyBuilderAccess.Run ) ; var mod = ab.DefineDynamicModule ( name+ '' .dll '' ) ; var tb = GenerateTestType ( mod ) ; tb.CreateType ( ) ; return ab ; } private static TypeBuilder GenerateTestType ( ModuleBuilder mod ) { var tb = mod.DefineType ( `` TestType '' , TypeAttributes.Public | TypeAttributes.Serializable , typeof ( ValueType ) ) ; for ( int i = 0 ; i < 3 ; i++ ) { tb.DefineField ( `` _ '' +i.ToString ( ) , typeof ( int ) , FieldAttributes.Public ) ; } return tb ; } }
Cross-AppDomain call corrupts the runtime
C_sharp : I 'm currently dealing with reflection in c # . After : And i found this : [ System.Numerics.Matrix4x4 ] , [ System.Numerics.Matrix4x4+CanonicalBasis ] , [ System.Numerics.Matrix4x4+VectorBasis ] ( There are reflected types from `` System.Numerics.Vectors.dll '' ) I know that Matrix4x4 is structture , however I ca n't find any info about CanonicalBasis and VectorBasis , and what `` + '' means in this context.I was doing further research and another strange thing is that : But : Moreover , when I looked through members of Matrix4x4+VectorBasis there is member like this : And is it raw pointer like in c++ ? Or what is it ? P.S . I was doing it in c # interactive , but i do n't think it had any influence on results . <code> Assembly.LoadFile ( @ '' C : \Program Files\dotnet\shared\Microsoft.NETCore.App\2.0.7\System.Numerics.Vectors.dll '' ) .GetTypes ( ) Assembly.LoadFile ( @ '' C : \Program Files\dotnet\shared\Microsoft.NETCore.App\2.0.7\System.Numerics.Vectors.dll '' ) .GetType ( `` System.Numerics.Matrix4x4+VectorBasis '' ) .FullName '' System.Numerics.Matrix4x4+VectorBasis '' Assembly.LoadFile ( @ '' C : \Program Files\dotnet\shared\Microsoft.NETCore.App\2.0.7\System.Numerics.Vectors.dll '' ) .GetType ( `` System.Numerics.Matrix4x4+VectorBasis '' ) .Name '' VectorBasis '' [ System.Numerics.Vector3* Element0 ]
What does `` + '' mean in reflected FullName and '* ' after Member c #
C_sharp : I 'm trying to create a type similar to Rust 's Result or Haskell 's Either and I 've got this far : Given that both types parameters are restricted to be notnull , why is it complaining ( anywhere where there 's a type parameter with the nullable ? sign after it ) that : A nullable type parameter must be known to be a value type or non-nullable reference type . Consider adding a 'class ' , 'struct ' , or type constraint . ? I 'm using C # 8 on .NET Core 3 with nullable reference types enabled . <code> public struct Result < TResult , TError > where TResult : notnull where TError : notnull { private readonly OneOf < TResult , TError > Value ; public Result ( TResult result ) = > Value = result ; public Result ( TError error ) = > Value = error ; public static implicit operator Result < TResult , TError > ( TResult result ) = > new Result < TResult , TError > ( result ) ; public static implicit operator Result < TResult , TError > ( TError error ) = > new Result < TResult , TError > ( error ) ; public void Deconstruct ( out TResult ? result , out TError ? error ) { result = ( Value.IsT0 ) ? Value.AsT0 : ( TResult ? ) null ; error = ( Value.IsT1 ) ? Value.AsT1 : ( TError ? ) null ; } }
C # 's ca n't make ` notnull ` type nullable
C_sharp : I know Since the release of msbuild 15 ( vs 2017 ) that NuGet is now fully integrated into MSBuild.I have a nuspec file with defining variables of package properties like : The nuspec file is located in the same folder of the project.When using nuget tool to create the package , it works fine . When using msbuild v15 , it raise an exception.run the command : Microsoft ( R ) Build Engine version 15.8.168+ga8fba1ebd7 for .NET Framework 15.8.168.64424raise exception : C : \Program Files\dotnet\sdk\2.1.402\Sdks\NuGet.Build.Tasks.Pack\build\NuGet.Build.Tasks.Pack.targets ( 199,5 ) : error : Value can not be null or an empty string . The strange is that dotnet sdk version 2.1.402 raises the exception.I tried msbuild installed with vs2017 with its path and also it raises the same exception.When i substitute the variables with its values , msbuild is working fine.The questionIs this a bug in msbuild version 15.8.168.64424 or i missed something ? In other words , Can msbuild support using the metadata variables of the package ? . <code> < metadata > < id > $ id $ < /id > < version > $ version $ < /version > < authors > $ authors $ < /authors > ... < /metadata > nuget pack msbuild -version msbuild /t : pack /p : configuration=release /p : NuspecFile=mylib.nuspec
Msbuild v15 ca n't resolve the variables of metadata of nuspec file
C_sharp : I 'm trying to create Unit Test . I have class User : My first test is UsersCount_Test test which tests UsersCount property : If I add new test method in my test class ( I 'm using separate classes for testing each entity ) , I need to create new instance of User . That 's why I did this : Now each test classes inherits from this class . And also I created test initializer method . Now my test class looks like this : Now I 'm adding new property to User and writing some logic : After that I 'm creating new test : Test fails because UserContact of TestEntity is null . I understood that TestEntity should be created by logic . After that I fix test initilizer method : Here is Contact modelMy question is how to set TestEntity only one time , is it possible ( maybe get it in memory and use it when it calls SetTestEntity method ) ? Because SetTestentity method creates a new entity in each test and it takes more development time . ( For example , If creating an instance of UserContact takes 3 seconds all , test runs more than 3 seconds ) . Another way , in this case , is to set UserContact in ContactLists test , but I think it 's not a good idea . In the future when we will add new logics , I need to fix each test . Please give me any suggestion and/or ideas . <code> public class User { public int UsersCount { get { using ( MainContext context = new MainContext ( ) ) { return context.Users.Count ( ) ; } } } public Guid Id { get ; set ; } = Guid.NewGuid ( ) ; public string UserName { get ; set ; } public string Password { get ; set ; } public Contact UserContact { get ; set ; } } [ TestMethod ] public void UsersCount_Test ( ) { var user = new User ( ) ; var context = new MainContext ( ) ; int usersCount = context.Users.Count ( ) ; context.Users.Add ( new User ( ) ) ; context.SaveChanges ( ) ; Assert.AreEqual ( usersCount + 1 , user.UsersCount , $ '' It should be { usersCount + 1 } because we 're adding one more user '' ) ; } public class BaseTest < T > { public T TestEntity ; public MainContext TestContext = new MainContext ( ) ; } [ TestClass ] public class UserTest : BaseTest < User > { [ TestMethod ] public void UsersCount ( ) { int usersCount = TestContext.Users.Count ( ) ; TestContext.Users.Add ( new User ( ) ) ; TestContext.SaveChanges ( ) ; Assert.AreEqual ( usersCount + 1 , TestEntity.UsersCount , $ '' It should be { usersCount + 1 } because we 're adding one more user '' ) ; } [ TestInitialize ] public void SetTestEntity ( ) { TestEntity = new User ( ) ; } } string phoneNumber ; public string PhoneNumber { get { return phoneNumber ; } set { SetUserContact ( phoneNumber , value ) ; phoneNumber = value ; } } void SetUserContact ( string oldContact , string newContact ) { UserContact.ContactsList.Remove ( oldContact ) ; UserContact.ContactsList.Add ( newContact ) ; } [ TestMethod ] public void ContactList_Test ( ) { var newPhone = `` +8888888888888 '' ; TestEntity.PhoneNumber = newPhone ; Assert.IsTrue ( TestEntity.UserContact.ContactsList.Any ( a = > a == newPhone ) , $ '' It should contains { newPhone } '' ) ; } [ TestInitialize ] public void SetTestEntity ( ) { TestEntity = new User ( ) { UserContact = new Contact ( ) } ; } public class Contact { public Guid Id { get ; set ; } = Guid.NewGuid ( ) ; public virtual List < string > ContactsList { get ; set ; } = new List < string > ( ) ; }
How to get test initialize in memory and use in each test
C_sharp : I need to make a simple check if a dds file is of valid format . I just need to do a general check of the dds file , so I do not need to check if it is a dxt1 , dxt5 , dx10 etc . For example if I have a png image and I rename the extensions to .dds the dds format will ofcourse be wrong and I would then need to tell the user that he is trying to use a dds file with a wrong format . However if I have a dds that indeed has a correct file format I will not need to do any further investigation since I do not care of what type of dds file it is ( at this moment ) . So I do only have to read the parts of the dds file that will stay the same on ALL dds files . I 'm thinking I could read the dds header and magic number in some way . I have to do the same validation for a png file and there I am reading the png header like this : And I was looking if there is a similiar way to check the format of a dds file . I am new to this and the problem I am having is to know what bytes in the dds file that will always be the same for all dds files ( so that I can check these bytes to see if the dds format is valid ) and how I can implement the code in a simple way to check the dds format . Any help will be appreciated.Edit : So thanks to @ NaCl I have got the first part of the question answered . I now know what parts in the dds file that is required but I do not know how to locate it in the dds file . I have opened a lot of dds files with a hex editor but I am not very good at reverse engineering so I ca n't understand where the bytes that I need to check is located which will furthermore make me not to know how I can implement code to search for bytes at the specified positions ( which I can do with the png file since I found much more document about that file ) since I do not know at what position to go to.If anybody can Point me in the right direction or help me in some other way I would appreciate it very much . Thanks . <code> var png = new byte [ ] { 0x89 , 0x50 , 0x4e , 0x47 , 0x0D , 0x0A , 0x1A , 0x0A } using ( FileStream fs = new FileStream ( fileToCheck , FileMode.Open , FileAccess.Read ) ) { if ( fs.Length > buffer.Length ) { fs.Read ( buffer , 0 , buffer.Length ) ; fs.Position = ( int ) fs.Length - endBuffer.Length ; fs.Read ( bufferEnd , 0 , endBuffer.Length ) ; } fs.Close ( ) ; } for ( int i = 0 ; i < png.Length ; i++ ) { if ( buffer [ i ] ! = png [ i ] ) return false ; } return true ;
How can I make sure that a DirectDraw surface has a correct file format ?
C_sharp : I have the following query : Which is used to query a SQLite in-memory DB as : However when I try to read the values as Int32 I get InvalidCastException.The reason why I am using dapper like so is that as a side project I am building some features on top of dapper to map the values to a POCO ( I am aware of the similar projects e.g . rainbow , dapper.extensions etc ) .So something along the lines of : Again , ignore the performance cost associated with the reflection call.In the example above the property type of the POCO is int32 and because of this problem I can not assign the value to the obj.Any help or ideas are very much appreciated . <code> SELECT [ Person ] . [ Id ] AS [ Person_Id ] , [ Person ] . [ Name ] AS [ Person_Name ] , [ Address ] . [ Id ] AS [ Address_Id ] , [ Address ] . [ Number ] AS [ Address_Number ] , [ Address ] . [ Street ] AS [ Address_Street ] , FROM [ Person ] LEFT JOIN [ Address ] ON [ Person ] . [ addressId ] = [ Address ] . [ Id ] var rows = _database.Query ( query ) ; foreach ( IDictionary < string , object > row in rows ) { var someId = ( int ) row [ `` Person_Id '' ] ; var someNumber = ( int ) row [ `` Address_Number '' ] ; } var rowVal = row [ fieldName ] ; propInfo.SetValue ( obj , rowVal , null ) ;
Why is dapper returning every number column as Int64 ?
C_sharp : For instance : I have array Who know fast method to find index of tag 's array ? I need something as following : a sequence can be in more than one times in src.Solution : How to find index of sublist in list ? <code> var src = new byte [ ] { 1 , 2 , 3 , 4 , 5 } ; var tag = new byte [ ] { 3 , 4 } ; int FindIndexOfSeq ( byte [ ] src , byte [ ] sequence ) ;
How to determine that one array is a part of another one ?
C_sharp : I am new to c # . I would like to know if a string such as a user name contains a specific word . I want to get those specific words from an array.Here 's a example. ` ( Update ) Thank you all but me learning c # only for about a month could not cover lambda or regex yet . I will have a look at these codes while later . <code> Console.Write ( `` Name : `` ) ; _name = Console.ReadLine ( ) ; name = Program.ProperNameMethod ( _name ) ; Console.WriteLine ( ) ; string [ ] badWordArray = { `` aBadword1 '' , `` aBadWord2 '' , `` aBadWord3 '' } ; if ( ! string.IsNullOrEmpty ( name ) // Would like to check for the badwordarray aswell )
Check if a string contains a specific string using array
C_sharp : I am using Telerik Gridview for displaying list of records and i have more than 10 pages on which i am using this gridview with this following common events code copy pasted ( with some minor changes ) on all this pages : This is my one page which inherits from following page : So is this possible that i can place all this events in this ParentPage page and just call from every child page instead of polluting my every page with this events ? ? Note : In some of my pages this DisplayRecords methods can contains some parameters but rest all events are just common . <code> protected void Page_Load ( object sender , EventArgs e ) { DisplayRecords ( ) } public void DisplayRecords ( ) { //Grid view names are different on different pages . GridView1.DataSource=Fetching records from database . GridView1.DataBind ( ) ; } protected void GridView1_SortCommand ( object sender , GridSortCommandEventArgs e ) { DisplayRecords ( ) } protected void GridView1_PageIndexChanged ( object sender , GridPageChangedEventArgs e ) { var index = e.NewPageIndex ; DisplayRecords ( ) } protected void GridView1_PageSizeChanged ( object sender , GridPageSizeChangedEventArgs e ) { var size = e.NewPageSize ; DisplayRecords ( ) } public partial class LoadSettings : ParentPage { //Load events and other events } [ Serializable ] public class ParentPage : RadAjaxPage { } Page 1 : **ttt.aspx**public void DisplayRecords ( ) { //Grid view names are different on different pages . GridView1.DataSource=this.GetAlltttData ( ) GridView1.DataBind ( ) ; } public DataTable GetAlltttData ( ) { using ( var context = new MyDataContext ( ) ) { var data = from c in context.ttt select c ; return MyDataContext.LINQToDataTable ( data ) ; } } Page 2 : **bbb.aspx**public void DisplayRecords ( ) { //Grid view names are different on different pages . GridView1.DataSource=this.GetAllbbbData ( ) GridView1.DataBind ( ) ; } public DataTable GetAllbbbData ( ) { using ( var context = new MyDataContext ( ) ) { var data = from c in context.bbb select c ; return MyDataContext.LINQToDataTable ( data ) ; } } protected void rgbbb_SortCommand ( object sender , GridSortCommandEventArgs e ) { DisplayRecords ( ) } protected void rgbbb_PageIndexChanged ( object sender , GridPageChangedEventArgs e ) { var index = e.NewPageIndex ; DisplayRecords ( ) } protected void rgbbb_PageSizeChanged ( object sender , GridPageSizeChangedEventArgs e ) { var size = e.NewPageSize ; DisplayRecords ( ) }
How to delegate telerik grid view common methods to be call from parent page from every child page ?
C_sharp : I 'm trying to remove duplicate entries from a list which contains a generic object.And the code to remove the dupes : The problem is Equals and GetHashCode is never called . Anyone have any idea why ? <code> public class MessageInfo { public DateTime Date { get ; set ; } public string To { get ; set ; } public string Message { get ; set ; } } public class SMSDupeRemover : IEqualityComparer < MessageInfo > { public bool Equals ( MessageInfo x , MessageInfo y ) { throw new NotImplementedException ( ) ; } public int GetHashCode ( MessageInfo obj ) { throw new NotImplementedException ( ) ; } } IEnumerable < MessageInfo > new_texts = text_messages.Distinct ( new SMSDupeRemover ( ) ) ;
Simple IEqualityComparer < T > question
C_sharp : I am writing an Android ( Xamarin ) application which is able to zoom and pan an image . A user can also click on a position on the image . I need those coordinates on the image for later use.The following code is zooming and panning the image : So far so good , now I have some MotionEvent in use , which is a LongPressListener . I wrote the following code to translate the coordinates from the MotionEvent to the coordinates on the image : e in this case is the frame of the image . The frame holds an image ( which is _parent ) , the user can drag the image . _parent._posX/Y are changed when that happens . The user can also zoom the image , that 's the _scaleFactor.So , when a user taps anywhere in e , I need to translate those coordinates to the image coordinates.Those two lines of code works , but when the user zooms in , the coordinates are off as you can see in the attached image : The red dots represent the calculated positions . As you can see , if a user zooms in the coordinates gets more off . What 's wrong in this calculation ? <code> protected override void OnDraw ( Canvas canvas ) { base.OnDraw ( canvas ) ; _maxX = canvas.Width ; _maxY = canvas.Height ; canvas.Translate ( _posX , _posY ) ; if ( _scaleDetector.IsInProgress ) canvas.Scale ( _scaleFactor , _scaleFactor , _scaleDetector.FocusX , _scaleDetector.FocusY ) ; else canvas.Scale ( _scaleFactor , _scaleFactor , _lastGestureX , _lastGestureY ) ; } var actualX = e.GetX ( ) - ( _parent._posX / _parent._scaleFactor ) ; var actualY = e.GetY ( ) - ( _parent._posY / _parent._scaleFactor ) ;
Android : Get correct coordinates with scaled and translated canvas
C_sharp : You 'll appreciate the following two syntactic sugars : andClearly the first example in each case is more readable . Is there a way to define this kind of thing myself , either in the C # language , or in the IDE ? The reason I ask is that there are many similar usages ( of the long kind ) that would benefit from this , eg . if you 're using ReaderWriterLockSlim , you want something pretty similar.EDIT 1 : I 've been asked to provide an example , so I 'll give it a go : Of course you 'd have to give some thoughts as to how to use the TryEnterReadLocks and those kinds of things with returns . But I 'm sure you could think of something . <code> lock ( obj ) { //Code } same as : Monitor.Enter ( obj ) try { //Code } finally { Monitor.Exit ( obj ) } using ( var adapt = new adapter ( ) ) { //Code2 } same as : var adapt= new adapter ( ) try { //Code2 } finally { adapt.Dispose ( ) } myclass { ReaderWriterLockSlim rwl = new ReaderWriterLockSlim ( ) ; void MyConcurrentMethod ( ) { rwl.EnterReadLock ( ) ; try { //Code to do in the lock , often just one line , but now its turned into 8 ! } finally { rwl.ExitReadLock ( ) ; } } } //I 'd rather have : void MyConcurrentMethod ( ) { rwl.EnterReadLock ( ) { //Code block . Or even simpler , no brackets like one-line ifs and usings } }
Does this feature exist ? Defining my own curly brackets in C #
C_sharp : I know that 'new ' keyword will call the constructor and initialize the object in managed heap.My question is how the CLR doing the below.How the above line is executed by CLR ? How the memeory is allocated for the object by CLR ? How CLR determine the size of the object ? How CLR will come know it , if there is no space to allocate memory for the object from the heap ? <code> MyObject obj = new MyObject ( ) ;
What is happening when I give MyObject obj = new MyObject ( )
C_sharp : I 've always been explicit with my code when using instance members , prefixing them with this . and with static members , prefixing them with the type name.Roslyn seems not to like this , and politely suggests that you can omit this . and Type . from your code where appropriate ... ... so where I would do this ... ( no pun intended ) ... roslyn suggests I do this ... ... however when it comes to using extension methods , it appears that I can not omit the use of this . for example ... Questions : Why does Roslyn not seem to like explicit use of this . and Type . ? Why do I need to explicitly use this . for extension methods ? Whilst not strictly part of this question , how do I resolve the discrepancy between Roslyn NOT wanting me to use this . and Type . and StyleCop 's analyzers insisting that I use them ? <code> public void DoSomethingCool ( ) { this.CallAwesomeMethod ( ) ; CoolCucumber.DoSomethingLessAewsome ( ) ; } public void DoSomethingCool ( ) { CallAwesomeMethod ( ) ; DoSomethingLessAwesome ( ) ; } public int GetTotal ( ) { // This does n't work return Sum ( o = > o.Value ) ; // This does return this.Sum ( o = > o.Value ) ; }
Roslyn code analyzers - when should I use `` this . `` ?
C_sharp : If you put the following code in your compiler the result is a bit bizar : Result : decimal x = 275.99999999999999999999999double y = 276.0Can someone explain this to me ? I do n't understand how this can be correct . <code> decimal x = ( 276/304 ) *304 ; double y = ( 276/304 ) *304 ; Console.WriteLine ( `` decimal x = `` + x ) ; Console.WriteLine ( `` double y = `` + y ) ;
decimal rounding is off for ( 276/304 ) *304
C_sharp : I have been looking for an answer to this for 2 days now . I 'm not even sure exactly what is wrong , but I think I may have pinpointed the possible culprit . My program is a database tracker/manager that will keep track of the equipment at my company . The user can query for , create , and edit equipment . Right now , querying the database works , but when I try to add to or update the database the program throws Validation errors ( I 'll get into this more below ) .I have an equipment class that has many nullable attributes ( because the user may not know many of these properties when creating a new entry , we left almost all the attributes nullable ) and is connected to ( using foreign keys and lazy loading/ '' virtual '' ) to a few other tables that were made to help normalize the database.Here is some abreviated code to help : Equipment Model : Division Model : This table only contains the 5 different divisions at our company and the related IDs.PAU Model : This model contains the PAU # s and the related description and ID.Equipment Controller : In the views I have dropdown lists that for these attributes that are populated with the possible options already in the database ( stored in ViewData above ) . I have tried a couple different ways of storing this data into my model , but this way seems to work the best : Ok so after a lot of debugging , the problem seems to be because the lazy loaded properties have null attributes , which are not allowed in their tables . My examples will be dealing more with creating new equipment objects , though I believe the problem is the same for editing them.Division Example : So DivisionId in the Equipment class can be null ( either user does n't know or equipment does n't belong to specific division ) , and the Equipment table/class does n't complain about that . But when I try to SaveChanges ( ) , the program complains becuase the virtual Division object is null ( has the default DivisionId of 0 and a null DivisionName ) . Since Equipment.DivisionId is null , I do n't want to be updating the Division table for this Equipment object . Is there a way to get around this ? Should I not be lazy loading ? PAU Example : Since PAUId is a required attribute for all Equipment objects , but as in the Division Example , PAU.PAUNumber and PAU.PAUDescription are null ( and PAU.PAUId is the default 0 ) causing an error . This is just like the first one , but with the required attribute ( so I am not sure if it needs to be handled differently ) .So I am not really sure how to fix this problem . Is lazy loading the issue since I only want to connect my Equipment object to those other tables if the Id/Foreign Key is not null ? Is there some method I can call that would update the equipment object 's values from the other tables based on the Id 's ? Is it a method that I need to create myself ? If I get rid of lazy loading , could you explain how I should write my queries so I can still get access to the normalized data ( like DivisionName ) ? I apologize for the super long post . I just did n't want to miss anything that may be important . EditI have a rough solution to the PAU Example ( but I do n't think it works for the Division Example because of allowing nulls within Equipment but not the individual tables ) .It 's not very elegant though . I tried looking at a tutorial about reflection , but it did n't really make sense . If that would be a more elegant solution , could someone try explaining that ? I 'm still looking for a solution for the Division Example ( since Equipment.DivisionId is nullable but Division.DivisionId is not nullable this does n't work ) , so any help on either this or a more elegant solution to the above would be greatly appreciated ! <code> public class Equipment { public int EquipmentId { get ; set ; } //required public string Company { get ; set ; } //required public bool Verified { get ; set ; } //required ( ... other non-required attributes ... ) //The following two attributes are where my problems are I believe [ ForeignKey ( `` PAU '' ) ] public int PAUId { get ; set ; } //required and Foreign Key //This is not required ( but is FK to the related table ) if the user does n't know [ ForeignKey ( `` Division '' ) ] public Nullable < int > DivisionId { get ; set ; } //These are the lazy loading connections to the other tables in the database public virtual Division Division { get ; set ; } public virtual PAU PAU { get ; set ; } } public class Division { public Division ( ) { this.Equipments = new HashSet < Equipment > ( ) ; } //These are non-nullable/required fields public int DivisionId { get ; set ; } public string DivisionName { get ; set ; } public virtual ICollection < Equipment > Equipments { get ; set ; } } public class PAU { public PAU ( ) { this.Equipments = new HashSet < Equipment > ( ) ; } //These are non-nullable/required fields public int PAUId { get ; set ; } public string PAUNumber { get ; set ; } public string PAUDescription { get ; set ; } public virtual ICollection < Equipment > Equipments { get ; set ; } } public class EquipmentController : Controller { TLCP_DEVEntities4 db = new TLCP_DEVEntities4 ( ) ; ( ... ) public ActionResult Edit ( int id ) { ViewData [ `` divisions '' ] = new SelectList ( db.Equipments . OrderBy ( x = > x.Division.DivisionName ) . Select ( x = > x.Division ) .ToList ( ) . Distinct ( ) , `` DivisionId '' , `` DivisionName '' ) ; ViewData [ `` PAUNumbers '' ] = new SelectList ( db.Equipments . OrderBy ( x = > x.PAU.PAUNumber ) . Select ( x = > x.PAU ) .ToList ( ) . Distinct ( ) , `` PAUId '' , `` PAUNumber '' ) ; return View ( db.Equipments.Find ( id ) ) ; } [ HttpPost ] public ActionResult Edit ( Equipment equipment ) { if ( ModelState.IsValid ) { db.Entry ( equipment ) .State = EntityState.Modified ; db.SaveChanges ( ) ; //fails here return RedirectToAction ( `` Maintenance '' ) ; } ViewData [ `` divisions '' ] = new SelectList ( db.Equipments . OrderBy ( x = > x.Division.DivisionName ) . Select ( x = > x.Division ) .ToList ( ) . Distinct ( ) , `` DivisionId '' , `` DivisionName '' ) ; ViewData [ `` PAUNumbers '' ] = new SelectList ( db.Equipments . OrderBy ( x = > x.PAU.PAUNumber ) . Select ( x = > x.PAU ) .ToList ( ) . Distinct ( ) , `` PAUId '' , `` PAUNumber '' ) ; return View ( equipment ) ; } public ActionResult AddEquipment ( ) { ViewData [ `` divisions '' ] = new SelectList ( db.Equipments . OrderBy ( x = > x.Division.DivisionName ) . Select ( x = > x.Division ) .ToList ( ) . Distinct ( ) , `` DivisionId '' , `` DivisionName '' ) ; ViewData [ `` PAUNumbers '' ] = new SelectList ( db.Equipments . OrderBy ( x = > x.PAU.PAUNumber ) . Select ( x = > x.PAU ) .ToList ( ) . Distinct ( ) , `` PAUId '' , `` PAUNumber '' ) ; return View ( ) ; } public ActionResult AddEquipment ( Equipment equipment ) { try { db.Equipments.Add ( equipment ) ; db.SaveChanges ( ) ; return RedirectToAction ( `` Maintenance '' ) ; } catch ( Exception ex ) { ViewData [ `` divisions '' ] = new SelectList ( db.Equipments . OrderBy ( x = > x.Division.DivisionName ) . Select ( x = > x.Division ) .ToList ( ) . Distinct ( ) , `` DivisionId '' , `` DivisionName '' ) ; ViewData [ `` PAUNumbers '' ] = new SelectList ( db.Equipments . OrderBy ( x = > x.PAU.PAUNumber ) . Select ( x = > x.PAU ) .ToList ( ) . Distinct ( ) , `` PAUId '' , `` PAUNumber '' ) ; return View ( ) ; } } ( ... ) } < % : Html.DropDownListFor ( model = > model.DivisionId , ViewData [ `` divisions '' ] as SelectList , `` '' ) % > public ActionResult AddEquipment ( Equipment equipment ) { try { equipment.PAU.PAUId = equipment.PAUId ; equipment.PAU.PAUNumber = db.PAUs.Find ( equipment.PAUId ) .PAUNumber ; equipment.PAU.PAUDescription = db.PAUs.Find ( equipment.PAUId ) .PAUDescription ; ( ... ) }
Database Validation Errors . Allow nullable value in one table but not in related ( normalized ) table
C_sharp : Ugly : Better ( maybe monad ) : Even better ? Any reason this could n't be written ? <code> string city = null ; if ( myOrder ! = null & & myOrder.Customer ! = null ) city = myOrder.Customer.City ; var city = myOrder .With ( x = > x.Customer ) .With ( x = > x.City ) var city = Maybe ( ( ) = > myOrder.Customer.City ) ;
Maybe monad using expression trees ?
C_sharp : Is there a way how to programmatically enable/disable usage of property name specified by [ JsonProperty ] ? When I serialize : I would like to be able to see an output `` in debug '' : And `` in release '' : <code> public class Dto { [ JsonProperty ( `` l '' ) ] public string LooooooooooooongName { get ; set ; } } { `` LooooooooooooongName '' : '' Data '' } { `` l '' : '' Data '' }
Enable/disable usage of specified [ JsonProperty ] name
C_sharp : I have this method in c # , and I wish to refactor it . There are just too many bools and lines . What would be the best refactoring . Making a new class seems a bit overkill , and cutting simply in two seems hard . Any insight or pointer would be appreciated.method to refactor <code> private DialogResult CheckForSireRestrictionInSubGroup ( bool deletingGroup , string currentId ) { DialogResult result = DialogResult.No ; if ( ! searchAllSireList ) { DataAccessDialog dlg = BeginWaitMessage ( ) ; bool isClose = false ; try { ArrayList deletedSire = new ArrayList ( ) ; ISireGroupBE sireGroupBE = sireController.FindSireGroupSearch ( ) ; if ( sireGroupBE ! = null ) { //if the current group is in fact the seach group before saving bool currentGroupIsSeachGroup = sireGroupBE.TheSireGroup.id == currentId ; //if we have setting this group as search group bool selectedAsSearchGroup = this.chkBoxSelectedSireGroup.Checked ; //if the group we currently are in is not longer the seach group ( chk box was unchecked ) bool wasSearchGroup = currentGroupIsSeachGroup & & ! selectedAsSearchGroup ; //if the group is becoming the search group bool becomesSearchGroup = ! currentGroupIsSeachGroup & & selectedAsSearchGroup ; //if the group being deleted is in fact the search group bool deletingSearchGroup = deletingGroup & & currentGroupIsSeachGroup ; //if the user checked the checkbox but he 's deleting it , not a so common case , but //we should n't even consider to delete sire in this case bool deletingTemporarySearchGroup = deletingGroup & & ! currentGroupIsSeachGroup ; //if we are not deleting a temporary search group and it 's either //becoming one ( without deleting it ) or we already are the search group bool canDeleteSires = ! deletingTemporarySearchGroup & & ( becomesSearchGroup || currentGroupIsSeachGroup ) ; //we only delete sires if we are in search group if ( canDeleteSires ) { if ( deletingSearchGroup || wasSearchGroup ) { // If we deleted all sires deletedSire = new ArrayList ( ) ; deletedSire.AddRange ( sireGroupBE.SireList ) ; } else { //if we delete a few sire from the change of search group deletedSire = GetDeleteSire ( sireGroupBE.SireList ) ; } } EndWaitMessage ( dlg ) ; isClose = true ; result = ShowSubGroupAffected ( deletedSire ) ; } } finally { if ( ! isClose ) { EndWaitMessage ( dlg ) ; } } } return result ; }
Refactoring a method with too many bool in it
C_sharp : I am writing a very simple utility class with the aim to measure the time executed for any method passed in ( of any type ) .In my case Membership.ValidateUser ( model.UserName , model.Password ) return bool so I get an exception.I would like if would be possible write a utililty class of this type an a sample of code on how to fix it.Does it make sense use dynamic in stead of action ? <code> Tracing.Log ( Membership.ValidateUser ( model.UserName , model.Password ) , `` Membership.ValidateUser '' ) ; public static class Tracing { public static void Log ( Action action , string message ) { // Default details for the Log string sSource = `` TRACE '' ; string sLog = `` Application '' ; // Create the Log if ( ! EventLog.SourceExists ( sSource ) ) EventLog.CreateEventSource ( sSource , sLog ) ; // Measure time Elapsed for an Action Stopwatch stopwatch = Stopwatch.StartNew ( ) ; action ( ) ; stopwatch.Stop ( ) ; TimeSpan timeElapsed = stopwatch.Elapsed ; // Write the Log EventLog.WriteEntry ( sSource , `` TIME-ELAPSED : `` + timeElapsed .ToString ( ) + message , EventLogEntryType.Warning , 234 ) ; } }
How to count time elapsed for a method with an utility class
C_sharp : So , I 'm trying to have a parent/child class relationship like this : But , this is a compile error . So , my second thought was to declare the SetParent method with a where . But the problem is that I do n't know what type declare myParent as ( I know the type , I just so n't know how to declare it . ) <code> class ParentClass < C , T > where C : ChildClass < T > { public void AddChild ( C child ) { child.SetParent ( this ) ; //Argument 1 : can not convert from 'ParentClass < C , T > ' to 'ParentClass < ChildClass < T > , T > ' } } class ChildClass < T > { ParentClass < ChildClass < T > , T > myParent ; public void SetParent ( ParentClass < ChildClass < T > , T > parent ) { myParent = parent ; } } class ParentClass < C , T > where C : ChildClass < T > { public void AddChild ( C child ) { child.SetParent ( this ) ; } } class ChildClass < T > { var myParent ; //What should I declare this as ? public void SetParent < K > ( ParentClass < K , T > parent ) where K : ChildClass < T > { myParent = parent ; } }
Parent/Child Generics Relationship
C_sharp : I 've been optimising/benchmarking some code recently and came across this method : This is called from a performance critical loop elsewhere , so I naturally assumed all those typeof ( ... ) calls were adding unnecessary overhead ( a micro-optimisation , I know ) and could be moved to private fields within the class . ( I 'm aware there are better ways to refactor this code , however , I 'd still like to know what 's going on here . ) According to my benchmark this is n't the case at all ( using BenchmarkDotNet ) .Results on my machine ( Window 10 x64 , .NET 4.7.2 , RyuJIT , Release build ) : The functions compiled down to ASM : F1F2I do n't know how to interpret ASM so am unable to understand the significance of what 's happening here . In a nut shell , why is F1 faster ? <code> public void SomeMethod ( Type messageType ) { if ( messageType == typeof ( BroadcastMessage ) ) { // ... } else if ( messageType == typeof ( DirectMessage ) ) { // ... } else if ( messageType == typeof ( ClientListRequest ) ) { // ... } } [ DisassemblyDiagnoser ( printAsm : true , printSource : true ) ] [ RyuJitX64Job ] public class Tests { private Type a = typeof ( string ) ; private Type b = typeof ( int ) ; [ Benchmark ] public bool F1 ( ) { return a == typeof ( int ) ; } [ Benchmark ] public bool F2 ( ) { return a == b ; } } mov rcx , offset mscorlib_ni+0x729e10call clr ! InstallCustomModule+0x2320mov rcx , qword ptr [ rsp+30h ] cmp qword ptr [ rcx+8 ] , raxsete almovzx eax , al mov qword ptr [ rsp+30h ] , rcxmov rcx , qword ptr [ rcx+8 ] mov rdx , qword ptr [ rsp+30h ] mov rdx , qword ptr [ rdx+10h ] call System.Type.op_Equality ( System.Type , System.Type ) movzx eax , al
Why is typeA == typeB slower than typeA == typeof ( TypeB ) ?
C_sharp : The following ruby code runs in ~15s . It barely uses any CPU/Memory ( about 25 % of one CPU ) : And the following TPL C # puts all my 4 cores to 100 % usage and is orders of magnitude slower than the ruby version : How come ruby runs faster than C # ? I 've been told that Ruby is slow . Is that not true when it comes to algorithms ? Perf AFTER correction : Ruby ( Non parallel ) : 14.62sC # ( Non parallel ) : 2.22sC # ( With TPL ) : 0.64s <code> def collatz ( num ) num.even ? ? num/2 : 3*num + 1endstart_time = Time.nowmax_chain_count = 0max_starter_num = 0 ( 1..1000000 ) .each do |i| count = 0 current = i current = collatz ( current ) and count += 1 until ( current == 1 ) max_chain_count = count and max_starter_num = i if ( count > max_chain_count ) endputs `` Max starter num : # { max_starter_num } - > chain of # { max_chain_count } elements . Found in : # { Time.now - start_time } s '' static void Euler14Test ( ) { Stopwatch sw = new Stopwatch ( ) ; sw.Start ( ) ; int max_chain_count = 0 ; int max_starter_num = 0 ; object locker = new object ( ) ; Parallel.For ( 1 , 1000000 , i = > { int count = 0 ; int current = i ; while ( current ! = 1 ) { current = collatz ( current ) ; count++ ; } if ( count > max_chain_count ) { lock ( locker ) { max_chain_count = count ; max_starter_num = i ; } } if ( i % 1000 == 0 ) Console.WriteLine ( i ) ; } ) ; sw.Stop ( ) ; Console.WriteLine ( `` Max starter i : { 0 } - > chain of { 1 } elements . Found in : { 2 } s '' , max_starter_num , max_chain_count , sw.Elapsed.ToString ( ) ) ; } static int collatz ( int num ) { return num % 2 == 0 ? num / 2 : 3 * num + 1 ; }
How come this algorithm in Ruby runs faster than in Parallel 'd C # ?
C_sharp : I try to get a X509Certificate2 from a BountyCastle X509Certificate and a PKCS12 . I use the following code : I generate the rawData , like the following : The problem is , that I get the following exception : After some days of researching , I figured out , that the problem is based on the Mono implementation of ASN1 . This implementation does n't allow `` Undefined length encoding '' . If I use the code on Windows it works great.My questionIs there any way , to convert the pfxData stream to a valid ASN1 structure ? I have tried it with the following code : But with this code , I get the following exception : `` Index was out of range . Must be non-negative and less than the size of the collection.\nParameter name : startIndex '' I use Xamarin PCL with .NET Standard 1.3 and I can only use the `` Portable.BouncyCastle '' Nuget package.UPDATE Exception Stack Trace ( Converting BER to DER ) : EDIT : I have posted the same question in BouncyCastle GitHub : BouncyCastle GitHubEDIT 2 : I have tested to save the PKCS and create a X509Certificate2 with string constructor , like the following : Edit 3 : I have found the method var util = Pkcs12Utilities.ConvertToDefiniteLength ( pfxData.ToArray ( ) , certPassword.ToCharArray ( ) ) ; in the BouncyCastle library and if I use this method right before the File.WriteAllBytes ( pkcsPath , util ) ; line , the exception `` Undefined length encoding . '' is gone . But now , I get the following exception : Edit 4 : If I use the X509 certificate from BountyCastle as rawdata in the X509Certificate2 method , it works great ! But it is without the private key.. <code> certificate = new X509Certificate2 ( rawData , password , storageFlags ) ; using ( MemoryStream pfxData = new MemoryStream ( ) ) { X509CertificateEntry [ ] chain = new X509CertificateEntry [ 1 ] ; chain [ 0 ] = new X509CertificateEntry ( x509 ) ; pkcsStore.SetKeyEntry ( applicationName , new AsymmetricKeyEntry ( subjectKeyPair.Private ) , chain ) ; pkcsStore.Save ( pfxData , passcode.ToCharArray ( ) , random ) ; var rawData = pfx.ToArray ( ) ; } Asn1InputStream asn1InputStream = new Asn1InputStream ( pfxData ) ; var asn1Object = asn1InputStream.ReadObject ( ) ; MemoryStream memoryStream = new MemoryStream ( ) ; new Asn1OutputStream ( ( Stream ) memoryStream ) .WriteObject ( asn1Object ) ; var asn1ByteArray = memoryStream.ToArray ( ) ; certificate = new X509Certificate2 ( asn1ByteArray ) ; 05-28 15:19:54.895 D/Mono ( 3808 ) : Assembly Ref addref Mono.Security [ 0x9b4fe080 ] - > System [ 0xac8de400 ] : 1705-28 15:19:54.957 I/mono-stdout ( 3808 ) : System.AggregateException : One or more errors occurred . -- - > System.Security.Cryptography.CryptographicException : Unable to decode certificate . -- - > System.Security.Cryptography.CryptographicException : Input data can not be coded as a valid certificate . -- - > System.ArgumentOutOfRangeException : Index was out of range . Must be non-negative and less than the size of the collection.System.AggregateException : One or more errors occurred . -- - > System.Security.Cryptography.CryptographicException : Unable to decode certificate . -- - > System.Security.Cryptography.CryptographicException : Input data can not be coded as a valid certificate . -- - > System.ArgumentOutOfRangeException : Index was out of range . Must be non-negative and less than the size of the collection.Parameter name : startIndex at System.String.IndexOf ( System.String value , System.Int32 startIndex , System.Int32 count , System.StringComparison comparisonType ) [ 0x0002a ] in < d18287e1d683419a8ec3216fd78947b9 > :0 at System.String.IndexOf ( System.String value , System.Int32 startIndex , System.StringComparison comparisonType ) [ 0x00009 ] in < d18287e1d683419a8ec3216fd78947b9 > :0 at System.String.IndexOf ( System.String value , System.Int32 startIndex ) [ 0x00000 ] in < d18287e1d683419a8ec3216fd78947b9 > :0 at Mono.Security.X509.X509Certificate.PEM ( System.String type , System.Byte [ ] data ) [ 0x00030 ] in < 2940be14d5a1446694e2193e9029b558 > :0 at Mono.Security.X509.X509Certificate..ctor ( System.Byte [ ] data ) [ 0x00014 ] in < 2940be14d5a1446694e2193e9029b558 > :0 -- - End of inner exception stack trace -- - at Mono.Security.X509.X509Certificate..ctor ( System.Byte [ ] data ) [ 0x0002f ] in < 2940be14d5a1446694e2193e9029b558 > :0 05-28 15:19:54.958 I/mono-stdout ( 3808 ) : Parameter name : startIndex at System.Security.Cryptography.X509Certificates.X509Certificate2ImplMono.Import ( System.Byte [ ] rawData , System.String password , System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags ) [ 0x0000b ] in < 1a27f8ea09e3480db932cbde0eaedfb2 > :0 -- - End of inner exception stack trace -- - at System.Security.Cryptography.X509Certificates.X509Certificate2ImplMono.Import ( System.Byte [ ] rawData , System.String password , System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags ) [ 0x00031 ] in < 1a27f8ea09e3480db932cbde0eaedfb2 > :0 at System.Security.Cryptography.X509Certificates.X509Helper2.Import ( System.Byte [ ] rawData , System.String password , System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags , System.Boolean disableProvider ) [ 0x00020 ] in < 1a27f8ea09e3480db932cbde0eaedfb2 > :0 at System.Security.Cryptography.X509Certificates.X509Certificate2.Import ( System.Byte [ ] rawData , System.String password , System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags ) [ 0x00000 ] in < 1a27f8ea09e3480db932cbde0eaedfb2 > :0 at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor ( System.Byte [ ] rawData ) [ 0x00011 ] in < 1a27f8ea09e3480db932cbde0eaedfb2 > :0 05-28 15:19:54.958 I/mono-stdout ( 3808 ) : at System.String.IndexOf ( System.String value , System.Int32 startIndex , System.Int32 count , System.StringComparison comparisonType ) [ 0x0002a ] in < d18287e1d683419a8ec3216fd78947b9 > :0 at APP.Models.Services.ACommunicationService.CreateCertificate ( System.String storeType , System.String storePath , System.String password , System.String applicationUri , System.String applicationName , System.String subjectName , System.Collections.Generic.IList ` 1 [ T ] domainNames , System.UInt16 keySize , System.DateTime startTime , System.UInt16 lifetimeInMonths , System.UInt16 hashSizeInBits , System.Boolean isCA , System.Security.Cryptography.X509Certificates.X509Certificate2 issuerCAKeyCert ) [ 0x003b5 ] in C : \projects\APP - Kopie\APP_XamarinApplication\APP\APP\APP\Models\Services\ACommunicationService.cs:517 05-28 15:19:54.958 I/mono-stdout ( 3808 ) : at System.String.IndexOf ( System.String value , System.Int32 startIndex , System.StringComparison comparisonType ) [ 0x00009 ] in < d18287e1d683419a8ec3216fd78947b9 > :0 at APP.Models.Services.ACommunicationService.CreateCertificate ( System.String storeType , System.String storePath , System.String applicationUri , System.String applicationName , System.String subjectName , System.Collections.Generic.IList ` 1 [ T ] serverDomainNames , System.UInt16 keySize , System.UInt16 lifetimeInMonths , System.UInt16 hashSizeInBits ) [ 0x00001 ] in C : \projects\APP - Kopie\APP_XamarinApplication\APP\APP\APP\Models\Services\ACommunicationService.cs:318 at APP.Models.Services.ACommunicationService+ < ACommunicationServiceAsync > d__18.MoveNext ( ) [ 0x00972 ] in C : \projects\APP - Kopie\APP_XamarinApplication\APP\APP\APP\Models\Services\ACommunicationService.cs:214 -- - End of inner exception stack trace -- -05-28 15:19:54.959 I/mono-stdout ( 3808 ) : at System.String.IndexOf ( System.String value , System.Int32 startIndex ) [ 0x00000 ] in < d18287e1d683419a8ec3216fd78947b9 > :0 at System.Threading.Tasks.Task.ThrowIfExceptional ( System.Boolean includeTaskCanceledExceptions ) [ 0x00011 ] in < d18287e1d683419a8ec3216fd78947b9 > :0 at System.Threading.Tasks.Task.Wait ( System.Int32 millisecondsTimeout , System.Threading.CancellationToken cancellationToken ) [ 0x00043 ] in < d18287e1d683419a8ec3216fd78947b9 > :0 at System.Threading.Tasks.Task.Wait ( ) [ 0x00000 ] in < d18287e1d683419a8ec3216fd78947b9 > :0 at APP.Models.Services.ACommunicationService..ctor ( PCLStorage.IFolder rootFolder ) [ 0x00010 ] in C : \projects\APP - Kopie\APP_XamarinApplication\APP\APP\APP\Models\Services\ACommunicationService.cs:46 05-28 15:19:54.959 I/mono-stdout ( 3808 ) : at Mono.Security.X509.X509Certificate.PEM ( System.String type , System.Byte [ ] data ) [ 0x00030 ] in < 2940be14d5a1446694e2193e9029b558 > :0 05-28 15:19:54.959 I/mono-stdout ( 3808 ) : at Mono.Security.X509.X509Certificate..ctor ( System.Byte [ ] data ) [ 0x00014 ] in < 2940be14d5a1446694e2193e9029b558 > :0 05-28 15:19:54.959 I/mono-stdout ( 3808 ) : -- - End of inner exception stack trace -- -05-28 15:19:54.959 I/mono-stdout ( 3808 ) : at Mono.Security.X509.X509Certificate..ctor ( System.Byte [ ] data ) [ 0x0002f ] in < 2940be14d5a1446694e2193e9029b558 > :0 05-28 15:19:54.959 I/mono-stdout ( 3808 ) : at System.Security.Cryptography.X509Certificates.X509Certificate2ImplMono.Import ( System.Byte [ ] rawData , System.String password , System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags ) [ 0x0000b ] in < 1a27f8ea09e3480db932cbde0eaedfb2 > :0 -- - > ( Inner Exception # 0 ) System.Security.Cryptography.CryptographicException : Unable to decode certificate . -- - > System.Security.Cryptography.CryptographicException : Input data can not be coded as a valid certificate . -- - > System.ArgumentOutOfRangeException : Index was out of range . Must be non-negative and less than the size of the collection.05-28 15:19:54.961 I/mono-stdout ( 3808 ) : -- - End of inner exception stack trace -- -05-28 15:19:54.961 I/mono-stdout ( 3808 ) : at System.Security.Cryptography.X509Certificates.X509Certificate2ImplMono.Import ( System.Byte [ ] rawData , System.String password , System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags ) [ 0x00031 ] in < 1a27f8ea09e3480db932cbde0eaedfb2 > :0 05-28 15:19:54.961 I/mono-stdout ( 3808 ) : at System.Security.Cryptography.X509Certificates.X509Helper2.Import ( System.Byte [ ] rawData , System.String password , System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags , System.Boolean disableProvider ) [ 0x00020 ] in < 1a27f8ea09e3480db932cbde0eaedfb2 > :0 05-28 15:19:54.962 I/mono-stdout ( 3808 ) : at System.Security.Cryptography.X509Certificates.X509Certificate2.Import ( System.Byte [ ] rawData , System.String password , System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags ) [ 0x00000 ] in < 1a27f8ea09e3480db932cbde0eaedfb2 > :0 05-28 15:19:54.962 I/mono-stdout ( 3808 ) : at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor ( System.Byte [ ] rawData ) [ 0x00011 ] in < 1a27f8ea09e3480db932cbde0eaedfb2 > :0 Parameter name : startIndex05-28 15:19:54.963 I/mono-stdout ( 3808 ) : at APP.Models.Services.ACommunicationService.CreateCertificate ( System.String storeType , System.String storePath , System.String password , System.String applicationUri , System.String applicationName , System.String subjectName , System.Collections.Generic.IList ` 1 [ T ] domainNames , System.UInt16 keySize , System.DateTime startTime , System.UInt16 lifetimeInMonths , System.UInt16 hashSizeInBits , System.Boolean isCA , System.Security.Cryptography.X509Certificates.X509Certificate2 issuerCAKeyCert ) [ 0x003b5 ] in C : \projects\APP - Kopie\APP_XamarinApplication\APP\APP\APP\Models\Services\ACommunicationService.cs:517 05-28 15:19:54.963 I/mono-stdout ( 3808 ) : at APP.Models.Services.ACommunicationService.CreateCertificate ( System.String storeType , System.String storePath , System.String applicationUri , System.String applicationName , System.String subjectName , System.Collections.Generic.IList ` 1 [ T ] serverDomainNames , System.UInt16 keySize , System.UInt16 lifetimeInMonths , System.UInt16 hashSizeInBits ) [ 0x00001 ] in C : \projects\APP - Kopie\APP_XamarinApplication\APP\APP\APP\Models\Services\ACommunicationService.cs:318 05-28 15:19:54.964 I/mono-stdout ( 3808 ) : at APP.Models.Services.ACommunicationService+ < ACommunicationServiceAsync > d__18.MoveNext ( ) [ 0x00972 ] in C : \projects\APP - Kopie\APP_XamarinApplication\APP\APP\APP\Models\Services\ACommunicationService.cs:214 05-28 15:19:54.964 I/mono-stdout ( 3808 ) : -- - End of inner exception stack trace -- -05-28 15:19:54.965 I/mono-stdout ( 3808 ) : at System.Threading.Tasks.Task.ThrowIfExceptional ( System.Boolean includeTaskCanceledExceptions ) [ 0x00011 ] in < d18287e1d683419a8ec3216fd78947b9 > :0 05-28 15:19:54.965 I/mono-stdout ( 3808 ) : at System.Threading.Tasks.Task.Wait ( System.Int32 millisecondsTimeout , System.Threading.CancellationToken cancellationToken ) [ 0x00043 ] in < d18287e1d683419a8ec3216fd78947b9 > :0 05-28 15:19:54.965 I/mono-stdout ( 3808 ) : at System.Threading.Tasks.Task.Wait ( ) [ 0x00000 ] in < d18287e1d683419a8ec3216fd78947b9 > :0 at System.String.IndexOf ( System.String value , System.Int32 startIndex , System.Int32 count , System.StringComparison comparisonType ) [ 0x0002a ] in < d18287e1d683419a8ec3216fd78947b9 > :0 05-28 15:19:54.965 I/mono-stdout ( 3808 ) : at APP.Models.Services.ACommunicationService..ctor ( PCLStorage.IFolder rootFolder ) [ 0x00010 ] in C : \projects\APP - Kopie\APP_XamarinApplication\APP\APP\APP\Models\Services\ACommunicationService.cs:46 05-28 15:19:54.966 I/mono-stdout ( 3808 ) : -- - > ( Inner Exception # 0 ) System.Security.Cryptography.CryptographicException : Unable to decode certificate . -- - > System.Security.Cryptography.CryptographicException : Input data can not be coded as a valid certificate . -- - > System.ArgumentOutOfRangeException : Index was out of range . Must be non-negative and less than the size of the collection.05-28 15:19:54.966 I/mono-stdout ( 3808 ) : Parameter name : startIndex05-28 15:19:54.967 I/mono-stdout ( 3808 ) : at System.String.IndexOf ( System.String value , System.Int32 startIndex , System.Int32 count , System.StringComparison comparisonType ) [ 0x0002a ] in < d18287e1d683419a8ec3216fd78947b9 > :0 at System.String.IndexOf ( System.String value , System.Int32 startIndex , System.StringComparison comparisonType ) [ 0x00009 ] in < d18287e1d683419a8ec3216fd78947b9 > :0 at System.String.IndexOf ( System.String value , System.Int32 startIndex ) [ 0x00000 ] in < d18287e1d683419a8ec3216fd78947b9 > :0 at Mono.Security.X509.X509Certificate.PEM ( System.String type , System.Byte [ ] data ) [ 0x00030 ] in < 2940be14d5a1446694e2193e9029b558 > :0 at Mono.Security.X509.X509Certificate..ctor ( System.Byte [ ] data ) [ 0x00014 ] in < 2940be14d5a1446694e2193e9029b558 > :0 -- - End of inner exception stack trace -- - at Mono.Security.X509.X509Certificate..ctor ( System.Byte [ ] data ) [ 0x0002f ] in < 2940be14d5a1446694e2193e9029b558 > :0 at System.Security.Cryptography.X509Certificates.X509Certificate2ImplMono.Import ( System.Byte [ ] rawData , System.String password , System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags ) [ 0x0000b ] in < 1a27f8ea09e3480db932cbde0eaedfb2 > :0 -- - End of inner exception stack trace -- - at System.Security.Cryptography.X509Certificates.X509Certificate2ImplMono.Import ( System.Byte [ ] rawData , System.String password , System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags ) [ 0x00031 ] in < 1a27f8ea09e3480db932cbde0eaedfb2 > :0 at System.Security.Cryptography.X509Certificates.X509Helper2.Import ( System.Byte [ ] rawData , System.String password , System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags , System.Boolean disableProvider ) [ 0x00020 ] in < 1a27f8ea09e3480db932cbde0eaedfb2 > :0 at System.Security.Cryptography.X509Certificates.X509Certificate2.Import ( System.Byte [ ] rawData , System.String password , System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags ) [ 0x00000 ] in < 1a27f8ea09e3480db932cbde0eaedfb2 > :0 at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor ( System.Byte [ ] rawData ) [ 0x00011 ] in < 1a27f8ea09e3480db932cbde0eaedfb2 > :0 at APP.Models.Services.ACommunicationService.CreateCertificate ( System.String storeType , System.String storePath , System.String password , System.String applicationUri , System.String applicationName , System.String subjectName , System.Collections.Generic.IList ` 1 [ T ] domainNames , System.UInt16 keySize , System.DateTime startTime , System.UInt16 lifetimeInMonths , System.UInt16 hashSizeInBits , System.Boolean isCA , System.Security.Cryptography.X509Certificates.X509Certificate2 issuerCAKeyCert ) [ 0x003b5 ] in C : \projects\APP - Kopie\APP_XamarinApplication\APP\APP\APP\Models\Services\ACommunicationService.cs:517 at APP.Models.Services.ACommunicationService.CreateCertificate ( System.String storeType , System.String storePath , System.String applicationUri , System.String applicationName , System.String subjectName , System.Collections.Generic.IList ` 1 [ T ] serverDomainNames , System.UInt16 keySize , System.UInt16 lifetimeInMonths , System.UInt16 hashSizeInBits ) [ 0x00001 ] in C : \projects\APP - Kopie\APP_XamarinApplication\APP\APP\APP\Models\Services\ACommunicationService.cs:318 at APP.Models.Services.ACommunicationService+ < ACommunicationServiceAsync > d__18.MoveNext ( ) [ 0x00972 ] in C : \projects\APP - Kopie\APP_XamarinApplication\APP\APP\APP\Models\Services\ACommunicationService.cs:214 < -- -05-28 15:19:54.968 I/mono-stdout ( 3808 ) : at System.String.IndexOf ( System.String value , System.Int32 startIndex , System.StringComparison comparisonType ) [ 0x00009 ] in < d18287e1d683419a8ec3216fd78947b9 > :0 05-28 15:19:54.969 I/mono-stdout ( 3808 ) : at System.String.IndexOf ( System.String value , System.Int32 startIndex ) [ 0x00000 ] in < d18287e1d683419a8ec3216fd78947b9 > :0 05-28 15:19:54.969 I/mono-stdout ( 3808 ) : at Mono.Security.X509.X509Certificate.PEM ( System.String type , System.Byte [ ] data ) [ 0x00030 ] in < 2940be14d5a1446694e2193e9029b558 > :0 05-28 15:19:54.969 I/mono-stdout ( 3808 ) : at Mono.Security.X509.X509Certificate..ctor ( System.Byte [ ] data ) [ 0x00014 ] in < 2940be14d5a1446694e2193e9029b558 > :0 05-28 15:19:54.969 I/mono-stdout ( 3808 ) : -- - End of inner exception stack trace -- -05-28 15:19:54.969 I/mono-stdout ( 3808 ) : at Mono.Security.X509.X509Certificate..ctor ( System.Byte [ ] data ) [ 0x0002f ] in < 2940be14d5a1446694e2193e9029b558 > :0 05-28 15:19:54.969 I/mono-stdout ( 3808 ) : at System.Security.Cryptography.X509Certificates.X509Certificate2ImplMono.Import ( System.Byte [ ] rawData , System.String password , System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags ) [ 0x0000b ] in < 1a27f8ea09e3480db932cbde0eaedfb2 > :0 05-28 15:19:54.969 I/mono-stdout ( 3808 ) : -- - End of inner exception stack trace -- -05-28 15:19:54.969 I/mono-stdout ( 3808 ) : at System.Security.Cryptography.X509Certificates.X509Certificate2ImplMono.Import ( System.Byte [ ] rawData , System.String password , System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags ) [ 0x00031 ] in < 1a27f8ea09e3480db932cbde0eaedfb2 > :0 05-28 15:19:54.970 I/mono-stdout ( 3808 ) : at System.Security.Cryptography.X509Certificates.X509Helper2.Import ( System.Byte [ ] rawData , System.String password , System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags , System.Boolean disableProvider ) [ 0x00020 ] in < 1a27f8ea09e3480db932cbde0eaedfb2 > :0 05-28 15:19:54.970 I/mono-stdout ( 3808 ) : at System.Security.Cryptography.X509Certificates.X509Certificate2.Import ( System.Byte [ ] rawData , System.String password , System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags ) [ 0x00000 ] in < 1a27f8ea09e3480db932cbde0eaedfb2 > :0 05-28 15:19:54.970 I/mono-stdout ( 3808 ) : at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor ( System.Byte [ ] rawData ) [ 0x00011 ] in < 1a27f8ea09e3480db932cbde0eaedfb2 > :0 05-28 15:19:54.970 I/mono-stdout ( 3808 ) : at APP.Models.Services.ACommunicationService.CreateCertificate ( System.String storeType , System.String storePath , System.String password , System.String applicationUri , System.String applicationName , System.String subjectName , System.Collections.Generic.IList ` 1 [ T ] domainNames , System.UInt16 keySize , System.DateTime startTime , System.UInt16 lifetimeInMonths , System.UInt16 hashSizeInBits , System.Boolean isCA , System.Security.Cryptography.X509Certificates.X509Certificate2 issuerCAKeyCert ) [ 0x003b5 ] in C : \projects\APP - Kopie\APP_XamarinApplication\APP\APP\APP\Models\Services\ACommunicationService.cs:517 05-28 15:19:54.971 I/mono-stdout ( 3808 ) : at APP.Models.Services.ACommunicationService.CreateCertificate ( System.String storeType , System.String storePath , System.String applicationUri , System.String applicationName , System.String subjectName , System.Collections.Generic.IList ` 1 [ T ] serverDomainNames , System.UInt16 keySize , System.UInt16 lifetimeInMonths , System.UInt16 hashSizeInBits ) [ 0x00001 ] in C : \projects\APP - Kopie\APP_XamarinApplication\APP\APP\APP\Models\Services\ACommunicationService.cs:318 05-28 15:19:54.971 I/mono-stdout ( 3808 ) : at APP.Models.Services.ACommunicationService+ < ACommunicationServiceAsync > d__18.MoveNext ( ) [ 0x00972 ] in C : \projects\APP - Kopie\APP_XamarinApplication\APP\APP\APP\Models\Services\ACommunicationService.cs:214 < -- - var pkcsPath = pkcsStorePath + `` /pkcs.p12 '' ; File.WriteAllBytes ( pkcsPath , pfxData.ToArray ( ) ) ; // Exception is thrown on this line ( Undefined length ) : certificate = new X509Certificate2 ( pkcsPath , string.Empty ) ; 06-01 21:05:54.903 I/mono-stdout ( 31001 ) : System.Security.Cryptography.CryptographicException : Input data can not be coded as a valid certificate . -- - > System.Security.Cryptography.CryptographicException : Input data can not be coded as a valid certificate.System.Security.Cryptography.CryptographicException : Input data can not be coded as a valid certificate . -- - > System.Security.Cryptography.CryptographicException : Input data can not be coded as a valid certificate . at Mono.Security.X509.X509Certificate.Parse ( System.Byte [ ] data ) [ 0x0003b ] in < 2940be14d5a1446694e2193e9029b558 > :0 -- - End of inner exception stack trace -- - at Mono.Security.X509.X509Certificate.Parse ( System.Byte [ ] data ) [ 0x00322 ] in < 2940be14d5a1446694e2193e9029b558 > :0 at Mono.Security.X509.X509Certificate..ctor ( System.Byte [ ] data ) [ 0x00030 ] in < 2940be14d5a1446694e2193e9029b558 > :0 06-01 21:05:54.905 I/mono-stdout ( 31001 ) : at Mono.Security.X509.X509Certificate.Parse ( System.Byte [ ] data ) [ 0x0003b ] in < 2940be14d5a1446694e2193e9029b558 > :0 at System.Security.Cryptography.X509Certificates.X509Certificate2ImplMono.Import ( System.Byte [ ] rawData , System.String password , System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags ) [ 0x00041 ] in < 1a27f8ea09e3480db932cbde0eaedfb2 > :0 at System.Security.Cryptography.X509Certificates.X509Helper2.Import ( System.Byte [ ] rawData , System.String password , System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags , System.Boolean disableProvider ) [ 0x00020 ] in < 1a27f8ea09e3480db932cbde0eaedfb2 > :0 at System.Security.Cryptography.X509Certificates.X509Certificate2.Import ( System.Byte [ ] rawData , System.String password , System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags ) [ 0x00000 ] in < 1a27f8ea09e3480db932cbde0eaedfb2 > :0 at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor ( System.Byte [ ] rawData , System.String password ) [ 0x00011 ] in < 1a27f8ea09e3480db932cbde0eaedfb2 > :0 at Pkcs12TestProject.MyClass.CreateCertificate ( System.String storeType , System.String storePath , System.String password , System.String applicationUri , System.String applicationName , System.String subjectName , System.Collections.Generic.IList ` 1 [ T ] domainNames , System.UInt16 keySize , System.DateTime startTime , System.UInt16 lifetimeInMonths , System.UInt16 hashSizeInBits , System.Boolean isCA , System.Security.Cryptography.X509Certificates.X509Certificate2 issuerCAKeyCert , System.String pkcsStorePath ) [ 0x00377 ] in C : \OneDrive\VS\Pkcs12TestProject\Pkcs12TestProject\Pkcs12TestProject\MyClass.cs:223 06-01 21:05:54.906 I/mono-stdout ( 31001 ) : -- - End of inner exception stack trace -- -06-01 21:05:54.906 I/mono-stdout ( 31001 ) : at Mono.Security.X509.X509Certificate.Parse ( System.Byte [ ] data ) [ 0x00322 ] in < 2940be14d5a1446694e2193e9029b558 > :0 06-01 21:05:54.906 I/mono-stdout ( 31001 ) : at Mono.Security.X509.X509Certificate..ctor ( System.Byte [ ] data ) [ 0x00030 ] in < 2940be14d5a1446694e2193e9029b558 > :0 06-01 21:05:54.906 I/mono-stdout ( 31001 ) : at System.Security.Cryptography.X509Certificates.X509Certificate2ImplMono.Import ( System.Byte [ ] rawData , System.String password , System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags ) [ 0x00041 ] in < 1a27f8ea09e3480db932cbde0eaedfb2 > :0 06-01 21:05:54.906 I/mono-stdout ( 31001 ) : at System.Security.Cryptography.X509Certificates.X509Helper2.Import ( System.Byte [ ] rawData , System.String password , System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags , System.Boolean disableProvider ) [ 0x00020 ] in < 1a27f8ea09e3480db932cbde0eaedfb2 > :0 06-01 21:05:54.906 I/mono-stdout ( 31001 ) : at System.Security.Cryptography.X509Certificates.X509Certificate2.Import ( System.Byte [ ] rawData , System.String password , System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags ) [ 0x00000 ] in < 1a27f8ea09e3480db932cbde0eaedfb2 > :0 06-01 21:05:54.907 I/mono-stdout ( 31001 ) : at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor ( System.Byte [ ] rawData , System.String password ) [ 0x00011 ] in < 1a27f8ea09e3480db932cbde0eaedfb2 > :0 06-01 21:05:54.907 I/mono-stdout ( 31001 ) : at Pkcs12TestProject.MyClass.CreateCertificate ( System.String storeType , System.String storePath , System.String password , System.String applicationUri , System.String applicationName , System.String subjectName , System.Collections.Generic.IList ` 1 [ T ] domainNames , System.UInt16 keySize , System.DateTime startTime , System.UInt16 lifetimeInMonths , System.UInt16 hashSizeInBits , System.Boolean isCA , System.Security.Cryptography.X509Certificates.X509Certificate2 issuerCAKeyCert , System.String pkcsStorePath ) [ 0x00377 ] in C : \OneDrive\VS\Pkcs12TestProject\Pkcs12TestProject\Pkcs12TestProject\MyClass.cs:223
BouncyCastle undefined length ASN1
C_sharp : I 'm trying to close my Main Window from a child window in my WPF application . The problem is , once I try to 'close ' the main window , my whole application closes.Here is my coding from my main window ( pgLogin ) : And my child window ( pgDashboard ) : Is there a way to close the main window without hiding it and still keeping open my child window ? <code> Window nextWindow = null ; nextWindow = new pgDashboard ( ) ; nextWindow.Owner = this ; this.Hide ( ) ; nextWindow.Show ( ) ; public static T IsWindowOpen < T > ( string name = null ) where T : Window { var windows = Application.Current.Windows.OfType < T > ( ) ; return string.IsNullOrEmpty ( name ) ? windows.FirstOrDefault ( ) : windows.FirstOrDefault ( w = > w.Name.Equals ( name ) ) ; } private void HAZEDashboard_Loaded ( object sender , RoutedEventArgs e ) { var credentials = this.Owner as pgLogin ; credentials.txtEmailAddress.Text.ToString ( ) ; var window = IsWindowOpen < pgLogin > ( ) ; if ( window ! = null ) { window.Close ( ) ; } }
How to stop MainWindow from closing whole application
C_sharp : I am using the Memory Management while returning the data like below.Query - Is there any issue in placing the 'Using ' Statement while returning the data ? I am Still getting the complete schema as well as the data in the receiving function ? <code> private DataSet ReturnDs ( ) { using ( DataSet ds = new DataSet ( ) ) { return ds ; } }
Using Statement while returning data
C_sharp : This is something I 've never understood . It almost seems like a hack to create a dummy object that gets locked , like the examplefrom https : //msdn.microsoft.com/en-us/library/c5kehkcz.aspx.Why could n't the language designers make it so that would be equivalent ? <code> class Account { decimal balance ; private Object thisLock = new Object ( ) ; public void Withdraw ( decimal amount ) { lock ( thisLock ) { if ( amount > balance ) { throw new Exception ( `` Insufficient funds '' ) ; } balance -= amount ; } } } class Account { decimal balance ; public void Withdraw ( decimal amount ) { lock { if ( amount > balance ) { throw new Exception ( `` Insufficient funds '' ) ; } balance -= amount ; } } }
Why do we need to lock and object in C # ?
C_sharp : I 'm returning Streams from a remote service ( .NET Remoting ) . But Streams are also disposables which as we all know are ment to be disposed.I could call Dispose on the client side once I finished consuming those . However , I would like to know what exactly happens under the cover when I return a Stream from a remote object.Especially : Should I better read everything into a byte [ ] and return that instead of a Stream ? Or is .NET remoting doing exactly that for me under the covers anyway ? If not , how is returning a Stream different from returning a byte [ ] ? In the end , .NET Remoting must somehow serialize the data anyway ? Does calling Dispose on the client side even has any affect at all ? Is there any magical connection between the object on the client side and the object on the serverside ? I think once it 's deserialized behind the covers , there is no sense in calling Dispose ( ) on the client side or is there ? I 'm answering to Mike Bild here because I also want to improve the question a littleOk , so the stream talking back to the server is ( for me at least ) unexpected.To cosume a remote object one has to do something like this : So you are explicitly reaching out for a specific remote object at some URI to consume . And when a method on that remote object returns an object that inherits from MarshallByRefObject that means it automatically is associated with the object on the remote side ? Ok , that should be easy to reproduce with a test object I build myself . So this also means I should call Dispose on the client side and it get 's proxied back to the object on the server side ? <code> public static class ServiceFactory < T > { public static T CreateProxy ( ) { Type interfaceType = typeof ( T ) ; string uri = ApplicationServer.ServerURL + interfaceType.FullName ; return ( T ) Activator.GetObject ( interfaceType , uri ) ; } }
What happens under the cover when you return a Stream from a remote object via .NET Remoting
C_sharp : Suppose I had two classes : We have here the descriptions of two geometric shapes along with an operation in both.And here 's my attempt in F # : Suppose I made an observation about these two classes ( they both have Height ! ) and I wanted to extract an operation that made sense for anything that had a height property . So in C # I might pull out a base class and define the operation there , as follows : Note how individual subclasses might have their own ideas as to the implementation of this operation.Closer to the point , I might have a function somewhere which can accept either a Triangle or a Cylinder : .. and this function can accept either a Triangle or a Cylinder.I 'm having trouble applying the same line of thinking to F # .I 've been doing some reading about functional languages . The conventional thinking is that it is preferred to express algebraic value types rather than inherited classes . The thinking goes that it 's better to compose or build richer types out of smaller building blocks rather than starting with an abstract class and narrowing from there.In F # I want to be able to define a function which takes an argument that is known to have a Height property , and work with it somehow ( i.e . the base version of CanSuperManJumpOver ) . How should I structure these types in a functional world to achieve it ? Does my question even make sense in a functional world ? Any comments on the thinking is most welcome . <code> public class Triangle { public float Base { get ; set ; } public float Height { get ; set ; } public float CalcArea ( ) { return Base * Height / 2.0 ; } } public class Cylinder { public float Radius { get ; set ; } public float Height { get ; set ; } public float CalcVolume ( ) { return Radius * Radius * Math.PI * Height } } type Triangle = { Base : float ; Height : float } module TriangleStuff = let CalcArea t = t.Base * t.Height / 2.0type Cylinder = { Radius : float ; Height : float } module CylinderStuff = let CalcVolume c = c.Radius * c.Radius * Math.PI * c.Height public abstract class ShapeWithHeight { public float Height { get ; set ; } public virtual bool CanSuperManJumpOver ( ) { return Height == TALL ; // Superman can *only* jump over tall buildings } public const float TALL = float.MaxValue ; } public class Triangle : ShapeWithHeight { public float Base { get ; set ; } public float CalcArea ( ) { return Base * Height / 2.0 ; } public override bool CanSuperManJumpOver ( ) { throw new InvalidOperationException ( `` Superman can only jump over 3-d objects '' ) ; } } public class Cylinder : ShapeWithHeight { public float Radius { get ; set ; } public float CalcVolume ( ) { return Radius * Radius * Math.PI * Height } } public class Superman { public void JumpOver ( ShapeWithHeight shape ) { try { if ( shape.CanSuperManJumpOver ( ) ) { Jump ( shape ) ; } } catch { // ... } } }
C # to F # : Functional thinking vs. polymorphism
C_sharp : I use Noda Time , and have the following code : This results in an UnparsableValueException with the message : The local date/time is ambiguous in the target time zoneThe problem , as I understand it , is that this specific time can occur twice because of daylight saving . At 02:00 , the clock is turned back one hour to 01:00 . NodaTime does n't know which `` version '' of 01:00 that the string refers to , and because of that the exception is thrown.To me , it does n't really matter which version of the time that the parse results in , I just want to avoid the exception , and get a date that is as close to reality as possible . One hour less or more is OK. What would be the best way to do that ? The only way I can think of is splitting the string and parsing the parts individually , and then add one hour , but that feels completely wrong . Is there a better solution ? <code> var pattern = ZonedDateTimePattern.CreateWithInvariantCulture ( `` yyyy-MM-dd HH : mm : ss z '' , DateTimeZoneProviders.Tzdb ) ; var parsed = pattern.Parse ( `` 2017-11-05 01:00:00 America/Los_Angeles '' ) ; Console.WriteLine ( parsed.Value ) ;
Parsing ambiguous datetime with Noda Time
C_sharp : Consider , I have the following 3 classes / interfaces : And I want to be able to cast a MyClass < Derived > into a MyClass < IMyInterface > or visa-versa : But I get compiler errors if I try : I 'm sure there is a very good reason why I cant do this , but I ca n't think of one.As for why I want to do this - The scenario I 'm imagining is one whereby you ideally want to work with an instance of MyClass < Derived > in order to avoid lots of nasty casts , however you need to pass your instance to an interface that accepts MyClass < IMyInterface > .So my question is twofold : Why can I not cast between these two types ? Is there any way of keeping the niceness of working with an instance of MyClass < Derived > while still being able to cast this into a MyClass < IMyInterface > ? <code> class MyClass < T > { } interface IMyInterface { } class Derived : IMyInterface { } MyClass < Derived > a = new MyClass < Derived > ( ) ; MyClass < IMyInterface > b = ( MyClass < IMyInterface > ) a ; Can not convert type 'MyClass < Derived > ' to 'MyClass < IMyInterface > '
Casting generics and the generic type
C_sharp : The title is possibly worded incorrectly , so please show me the correct terms.I 've got a base class called DAL_Base that accepts a generic type T. The type T comes from our many classes in our Business Objects layer , and each one of them has a corresponding Data Access Layer.DAL_Base accepts parameters that allows me to specify the Stored Procedure names and parameters that I use to call methods to select , insert , and update records.What I currently seem to be stuck on is that I ca n't seem to find a way to instantiate a new instance of my DAL_Base , which needs to initialize the various variables.Partial listing : The error VS2010 is giving me is : Invalid token ' ( ' in class , struct , or interface member declarationI have tried creating constructors without parenthesis , but that is not useful either.When I search , all I seem to be able to return are ways to create instances of my generic type T. That was easy to find out how to do ! MSDN 's An Introduction to C # Generics did not seem to cover this , either . <code> public class DAL_Base < T > where T : IDisposable , new ( ) { public DAL_Base < T > ( ) { // < = ERROR HERE // initialize items that will be used in all derived classes } }
Create Instance of a C # Generic Class
C_sharp : I have a C # public API that is used by many third-party developers that have written custom applications on top of it . In addition , the API is used widely by internal developers.This API was n't written with testability in mind : most class methods are n't virtual and things were n't factored out into interfaces . In addition , there are some helper static methods.For many reasons I ca n't change the design significantly without causing breaking changes for applications developed by programmers using my API . However , I 'd still like to give internal and external developers using this API the chance to write unit tests and be able to mock the objects in the API.There are several approaches that come to mind , but none of them seem great : The traditional approach would be to force developers to create a proxy class that they controlled that would talk to my API . This wo n't work in practice because there are now hundreds of classes , many of which are effectively strongly typed data transfer objects that would be a pain to reproduce and maintain.Force all developers using the API that want to unit test it to buy TypeMock . This seems harsh to force people to pay $ 300+ per developer and potentially require them to learn a different mock object tool than what their used to.Go through the entire project and make all the methods virtual . This would allow mock-ing of objects using free tools like Moq or Rhino Mocks , but it could potentially open up security risks for classes that were never meant to be derived from . Additionally this could cause breaking changes.I could create a tool that given an input assembly would output an assembly with the same namespaces , classes , and members , but would make all of the methods virtual and it would make the method body just return the default value for the return type . Then , I could ship this dummy test assembly each time I released an update to the API . Developers could then write tests for the API against the dummy assembly since it had virtual members that are very mock-able . This might work , but it seems a bit tedious to write a custom tool for this and I ca n't seem to find an existing one that does it well ( especially that works well with generics ) . Furthermore , it has the complication that it requires developers to use two different assemblies that could possibly go out of date.Similar to # 4 , I could go through every file and add something like `` # ifdef UNITTEST '' to every method and body to do the equivalent of what a tool would do . This does n't require an external tool , but it would pollute the codebase with a lot of ugly `` # ifdef '' 's.Is there something else that I have n't considered that would be a good fit ? Does a tool like what I mentioned in # 4 already exist ? Again , the complicating factor is that this is a rather large API ( hundreds of classes and ~10 files ) and has existing applications using it which makes it hard to do drastic design changes.There have been several questions on Stack Overflow that were generic about retrofitting an existing application to make it testable , but none seem to address the concerns I have ( specifically in the context of a widely used API with many third-party developers ) . I 'm also aware of `` Working Effectively With Legacy Code '' and think it has good advice , but I am looking for a specific .net approach given the constraints mentioned above.UPDATE : I appreciate the answers so far . One that Patrik Hägne brought up is `` why not extract interfaces ? '' This indeed works to a point , but has some problems such as the existing design has many cases where we take expose a concrete class . For example : Existing customers that are expecting the concrete class ( e.g . `` UserData '' ) would break if they were given an `` IUserData . '' Additionally , as mentioned in the comments there are cases where we take in a class and then expose it for convenience . This could cause problems if we took in an interface and then had to expose it as a concrete class.The biggest challenge to a significant rewrite or redesign is that there is a huge investment in the current API ( thousands of hours of development and probably just as much third party training ) . So , while I agree that a better SOLID design rewrite or abstraction layer ( that eventually could become the new API ) that focused on items like the Interface Separation Principle would be a plus from a testability perspective , it 'd be a large undertaking that probably ca n't be cost justified at the present time.We do have testing for the current API , but it is more complicated integration testing rather than unit-testing . Additionally , as mentioned by Chad Myers , this is question addresses a similar problem that the .NET framework itself faces in some areas.I realize that I 'm probably looking for a `` silver bullet '' here that does n't exist , but all help is appreciated . The important part is protecting the huge time investments by many third party developers as well as the huge existing development to create the current API.All answers , especially those that consider the business side of the problem , will be carefully reviewed . Thanks ! <code> public class UserRepository { public UserData GetData ( string userName ) { ... } }
How to make an existing public API testable for external programmers using it ?
C_sharp : Say I have the following : I 'd like to parameterize the tests using the TestCase/TestCaseSource attribute including the call itself . Due to the repetitive nature of the tests , each method needs to be called with slightly different parameters , but I need to be able to tag a different call for each of the different parameters . Is this even possible in Nunit ? If so , how would I go about it ? <code> [ Test ] // would like to parameterize the parameters in call AND the call itself public void Test ( ) { var res1 = _sut.Method1 ( 1 ) ; var res2 = _sut.Method2 ( `` test '' ) ; var res3 = _sit.Method3 ( 3 ) ; Assert.That ( res1 , Is.Null ) ; Assert.That ( res2 , Is.Null ) ; Assert.That ( res3 , Is.Null ) ; }
Is there a way to run a list of different action methods on an object in Nunit using TestCase ?
C_sharp : I know that generics are used to achieve type safety and i frequently read that they are largely used in custom collections . But why actually do we need to have them generic ? For example , Why ca n't I use string [ ] instead of List < string > ? Let 's consider I declare a generic class and it has a generic type parameter X.If I provide a method for the class which does What does it mean actually ? I do n't know what T is actually going to be and I do n't know what x = x + 1 going to perform actually.If I 'm not able to do my own manipulations in my methods , how the generics are going to help me anyway ? I 've already studied lot of bookish answers . It would be much appreciated if any one can provide some clear insights in this.Regards , NLV <code> T x ; x = x + 1 ;
'Why ' and 'Where ' Generics is actually used ?
C_sharp : I can have a nested contracts type for a non-generic interface : But it complains when I try to do the same thing with a generic interface : The warning is : The contract class Foo+FooContracts ` 1 and the type IFoo ` 1 must have the same declaring type if any.It compiles without a warning if I get FooContracts out of the Foo class.Why does that limitation exist for generic interfaces ? Why does n't that limitation exist for non-generic ones ? <code> [ ContractClass ( typeof ( Foo.FooContracts ) ) ] public interface IFoo { string Bar ( object obj ) ; } [ ContractClass ( typeof ( Foo.FooContracts < > ) ) ] public interface IFoo < T > { string Bar ( T obj ) ; }
Nested contracts for generic interfaces
C_sharp : Usually , treating a struct S as an interface I will trigger autoboxing of the struct , which can have impacts on performance if done often . However , if I write a generic method taking a type parameter T : I and call it with an S , then will the compiler omit the boxing , since it knows the type S and does not have to use the interface ? This code shows my point : The doFoo method calls foo ( ) on an object of type I , so once we call it with an S , that S will get boxed . The doFooGeneric method does the same thing . However , once we call it with an S , no autoboxing might be required , since the runtime knows how to call foo ( ) on an S. But will this be done ? Or will the runtime blindly box S to an I to call the interface method ? <code> interface I { void foo ( ) ; } struct S : I { public void foo ( ) { /* do something */ } } class Y { void doFoo ( I i ) { i.foo ( ) ; } void doFooGeneric < T > ( T t ) where T : I { t.foo ( ) ; // < -- - Will an S be boxed here ? ? } public static void Main ( string [ ] args ) { S x ; doFoo ( x ) ; // x is boxed doFooGeneric ( x ) ; // x is not boxed , at least not here , right ? } }
Do C # generics prevent autoboxing of structs in this case ?
C_sharp : for example : why do we have to add that M ? why not just do : since it already says decimal , doesnt it imply that 25.50 is a decimal ? <code> const decimal dollars = 25.50M ; const decimal dollars = 25.50 ;
what is the purpose of double implying ?
C_sharp : I am wondering if there is a way to create a concatenated WHERE clause using an array of int . I need to get the results for the entire array combined . Can I do something like : <code> public ViewResult Results ( int ? programId , int ? programYear , int ? programTypeId , string toDate , string fromDate , int ? [ ] programTypeIdList , int ? [ ] programIdList ) { surveyResponseRepository.Get ( ) .Any ( x = > x.ProgramId == programIdList ) ; }
Concatenated Where clause with array of strings
C_sharp : I have this piece of code ( well I have the issue everywhere ) When I debug this , break in the funcion , try to watch some variables . And I keep getting a FileNotFoundExceptionBut the `` missing '' DLL is in the folder , it 's not readonly or any other flags Windows has . <code> public void PayrollActivityCodeTest ( ) { using ( var pr = new ActivityCodeProcess ( ) ) { pr.Add ( ) ; pr.WorkingEntity.PayrollConfiguration.Provinces = PayrollProvincesType.QC | PayrollProvincesType.ON ; pr.WorkingEntity.ActivityCodeId = `` 01 '' ; //pr.WorkingEntity.Rates.CodeByProvinceCollection.First ( ) .CodeValueCollection.FirstOrDefault ( ) .Value Assert.AreEqual ( 2 , pr.WorkingEntity.Rates.CodeByProvinceCollection.Count ) ; } }
FileNotFoundException while watching variables in debug mode
C_sharp : What is the point of writing an interface without members ? INamingContainer is one example in .NET Framework . And it 's described in MSDN as : Identifies a container control that creates a new ID namespace within a Page object 's control hierarchy . This is a marker interface only.Is it used for just this kind of blocks : Or are there other advantages of it ? EDIT : It was called Marker Interface Pattern ( thanks Preet ) <code> if ( myControl is INamingContainer ) { // do something }
Why do we use memberless interface ?
C_sharp : I have n't found a case that fail this condition.So why and when should I use the Marshal method instead of simply getting the GUID property ? <code> Type classType = typeof ( SomeClass ) ; bool equal = Marshal.GenerateGuidForType ( classType ) == classType.GUID ;
What 's the difference between Marshal.GenerateGuidForType ( Type ) and Type.GUID ?
C_sharp : How can a C # program detect it is being compiled under a version of C # that does not contain support for the language features used in that program ? The C # compiler will reject the program , and produce some error message , on encountering the features of the language it does not support . This does not address the issue , which is to state that the program is being compiled with too old a version of the C # compiler , or a C # compiler that does not support the required version of C # Ideally , it would be as simple as <code> # if CS_VERSION < 3 # error CSharp 3 or later is required # end
How can compilation of C # code be made to require a given language or compiler version ?
C_sharp : I am using UpdatePanel for asp.net Controls . So , to validate it I am using jquery onEachRequest . It is also working fine.But , main issue is that It stops executing postback of DropDownList . Means , It does not postback to retrive data.My Code : How to solve this issue ? <code> function onEachRequest ( sender , args ) { if ( $ ( `` # form1 '' ) .valid ( ) ==false ) { args.set_cancel ( true ) ; } } function pageLoad ( ) { $ ( ' # < % = btnPayment.ClientID % > ' ) .click ( function ( ) { $ ( `` # form1 '' ) .validate ( { rules : { < % =txtName.UniqueID % > : { required : true } } , messages : { < % =txtName.UniqueID % > : { required : `` Please enter Name . '' } } } ) ; var prm = Sys.WebForms.PageRequestManager.getInstance ( ) ; prm.add_initializeRequest ( onEachRequest ) ; } ) ; }
jQuery Validation with Update Panel C #
C_sharp : LINQ 's AsParallel returns ParallelQuery . I wonder if it 's possible to change this behavior so that I could compare the LINQ statement run with and without parallelism without actually changing the code ? This behavior should be similar to Debug.Assert - when DEBUG preprocessor directive is not set , it 's optimized out . So I 'd like to be able to make AsParallel return the same type without converting it to ParallelQuery . I suppose I can declare my own extension method ( because I ca n't override AsParallel ) and have that preprocessor directive analyzed within it : I wonder if there is any other way . Am I asking for too much ? <code> public static class MyExtensions { # if TURN_OFF_LINQ_PARALLELISM public static IEnumerable < T > AsControllableParallel < T > ( this IEnumerable < T > enumerable ) { return enumerable ; } # else public static ParallelQuery < T > AsControllableParallel < T > ( this IEnumerable < T > enumerable ) { return enumerable.AsParallel ( ) ; } # endif }
LINQ : How to modify the return type of AsParallel depending on a context ?
C_sharp : This might get closed , but I 'll try anyway.I was showing a VB6 programmer some of my C # code the other day and he noticed the var keyword and was like `` Oh a variant type , that 's not really strong typing when you do that . '' and I had to go on the typical `` var ! = VARIANT '' speech to explain to him that it is not a variant it just compiler inferred . I was thinking about other words they ( C # team ) could have used so this kind of thing did n't happen . I personally like infer , something like : I know this is not really that big of deal , but just curious to see what other people would use to do the same thing.I have made this a community wiki because it does n't really have an answer . <code> infer person = new Person ( `` Bob '' ) ;
Better word for inferring variables other than var
C_sharp : The next 2 lines adds the same amount to the same date , and the results date part is the same , but somehow the there 's difference in the time part ! you 'll get a difference of 15 secs , and with both are at least roundable to days , I do n't know why this happend , but it happens only with AddDays , but not AddMonths ( even with thousands of months added ) Edit 1So I 've tried to make a sample project , but no luck . If I run my main project , and put the sample lines into the watches , than I get 2 separate values , if I make a fresh start , the problem is not there . The project is 3.5 , c # , vs2010 , win7hp x64 ( proj : x86 ) . I 'm trying to reproduce it also in a fresh small project , I 'll be writing back if I have it.These are my results in the main project ( copeid from watches ! ) : Edit 2I 've managed to narrow it down even more . We have a self-made component , panel base , we draw on it with directx . If I make that visible=false , than visible=true , than the error comes , before the visible=true ( or show ( ) ) , the calculation is correct . What in the world can be there , that the result gets something else of a formula where no variable is used . Culture is not affected in the component.. <code> ( new DateTime ( 2000,1,3,18,0,0 ) ) .AddDays ( 4535 ) ; ( new DateTime ( 2000,1,3,18,0,0 ) ) .AddMonths ( 149 ) ; ( new DateTime ( 2000 , 1 , 3 , 18 , 0 , 0 ) ) .AddDays ( 4535 ) .Ticks 634743432153600000 long ( new DateTime ( 2000 , 1 , 3 , 18 , 0 , 0 ) ) .AddMonths ( 149 ) .Ticks 634743432000000000 long
.NET AddDays issue
C_sharp : In java , we can override or implement abstract methods upon instance creation as follows : Is this possible in C # ? if Yes , what 's the equivalent codeThanks <code> AbstractClass test =new AbstractClass ( ) { public void AbstractMethod ( string i ) { } public void AbstractMethod2 ( string i ) { } } ;
Override abstract method upon instance creation in c #
C_sharp : I 've known for a long time that the first statement is incorrect , but it has always bugged me . I 've verified that bar is not null , so why does the compiler complain ? <code> int foo ; int ? bar ; if ( bar ! = null ) { foo = bar ; // does not compile foo = ( int ) bar ; // compiles foo = bar.Value ; // compiles }
Why is an explicit conversion required after checking for null ?
C_sharp : The article states the following : http : //msdn.microsoft.com/en-us/library/dd799517.aspxVariance does not apply to delegate combination . That is , given two delegates of types Action < Derived > and Action < Base > ( Action ( Of Derived ) and Action ( Of Base ) in Visual Basic ) , you can not combine the second delegate with the first although the result would be type safe . Variance allows the second delegate to be assigned to a variable of type Action < Derived > , but delegates can combine only if their types match exactly . In the above code baction and daction take different parameters . But still I am able to combine them.What am I missing ? TIA . <code> Action < B > baction = ( taret ) = > { Console.WriteLine ( taret.GetType ( ) .Name ) ; } ; Action < D > daction = baction ; Action < D > caction = baction + daction ;
Combining delegates and contravariance
C_sharp : in C # it is possible to apply an attribute to the return of a method : Is this possible in F # ? Background : I would like a method of a library written in F # which will be consumed in a language like C # to return `` dynamic '' from a method . If I look into a similarly defined method compiled from C # it seems like the return type is object and the DynamicAttribute is applied to the return value of the object . <code> [ return : DynamicAttribute ] public object Xyz ( ) { return new ExpandoObject ( ) ; }
Apply attribute to return value - In F #
C_sharp : I 've searched a bit about type inference , but I ca n't seem to apply any of the solutions to my particular problem.I 'm doing a lot of work with building and passing around functions . This seems to me like it should be able to infer the int type . The only thing I can think of is that the lambda return type is n't checked by the type inference algorithm . I have stripped unnecessary logic to show the issue more clearly.this compiles : but this gives the error `` The type arguments for method can not be inferred from the usage . Try specifying the type arguments explicitly '' : I guess I would just like to know why it works this way and any workarounds . <code> Func < T > Test < T > ( Func < Func < T > > func ) { return func ( ) ; } Func < int > x = Test < int > ( ( ) = > { int i = 0 ; return ( ) = > i ; } ) ; Func < int > x = Test ( ( ) = > { int i = 0 ; return ( ) = > i ; } ) ;
Type inference on nested generic functions
C_sharp : I 'm reading a lossy bit stream and I need a way to recover as much usable data as possible . There can be 1 's in place of 0 's and 0 's in palce of 1 's , but accuracy is probably over 80 % .A bonus would be if the algorithm could compensate for missing/too many bits as well.The source I 'm reading from is analogue with noise ( microphone via FFT ) , and the read timing could vary depending on computer speed.I remember reading about algorithms used in CD-ROM 's doing this in 3 ? layers , so I 'm guessing using several layers is a good option . I do n't remember the details though , so if anyone can share some ideas that would be great ! : ) Edit : Added sample dataEdit2 : I am able to controll the data being sent . Currently attempting to implement simple XOR checking ( though it wo n't be enough ) . <code> Best case data : in : 0000010101000010110100101101100111000000100100101101100111000000100100001100000010000101110101001101100111000101110000001001111011001100110000001001100111011110110101011100111011000100110000001000010111out : 0010101000010110100101101100111000000100100101101100111000000100100001100000010000101110101001101100111000101110000001001111011001100110000001001100111011110110101011100111011000100110000001000010111011Bade case ( timing is off , samples are missing ) : out : 00101010000101101001011011001110000001001001011011001110000001001000011000000100001011101010011011001 in : 00111101001011111110010010111111011110000010010000111000011101001101111110000110111011110111111111101
Redundancy algorithm for reading noisy bitstream
C_sharp : I find that using the following : is easier to write and understand than : Are there compelling reasons not to use the first construct ? <code> TreeViewItem i = sender as TreeViewItem ; if ( i ! = null ) { ... } if ( sender.GetType ( ) == typeof ( TreeViewItem ) ) { TreeViewItem i = ( TreeViewItem ) sender ; ... }
Are there compelling reasons AGAINST using the C # keyword `` as '' ?
C_sharp : My task is to get directory icons using tasks and display them in a DataGridView ( I 'm performing search through folders ) . For this , I use the SHGetImageList WinAPI function . I have a helper class as the following : On a form I have two DataGridViews and two buttons . On a click of the first button , I load icons in the UI thread : On the second button click , I do : So , I do the same , but in a task.When I click the first button and then the second one , I 'm getting the following System.InvalidCastException : Unable to cast COM object of type 'System.__ComObject ' to interface type 'IImageList ' . This operation failed because the QueryInterface call on the COM component for the interface with IID ' { 46EB5926-582E-4017-9FDF-E8998DAA0950 } ' failed due to the following error : No such interface supported ( Exception from HRESULT : 0x80004002 ( E_NOINTERFACE ) ) .The exception is raised in the line of the GetSystemImageListHandle method.I ca n't figure out what I 'm doing wrong . Any help is appreciated . <code> using System ; using System.Collections.Generic ; using System.Drawing ; using System.IO ; using System.Linq ; using System.Runtime.InteropServices ; using System.Text ; using System.Threading.Tasks ; namespace WindowsFormsApplication6 { public class Helper { private const uint ILD_TRANSPARENT = 0x00000001 ; private const uint SHGFI_SYSICONINDEX = 0x000004000 ; private const uint SHGFI_ICON = 0x000000100 ; public static readonly int MaxEntitiesCount = 80 ; public static void GetDirectories ( string path , List < Image > col , IconSizeType sizeType , Size itemSize ) { DirectoryInfo dirInfo = new DirectoryInfo ( path ) ; DirectoryInfo [ ] dirs = dirInfo.GetDirectories ( `` * '' , SearchOption.TopDirectoryOnly ) ; for ( int i = 0 ; i < dirs.Length & & i < MaxEntitiesCount ; i++ ) { DirectoryInfo subDirInfo = dirs [ i ] ; if ( ! CheckAccess ( subDirInfo ) || ! MatchFilter ( subDirInfo.Attributes ) ) { continue ; } col.Add ( GetFileImage ( subDirInfo.FullName , sizeType , itemSize ) ) ; } } public static bool CheckAccess ( DirectoryInfo info ) { bool isOk = false ; try { var secInfo = info.GetAccessControl ( ) ; isOk = true ; } catch { } return isOk ; } public static bool MatchFilter ( FileAttributes attributes ) { return ( attributes & ( FileAttributes.Hidden | FileAttributes.System ) ) == 0 ; } public static Image GetFileImage ( string path , IconSizeType sizeType , Size itemSize ) { return IconToBitmap ( GetFileIcon ( path , sizeType , itemSize ) , sizeType , itemSize ) ; } public static Image IconToBitmap ( Icon ico , IconSizeType sizeType , Size itemSize ) { if ( ico == null ) { return new Bitmap ( itemSize.Width , itemSize.Height ) ; } return ico.ToBitmap ( ) ; } public static Icon GetFileIcon ( string path , IconSizeType sizeType , Size itemSize ) { SHFILEINFO shinfo = new SHFILEINFO ( ) ; IntPtr retVal = SHGetFileInfo ( path , 0 , ref shinfo , ( uint ) Marshal.SizeOf ( shinfo ) , ( int ) ( SHGFI_SYSICONINDEX | SHGFI_ICON ) ) ; int iconIndex = shinfo.iIcon ; IImageList iImageList = ( IImageList ) GetSystemImageListHandle ( sizeType ) ; IntPtr hIcon = IntPtr.Zero ; if ( iImageList ! = null ) { iImageList.GetIcon ( iconIndex , ( int ) ILD_TRANSPARENT , ref hIcon ) ; } Icon icon = null ; if ( hIcon ! = IntPtr.Zero ) { icon = Icon.FromHandle ( hIcon ) .Clone ( ) as Icon ; DestroyIcon ( shinfo.hIcon ) ; } return icon ; } private static IImageList GetSystemImageListHandle ( IconSizeType sizeType ) { IImageList iImageList = null ; Guid imageListGuid = new Guid ( `` 46EB5926-582E-4017-9FDF-E8998DAA0950 '' ) ; int ret = SHGetImageList ( ( int ) sizeType , ref imageListGuid , ref iImageList ) ; return iImageList ; } [ DllImport ( `` shell32.dll '' , CharSet = CharSet.Auto ) ] private static extern IntPtr SHGetFileInfo ( string pszPath , uint dwFileAttributes , ref SHFILEINFO psfi , uint cbFileInfo , uint uFlags ) ; [ DllImport ( `` shell32.dll '' , EntryPoint = `` # 727 '' ) ] private static extern int SHGetImageList ( int iImageList , ref Guid riid , ref IImageList ppv ) ; [ DllImport ( `` user32.dll '' , SetLastError = true ) ] private static extern bool DestroyIcon ( IntPtr hIcon ) ; public enum IconSizeType { Medium = 0x0 , Small = 0x1 , Large = 0x2 , ExtraLarge = 0x4 } [ StructLayout ( LayoutKind.Sequential , CharSet = CharSet.Auto ) ] private struct SHFILEINFO { public IntPtr hIcon ; public int iIcon ; public uint dwAttributes ; [ MarshalAs ( UnmanagedType.ByValTStr , SizeConst = 260 ) ] public string szDisplayName ; [ MarshalAs ( UnmanagedType.ByValTStr , SizeConst = 80 ) ] public string szTypeName ; } [ ComImport , Guid ( `` 46EB5926-582E-4017-9FDF-E8998DAA0950 '' ) , InterfaceType ( ComInterfaceType.InterfaceIsIUnknown ) ] private interface IImageList { [ PreserveSig ] int Add ( IntPtr hbmImage , IntPtr hbmMask , ref int pi ) ; [ PreserveSig ] int ReplaceIcon ( int i , IntPtr hicon , ref int pi ) ; [ PreserveSig ] int SetOverlayImage ( int iImage , int iOverlay ) ; [ PreserveSig ] int Replace ( int i , IntPtr hbmImage , IntPtr hbmMask ) ; [ PreserveSig ] int AddMasked ( IntPtr hbmImage , int crMask , ref int pi ) ; [ PreserveSig ] int Draw ( ref IMAGELISTDRAWPARAMS pimldp ) ; [ PreserveSig ] int Remove ( int i ) ; [ PreserveSig ] int GetIcon ( int i , int flags , ref IntPtr picon ) ; [ PreserveSig ] int GetImageInfo ( int i , ref IMAGEINFO pImageInfo ) ; [ PreserveSig ] int Copy ( int iDst , IImageList punkSrc , int iSrc , int uFlags ) ; [ PreserveSig ] int Merge ( int i1 , IImageList punk2 , int i2 , int dx , int dy , ref Guid riid , ref IntPtr ppv ) ; [ PreserveSig ] int Clone ( ref Guid riid , ref IntPtr ppv ) ; [ PreserveSig ] int GetImageRect ( int i , ref RECT prc ) ; [ PreserveSig ] int GetIconSize ( ref int cx , ref int cy ) ; [ PreserveSig ] int SetIconSize ( int cx , int cy ) ; [ PreserveSig ] int GetImageCount ( ref int pi ) ; [ PreserveSig ] int SetImageCount ( int uNewCount ) ; [ PreserveSig ] int SetBkColor ( int clrBk , ref int pclr ) ; [ PreserveSig ] int GetBkColor ( ref int pclr ) ; [ PreserveSig ] int BeginDrag ( int iTrack , int dxHotspot , int dyHotspot ) ; [ PreserveSig ] int EndDrag ( ) ; [ PreserveSig ] int DragEnter ( IntPtr hwndLock , int x , int y ) ; [ PreserveSig ] int DragLeave ( IntPtr hwndLock ) ; [ PreserveSig ] int DragMove ( int x , int y ) ; [ PreserveSig ] int SetDragCursorImage ( ref IImageList punk , int iDrag , int dxHotspot , int dyHotspot ) ; [ PreserveSig ] int DragShowNolock ( int fShow ) ; [ PreserveSig ] int GetDragImage ( ref POINT ppt , ref POINT pptHotspot , ref Guid riid , ref IntPtr ppv ) ; [ PreserveSig ] int GetItemFlags ( int i , ref int dwFlags ) ; [ PreserveSig ] int GetOverlayImage ( int iOverlay , ref int piIndex ) ; } ; [ StructLayout ( LayoutKind.Sequential ) ] private struct IMAGELISTDRAWPARAMS { public int cbSize ; public IntPtr himl ; public int i ; public IntPtr hdcDst ; public int x ; public int y ; public int cx ; public int cy ; public int xBitmap ; public int yBitmap ; public int rgbBk ; public int rgbFg ; public int fStyle ; public int dwRop ; public int fState ; public int Frame ; public int crEffect ; } [ StructLayout ( LayoutKind.Sequential ) ] private struct IMAGEINFO { public IntPtr hbmImage ; public IntPtr hbmMask ; public int Unused1 ; public int Unused2 ; public RECT rcImage ; } [ StructLayout ( LayoutKind.Sequential ) ] public struct RECT { public int Left , Top , Right , Bottom ; public RECT ( int l , int t , int r , int b ) { Left = l ; Top = t ; Right = r ; Bottom = b ; } public RECT ( Rectangle r ) { Left = r.Left ; Top = r.Top ; Right = r.Right ; Bottom = r.Bottom ; } public Rectangle ToRectangle ( ) { return Rectangle.FromLTRB ( Left , Top , Right , Bottom ) ; } public void Inflate ( int width , int height ) { Left -= width ; Top -= height ; Right += width ; Bottom += height ; } public override string ToString ( ) { return string.Format ( `` x : { 0 } , y : { 1 } , width : { 2 } , height : { 3 } '' , Left , Top , Right - Left , Bottom - Top ) ; } } [ System.Runtime.InteropServices.StructLayout ( System.Runtime.InteropServices.LayoutKind.Sequential ) ] public struct POINT { public int X , Y ; public POINT ( int x , int y ) { this.X = x ; this.Y = y ; } public POINT ( Point pt ) { this.X = pt.X ; this.Y = pt.Y ; } public Point ToPoint ( ) { return new Point ( X , Y ) ; } } } } private void button1_Click ( object sender , EventArgs e ) { List < Image > list = new List < Image > ( ) ; Helper.GetDirectories ( fPath , list , Helper.IconSizeType.Small , new Size ( 16 , 16 ) ) ; dataGridView1.DataSource = list ; } private void button2_Click ( object sender , EventArgs e ) { Func < object , List < Image > > a = null ; a = ( p ) = > { string path = ( string ) p ; List < Image > list = new List < Image > ( ) ; Helper.GetDirectories ( path , list , Helper.IconSizeType.Small , new Size ( 16 , 16 ) ) ; return list ; } ; Task.Factory.StartNew ( a , fPath ) .ContinueWith ( t = > { dataGridView2.DataSource = t.Result ; } , TaskScheduler.FromCurrentSynchronizationContext ( ) ) ; } int ret = SHGetImageList ( ( int ) sizeType , ref imageListGuid , ref iImageList ) ;
Getting directory icons using tasks
C_sharp : Let 's say I have a disposable object MyDisposable whom take as a constructor parameter another disposable object.Assuming myDisposable do n't dispose the AnotherDisposable inside it 's dispose method.Does this only dispose correctly myDisposable ? or it dispose the AnotherDisposable too ? <code> using ( MyDisposable myDisposable= new MyDisposable ( new AnotherDisposable ( ) ) ) { //whatever }
Does the using statement dispose only the first variable it create ?
C_sharp : I 've switched to C # 8 on one of my projects . And I 've been moving all of my switch statements to expressions . However I found out that my project started working differently and I 've found out that it was because of the switch expression . Lets get this code for exampleI 've wrote the result as a comment , but tl ; dr when classic switch is used casting the value returns the value in the expected Type , but when switch expression is used it returns type of `` Double '' , resulting to different byte [ ] when getting the bytes of the value.What 's the difference between the two ? What do I miss ? <code> class Program { public enum DataType { Single , Double , UInt16 , UInt32 , UInt64 , Int16 , Int32 , Int64 , Byte } static void Main ( string [ ] args ) { dynamic value1 = 5 ; dynamic value2 = 6 ; var casted = CastToType ( value1 , DataType.Int16 ) ; var casted1 = CastToTypeExpression ( value2 , DataType.Int16 ) ; var type = casted.GetType ( ) ; // Int16 var type1 = casted1.GetType ( ) ; // Double var bytes = BitConverter.GetBytes ( casted ) ; // byte arr with 2 el = > [ 5 , 0 ] < - expected behavior var bytes1 = BitConverter.GetBytes ( casted1 ) ; // byte arr with 8 el = > [ 0 , 0 , 0 , 0 , 0 , 0 , 24 , 64 ] } public static dynamic CastToType ( dynamic value , DataType type ) { switch ( type ) { case DataType.Byte : return ( byte ) value ; case DataType.Double : return ( double ) value ; case DataType.Int16 : return ( short ) value ; case DataType.Int32 : return ( int ) value ; case DataType.Int64 : return ( long ) value ; case DataType.Single : return ( float ) value ; case DataType.UInt16 : return ( ushort ) value ; case DataType.UInt32 : return ( uint ) value ; case DataType.UInt64 : return ( ulong ) value ; default : throw new InvalidCastException ( ) ; } } public static dynamic CastToTypeExpression ( dynamic value , DataType type ) { return type switch { DataType.Byte = > ( byte ) value , DataType.Double = > ( double ) value , DataType.Int16 = > ( short ) value , DataType.Int32 = > ( int ) value , DataType.Int64 = > ( long ) value , DataType.Single = > ( float ) value , DataType.UInt16 = > ( ushort ) value , DataType.UInt32 = > ( uint ) value , DataType.UInt64 = > ( ulong ) value , _ = > throw new InvalidCastException ( ) , } ; } }
C # Switch expressions returning different result
C_sharp : I ’ ve got a weird intermittent issue with MVC4 / IIS / Forms Authentication . I ’ ve got a pair of sites that pass control to each other using SSO . Most of the time the handover occurs correctly and the user is redirected to the next site as intended . However , in some cases , the user is asked to log in again , even though valid SSO information was sent across . The SSO method is decorated with the [ AllowAnonymous ] attribute and the web.config also has a location entry granting access to /account/sso to all users . It appears to occur when the destination site is being hit for the first time - once the app pool is warmed up , the issue disappears . Some other points : 1 both sites are .net 4 , so there should not be any legacy encryption issues . 2. this issue happens quite rarely ( < 10 % of the time ) so the code itself should be sound 3 . Hosting is IIS 7.5 on win7x64 locally , and azure - happens in both places 4 . Seems to be browser independentAny ideas ? <code> < location path= '' account/sso '' > < system.web > < authorization > < allow users= '' * '' / > < /authorization > < /system.web > < /location > [ Authorize ] public class AccountController : BaseControllerTestable { public AccountController ( ) : base ( ) { } [ AllowAnonymous ] public ActionResult SSO ( string AuthToken , string Target ) { //SSO logic here } }
MVC4 / IIS / Forms Authentication SSO issue
C_sharp : I have a chunk of code where sometimes I need to create a new generic type , but with an unknown number of generic parameters . For example : The problem is that if I have more than one Type in my array , then the program will crash . In the short term I have come up with something like this as a stop-gap.This does work , and is easy enough to cover my scenarios , but it seems really hacky . Is there a better way to handle this ? <code> public object MakeGenericAction ( Type [ ] types ) { return typeof ( Action < > ) .MakeGenericType ( paramTypes ) ; } public object MakeGenericAction ( Type [ ] types ) { if ( types.Length == 1 ) { return typeof ( Action < > ) .MakeGenericType ( paramTypes ) ; } else if ( types.Length ==2 ) { return typeof ( Action < , > ) .MakeGenericType ( paramTypes ) ; } ... .. And so on ... . }
Making Generics with many types
C_sharp : I quite often write code that copies member variables to a local stack variable in the belief that it will improve performance by removing the pointer dereference that has to take place whenever accessing member variables.Is this valid ? For exampleMy thinking is that DoSomethingPossiblyFaster is actually faster than DoSomethingPossiblySlower . I know this is pretty much a micro optimisation , but it would be useful to have a definitive answer.EditJust to add a little bit of background around this . Our application has to process a lot of data coming from telecom networks , and this method is likely to be called about 1 billion times a day for some of our servers . My view is that every little helps , and sometimes all I am trying to do is give the compiler a few hints . <code> public class Manager { private readonly Constraint [ ] mConstraints ; public void DoSomethingPossiblyFaster ( ) { var constraints = mConstraints ; for ( var i = 0 ; i < constraints.Length ; i++ ) { var constraint = constraints [ i ] ; // Do something with it } } public void DoSomethingPossiblySlower ( ) { for ( var i = 0 ; i < mConstraints.Length ; i++ ) { var constraint = mConstraints [ i ] ; // Do something with it } } }
In C # , does copying a member variable to a local stack variable improve performance ?
C_sharp : When I scroll vertical scrollbar , DataGrid automatically expands column width if content in new visible rows is bigger and exceeds previous column width . It 's OK.But if all bigger rows are scrolled over and new visible ones have small content width , DataGrid does not decrease column width . Is there a way to archieve this ? Attached behaviour implementation will be great.Code behing : XAML : <code> public partial class MainWindow { public MainWindow ( ) { InitializeComponent ( ) ; var persons = new List < Person > ( ) ; for ( var i = 0 ; i < 20 ; i++ ) persons.Add ( new Person ( ) { Name = `` Coooooooooooooool '' , Surname = `` Super '' } ) ; for ( var i = 0 ; i < 20 ; i++ ) persons.Add ( new Person ( ) { Name = `` Cool '' , Surname = `` Suuuuuuuuuuuuuuper '' } ) ; for ( var i = 0 ; i < 20 ; i++ ) persons.Add ( new Person ( ) { Name = `` Coooooooooooooool '' , Surname = `` Super '' } ) ; DG.ItemsSource = persons ; } public class Person { public string Name { get ; set ; } public string Surname { get ; set ; } } } < Window x : Class= '' WpfApp4.MainWindow '' xmlns= '' 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 '' Title= '' MainWindow '' Width= '' 400 '' Height= '' 200 '' mc : Ignorable= '' d '' > < Grid > < DataGrid x : Name= '' DG '' CanUserAddRows= '' False '' CanUserDeleteRows= '' False '' CanUserReorderColumns= '' False '' CanUserResizeColumns= '' False '' CanUserResizeRows= '' False '' CanUserSortColumns= '' False '' / > < /Grid > < /Window >
WPF DataGrid : reduce column width to fit its content while scrolling
C_sharp : which one is better from following optionsIs one using statement is enough ? Option 1 : Option 2 : <code> using ( SqlConnection con = new SqlConnection ( constring ) ) { using ( SqlCommand cmd = new SqlCommand ( ) ) { ... ... ... ... ... ... ... ... . ... ... ... ... ... ... ... ... . ... ... ... ... ... ... ... ... . } } using ( SqlConnection con = new SqlConnection ( constring ) ) { SqlCommand cmd = new SqlCommand ( ) ; ... ... ... ... ... ... ... ... . ... ... ... ... ... ... ... ... . ... ... ... ... ... ... ... ... . }
C # using keyword , Proper use of it
C_sharp : I am making a WPF user control and I want similar behavior as DataGrid control in sense of binding . My question is : How does DataGrid know how to bind to any collection of type IEnumerable ? For example : You can pass a DataView as ItemsSource , and you can also pass any object collection . How DataGrid decides whether to bind to a column of DataView , or to a property of object only by looking at this : Thanks in advance . <code> < DataGridTextColumn Binding= '' { Binding **Path=SomePropertyOrColumn** } '' / >
How does DataGrid bind to properties of any collection ?
C_sharp : I have implemented a custom state `` blocked '' that moves into the enqueued state after certain external requirements have been fulfilled . Sometimes these external requirements are never fulfilled which causes the job to be stuck in the blocked state . What I 'd like to have is for jobs in this state to automatically expire after some configurable time.Is there any support for such a requirement ? There is the ExpirationDate field , but from looking at the code it seems to be only used for final states . The state is as simple as can be : and is used simply as _hangfireBackgroundJobClient.Create ( ( ) = > Console.WriteLine ( `` hello world '' ) , new BlockedState ( ) ) ; At a later stage it is then moved forward via _hangfireBackgroundJobClient.ChangeState ( jobId , new EnqueuedState ( ) , BlockedState.STATE_NAME ) <code> internal sealed class BlockedState : IState { internal const string STATE_NAME = `` Blocked '' ; public Dictionary < string , string > SerializeData ( ) { return new Dictionary < string , string > ( ) ; } public string Name = > STATE_NAME ; public string Reason = > `` Waiting for external resource '' ; public bool IsFinal = > false ; public bool IgnoreJobLoadException = > false ; }
Hangfire Custom State Expiration
C_sharp : If I override Equals and GetHashCode , how do I decide which fields to compare ? And what will happen if I have two objects with two fields each , but Equals only checks one field ? In other words , let 's say I have this class : I consider two objects Equal if they have the same MyId . So if the Id is equal but the description is different , they are still considered equal.I just wonder what the pitfalls of this approach are ? Of course , a construct like this will behave as expected : As eq2 is value-equal to eq1 , it will not be added . But that is code that I control , but I wonder if there is code in the framework that could cause unexpected problems ? So , should I always add all public Fields in my Equals ( ) Comparison , or what are the guidelines to avoid a nasty surprise because of some bad Framework-Mojo that was completely unexpected ? <code> class EqualsTestClass { public string MyDescription { get ; set ; } public int MyId { get ; set ; } public override bool Equals ( object obj ) { EqualsTestClass eq = obj as EqualsTestClass ; if ( eq == null ) { return false ; } else { return MyId.Equals ( eq.MyId ) ; } } public override int GetHashCode ( ) { int hashcode = 23 ; return ( hashcode * 17 ) + MyId.GetHashCode ( ) ; } } List < EqualsTestClass > test = new List < EqualsTestClass > ( ) ; EqualsTestClass eq1 = new EqualsTestClass ( ) ; eq1.MyId = 1 ; eq1.MyDescription = `` Des1 '' ; EqualsTestClass eq2 = new EqualsTestClass ( ) ; eq2.MyId = 1 ; eq2.MyDescription = `` Des2 '' ; test.Add ( eq1 ) ; if ( ! test.Contains ( eq2 ) ) { // Will not be executed , as test.Contains is true test.Add ( eq2 ) ; }
Overriding Equals ( ) but not checking all fields - what will happen ?
C_sharp : I have the following code example taken from the code of a Form : The second method ( SomeOtherMethod ) has resharper complaining at me . It says of onPaint that `` Value assigned is not used in any execution path '' .To my mind it was used because I added a method to the list of methods called when a paint was done.But usually when resharper tells me something like this it is because I am not understanding some part of C # . Like maybe when the param goes out of goes out of scope the item I added to the list gets removed ( or something like that ) .I thought I would ask here to see if any one knows what resharper is trying to tell me . ( Side Note : I usually just override OnPaint . But I am trying to get OnPaint to call a method in another class . I do n't want to expose that method publicly so I thought I would pass in the OnPaint group and add to it . ) <code> protected void SomeMethod ( ) { SomeOtherMethod ( this.OnPaint ) ; } private void SomeOtherMethod ( Action < PaintEventArgs > onPaint ) { onPaint += MyPaint ; } protected void MyPaint ( PaintEventArgs e ) { // paint some stuff }
Does adding to a method group count as using a variable ?
C_sharp : Is there any way for Visual Studio to create my interface 'public ' ? For example , right click on folder - > create new item - > code - > interface.Whenever the file is created there are no access modifiers . Is there any way to default it to make it public ? I 'm always forgetting to manually change them to public ( when they need to be ) . <code> interface IMyInterface { } public interface IMyInterface { }
Set interface to public by default in C #
C_sharp : I 'm trying to convert an enum from C++ code over to C # code , and I 'm having trouble wrapping my head around it . The C++ code is : What I do n't understand is what MASK is doing , and how I can either emulate the functionality in C # , or understand what it 's doing and set the enum DISP manually without it.I 'm not sure what I 'm saying is making sense , but that 's to be expected when I 'm not entirely certain what I 'm looking at . <code> enum FOO { FOO_1 = 0 , FOO_2 , // etc } # define MASK ( x ) ( ( 1 < < 16 ) | ( x ) ) enum DISP { DISP_1 = MASK ( FOO_1 ) , DISP_2 = MASK ( FOO_2 ) , // etc }
Reproducing some bit shift code from C++ to C #
C_sharp : I 'm using EF code first for developing my 3 layer WinForm Application , I used disconnected POCOs as my model entities . All my entities inherited from BaseEntity class . I used disconnected POCOs , so I handle entity 's State on client side , and in ApplyChanges ( ) method , I attach my entity graph ( e.g An Order with it 's OrderLines and Products ) to my DbContext and then synch each entity 's State with it 's client side State.So , when I want to save a graph of related entities , I used following methods : But if my graph contains 2 or more entities with the same key i give this error : How can i detect entities with the same keys in my graph ( root ) and make them unique in my ApplyChanges ( ) method ? <code> public class BaseEntity { int _dataBaseId = -1 ; public virtual int DataBaseId // DataBaseId override in each entity to return it 's key { get { return _dataBaseId ; } } public States State { get ; set ; } public enum States { Unchanged , Added , Modified , Deleted } } public static EntityState ConvertState ( BaseEntity.States state ) { switch ( state ) { case BaseEntity.States.Added : return EntityState.Added ; case BaseEntity.States.Modified : return EntityState.Modified ; case BaseEntity.States.Deleted : return EntityState.Deleted ; default : return EntityState.Unchanged ; } } public void ApplyChanges < TEntity > ( TEntity root ) where TEntity : BaseEntity { _dbContext.Set < TEntity > ( ) .Add ( root ) ; foreach ( var entry in _dbContext.ChangeTracker .Entries < BaseEntity > ( ) ) { BaseEntity stateInfo = entry.Entity ; entry.State = ConvertState ( stateInfo.State ) ; } } An object with the same key already exists in the ObjectStateManager ...
Finding entities with same key in an object graph for preventing `` An object with the same key already exists in the ObjectStateManager '' Error