text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
C_sharp : I know that the general guideline for implementing the dispose pattern warns against implementing a virtual Dispose ( ) . However , most often we 're only working with managed resources inside a class and so the full dispose pattern seems like an overkill - i.e . we do n't need a finalizer . In such cases , is it OK to have a virtual Dispose ( ) in the base class ? Consider this simple example : I find this more readable than a complete dispose pattern . I understand that this example would become problematic if we introduced an unmanaged resource into the Base class . But suppose that this wo n't happen . Is the above example then valid/safe/robust , or does it pose any problem ? Should I stick to the standard full-blown dispose pattern , even if no unmanaged resources are used ? Or is the above approach indeed perfectly OK in this situation - which in my experience is far more common than dealing with unmanaged resources ? <code> abstract class Base : IDisposable { private bool disposed = false ; public SecureString Password { get ; set ; } // SecureString implements IDisposable . public virtual void Dispose ( ) { if ( disposed ) return ; if ( Password ! = null ) Password.Dispose ( ) ; disposed = true ; } } class Sub : Base { private bool disposed = false ; public NetworkStream NStream { get ; set ; } // NetworkStream implements IDisposable . public override void Dispose ( ) { if ( disposed ) return ; if ( NStream ! = null ) NStream.Dispose ( ) ; disposed = true ; base.Dispose ( ) ; } } | Is it OK to have a virtual Dispose ( ) method as long as all classes in the hierarchy only use managed resources ? |
C_sharp : The situation I have is likeExcept I actually want j to go through the range 0-radius.length , but skip over i : I 'm wondering if there 's a way to do this that is compact , elegant , efficient , readable , and maybe even correct.How I planned to do it was <code> // radius is an int [ ] for ( int i = 0 ; i < radius.length ; ++i ) { for ( int j = 0 ; j < radius.length ; ++j ) { // do some stuff } } { 0,1 , ... , i-1 , i+1 , ... , radius.length } for ( int i = 0 ; i < radius.length ; ++i ) { for ( int j = 0 ; j < radius.length ; ) { // do some stuff j += j ! = i ? 1 : 2 ; } } | Does C # have a nice way of iterating through every integer in a range , minus 1 of them ? |
C_sharp : I am trying one more time to reach out to asp.net experts and hoping to get an answer . I am really stuck here and asking for help . Hopefully , my question will not get down voted , and I could get an answer purely from technical point of view instead of people simply being judgmental on my approach . Earlier I posted question as follows : asp.net convert asp.net page into Page variableThen I looked at following page but still its not working for me.Load an ASP.NET 2.0 aspx page using System.Reflection ? Inside my web application , I would like to be able to reference web pages any where in my code like `` WebForm1.aspx '' and get a listing of the controls on that page . Please just look at it from this point of view and not over analyze it . Is it possible ? In my Page variable p , I do not seem to have any controls for WebForm1.aspxHere is my code . Please help . <code> protected void Page_Load ( object sender , EventArgs e ) { string [ ] filePaths = Directory.GetFiles ( Server.MapPath ( `` ~/ '' ) , `` * . * '' , SearchOption.AllDirectories ) ; foreach ( string filepath in filePaths ) { if ( filepath.EndsWith ( `` .aspx '' ) ) { Response.Write ( filepath + `` < br/ > '' ) ; string [ ] folders = filepath.Split ( '\\ ' ) ; string filename = folders [ folders.Count ( ) - 1 ] ; string fullpath = `` ~/ '' + filename ; Page p = BuildManager.CreateInstanceFromVirtualPath ( `` ~/ '' +fullpath , typeof ( Page ) ) as Page ; List < String > controlList = new List < String > ( ) ; ResourceManager.AddControls ( p.Controls , controlList ) ; foreach ( string str in controlList ) { Response.Write ( str + `` < br/ > '' ) ; } } } | Identify Label and Button Control in each page of the web project |
C_sharp : This code does not compile : The compile fails stating : Inconsistent accessibility : parameter type Foo is less accessible than method SomeBaseClass.ProcessFoo <code> internal class Foo { } public abstract class SomeBaseClass { protected internal void ProcessFoo ( Foo value ) { // doing something ... } } | Protected Internal method not allowing Internal Class as parameter |
C_sharp : I have two very similar methods : The top one , will not compile , saying it returns IEnumerable rather than IQueryable.Why is this ? Also , I am aware I can add `` AsQueryable ( ) '' on the end and it will work . What difference does that make though ? Any performance hits ? I understand that IQueryable has deferred execution and such , will I still get this benefit ? <code> public IQueryable < User > Find ( Func < User , bool > exp ) { return db.Users.Where ( exp ) ; } public IQueryable < User > All ( ) { return db.Users.Where ( x = > ! x.deleted ) ; } | Why is my LINQ statement returning IEnumerable ? |
C_sharp : Browsing the .NET core source code for System.Linq.Expressions , I found the following code located here : Is there any way that GetGetMethod and GetSetMethod can both return null , as seems to be accounted for here ? Is this dead code ? The C # compiler does n't allow for a property to have no getter and no setter , so how is this possible for PropertyInfo.My motivation is to contribute to the OSS code by adding test coverage , so I 'm trying to see what test cases would cover this <code> MethodInfo mi = property.GetGetMethod ( true ) ; if ( mi == null ) { mi = property.GetSetMethod ( true ) ; if ( mi == null ) { throw Error.PropertyDoesNotHaveAccessor ( property , nameof ( property ) ) ; } } | Can a C # Property ever have no GetMethod and no SetMethod |
C_sharp : Im still pretty new so bear with me on this one , my question ( s ) are not meant to be argumentative or petty but during some reading something struck me as odd.Im under the assumption that when computers were slow and memory was expensive using the correct variable type was much more of a necessity than it is today . Now that memory is a bit easier to come by people seem to have relaxed a bit . For example , you see this sample code everywhere : int ? ( -2,147,483,648 to 2,147,483,648 ) for length ? Isnt byte ( 0-255 ) a better choice ? So Im curious of your opinion and what you believe to be best practice , I hate to think this would be used only because the acronym `` int '' is more intuitive for a beginner ... or has memory just become so cheap that we really dont need to concern ourselves with such petty things and therefore we should just use long so we can be sure any other numbers/types ( within reason ) used can be cast automagically ? ... or am Im just being silly by concerning myself with such things ? <code> for ( int i = 0 ; i < length ; i++ ) | Using different numeric variable types |
C_sharp : I have application and I have to use a certificate which requires a pin from prompt window.I have following code.Everything works fine in console application but when I run that code in windows service or console application started from task scheduler then application freezes on that line.No exceptions , no progress.I 'm running windows service with the same credentials as an application.Windows 10 / Windows Server 2012Do you have any ideas what is wrong ? <code> SecureString password = GetPassword ( ) ; X509Certificate2 certificate = GetCertificate ( ) ; var cspParameters = new CspParameters ( 1 , `` ProviderName '' , `` KeyContainerName '' , null , password ) ; certificate.PrivateKey = new RSACryptoServiceProvider ( cspParameters ) ; certificate.PrivateKey = new RSACryptoServiceProvider ( cspParameters ) ; | Setting private key in certificate hangs windows service |
C_sharp : Question is simpleis this codesame fast as this codecommon sense tell me that it should be faster to look up the reference in dictionary once and store it somewhere so that it does n't need to be looked up multiple times , but I do n't really know how dictionary works.So is it faster or not ? And why ? <code> public Dictionary < string , SomeObject > values = new Dictionary < string , SomeObject > ( ) ; void Function ( ) { values [ `` foo '' ] .a = `` bar a '' ; values [ `` foo '' ] .b = `` bar b '' ; values [ `` foo '' ] .c = `` bar c '' ; values [ `` foo '' ] .d = `` bar d '' ; } public Dictionary < string , SomeObject > values = new Dictionary < string , SomeObject > ( ) ; void Function ( ) { var someObject = values [ `` foo '' ] ; someObject.a = `` bar a '' ; someObject.b = `` bar b '' ; someObject.c = `` bar c '' ; someObject.d = `` bar d '' ; } | Is it faster to copy reference to object from dictionary or access it directly from dictionary ? |
C_sharp : I have tested two rescaling functions by applying them on FFT convolution outputs.The first one is collected from this link.Here the problem is incorrect contrast.The second one is collected from this link.Here the output is totally white.So , you can see two of the versions are giving one correct and another incorrect outputs.How can I solve this dilemma ? . Note . Matrix is the following kernel : Source Code . Here is my FFT Convolution function . <code> public static void RescaleComplex ( Complex [ , ] convolve ) { int imageWidth = convolve.GetLength ( 0 ) ; int imageHeight = convolve.GetLength ( 1 ) ; double maxAmp = 0.0 ; for ( int i = 0 ; i < imageWidth ; i++ ) { for ( int j = 0 ; j < imageHeight ; j++ ) { maxAmp = Math.Max ( maxAmp , convolve [ i , j ] .Magnitude ) ; } } double scale = 1.0 / maxAmp ; for ( int i = 0 ; i < imageWidth ; i++ ) { for ( int j = 0 ; j < imageHeight ; j++ ) { convolve [ i , j ] = new Complex ( convolve [ i , j ] .Real * scale , convolve [ i , j ] .Imaginary * scale ) ; } } } public static void RescaleComplex ( Complex [ , ] convolve ) { int imageWidth = convolve.GetLength ( 0 ) ; int imageHeight = convolve.GetLength ( 1 ) ; double scale = imageWidth * imageHeight ; for ( int j = 0 ; j < imageHeight ; j++ ) { for ( int i = 0 ; i < imageWidth ; i++ ) { double re = Math.Max ( 0.0 , Math.Min ( convolve [ i , j ] .Real * scale , 1.0 ) ) ; double im = Math.Max ( 0.0 , Math.Min ( convolve [ i , j ] .Imaginary * scale , 1.0 ) ) ; convolve [ i , j ] = new Complex ( re , im ) ; } } } 0 -1 0 -1 5 -1 0 -1 0 private static Complex [ , ] ConvolutionFft ( Complex [ , ] image , Complex [ , ] kernel ) { Complex [ , ] imageCopy = ( Complex [ , ] ) image.Clone ( ) ; Complex [ , ] kernelCopy = ( Complex [ , ] ) kernel.Clone ( ) ; Complex [ , ] convolve = null ; int imageWidth = imageCopy.GetLength ( 0 ) ; int imageHeight = imageCopy.GetLength ( 1 ) ; int kernelWidth = kernelCopy.GetLength ( 0 ) ; int kernelHeight = kernelCopy.GetLength ( 1 ) ; if ( imageWidth == kernelWidth & & imageHeight == kernelHeight ) { Complex [ , ] fftConvolved = new Complex [ imageWidth , imageHeight ] ; Complex [ , ] fftImage = FourierTransform.ForwardFFT ( imageCopy ) ; Complex [ , ] fftKernel = FourierTransform.ForwardFFT ( kernelCopy ) ; for ( int j = 0 ; j < imageHeight ; j++ ) { for ( int i = 0 ; i < imageWidth ; i++ ) { fftConvolved [ i , j ] = fftImage [ i , j ] * fftKernel [ i , j ] ; } } convolve = FourierTransform.InverseFFT ( fftConvolved ) ; RescaleComplex ( convolve ) ; convolve = FourierShifter.ShiftFft ( convolve ) ; } else { throw new Exception ( `` Padded image and kernel dimensions must be same . `` ) ; } return convolve ; } | Rescaling Complex data after FFT Convolution |
C_sharp : I have code like this : Let 's say the LongRunningCalc methods each take 1 second . The code above takes about 2 seconds to run , because while the list of 5 elements is operated on in parallel , the two methods called from the let statements are called sequentially.However , these methods can safely be called in parallel also . They obviously need to merge back for the select but until then should run in parallel - the select should wait for them.Is there a way to achieve this ? <code> var list = new List < int > { 1 , 2 , 3 , 4 , 5 } ; var result = from x in list.AsParallel ( ) let a = LongRunningCalc1 ( x ) let b = LongRunningCalc2 ( x ) select new { a , b } ; | How to run LINQ 'let ' statements in parallel ? |
C_sharp : Consider the following two extension methods : When I wrote my second method , I intended it to call the generic LINQ Enumerable.Contains < T > method ( type arguments inferred from the usage ) . However , I found out that it is actually calling the first method ( my custom Contains ( ) extension method . When I comment out my Contains ( ) method , the second method compiles fine , using the Enumerable.Contains < T > ( ) method.My question is , why does the compiler choose my Contains ( ) method with non-generic IEnumerable argument over Enumerable.Contains < T > ( ) with IEnumerable < T > argument ? I would expect it to choose Enumerable.Contains < T > ( ) because IEnumerable < T > is more derived than IEnumerable . <code> using System ; using System.Collections.Generic ; using System.Linq ; public static class Extensions { public static bool Contains ( this IEnumerable self , object obj ) { foreach ( object o in self ) { if ( Object.Equals ( o , obj ) ) { return true ; } } return false ; } public static bool ContainsEither < T > ( this IEnumerable < T > self , T arg1 , T arg2 ) { return self.Contains ( arg1 ) || self.Contains ( arg2 ) ; } } | Why does the compiler choose overload with IEnumerable over IEnumerable < T > ? |
C_sharp : I have a view model which retrieves an object from some service , and makes it available for data binding . The object is implementing INotifyPropertyChanged . In the view model , I am listening to the PropertyChanged event to perform some internal actions when certain properties in the object are modified.Now it is possible that a new object is requested from the service , completely replacing the old object . Given that the lifetime is essentially limited by the view model itself , and nobody else holds a reference to it ( WPF uses weak listeners ) , do I need to unsubscribe from the object in this case ? Of course , I should and it ’ s simple enough to do so in the setter , but do I really need to ? <code> public class MyViewModel : INotifyPropertyChanged { private DataType myData ; public DataType MyData { get { return myData ; } protected set { if ( value == myData ) return ; if ( myData ! = null ) myData.PropertyChanged -= DataPropertyChanged ; myData = value ; myData.PropertyChanged += DataPropertyChanged ; OnNotifyPropertyChanged ( `` MyData '' ) ; } } public void UpdateData ( ) { MyData = service.GetData ( ) ; } // ... } | Is unsubscribing from event necessary for an object with shorter lifetime ? |
C_sharp : In C , when compiled to a x86 machine , I would usually replace branches with logical expression , when speed is the most important aspect , even if the conditions are complex , for example , instead ofI will write : Now clearly , this might be a harder to maintain , and less readable code , but it might actually be faster.Is there any reason to act the same way when working with managed code , such as C # ? Are `` jumps '' expensive in managed code as they are in unmanaged code ( at least on x86 ) ? <code> char isSomething ( ) { if ( complexExpression01 ) { if ( complexExpression02 ) { if ( ! complexExpression03 ) { return 1 ; } } } return 0 ; } char isSomething ( ) { return complexExpression01 & & complexExpression02 & & ! complexExpression03 ; } | Avoiding branches in managed languages |
C_sharp : This is just for academic purpose . I noticed that for integral literals , we can declare up to 18446744073709551615 which is 2^64-1 or ulong.MaxValue . Defining greater than this value produces a compile-time error . And for floating-point literals , we can declare them with integral part up to 999 ... 999 ( 9 is repeated 308 times ) . Declaring the integral part with more digits again produces a compile-time error . One thing that interests me is that the compiler seems to allow us specify the fractional part unlimited number of digits . Practically , unlimited number of digits for the fractional part does not make sense . Questions : Is there a constant representing the max number of digits internally defined by C # compiler for the fractional part of a floating-point number ? If such a constant exists , why does not C # compiler throw compile-time error when users specify the fractional parts beyond its limit ? Minimal Working Example 1Minimal Working Example 2IL : <code> namespace FloatingPoint { class Program { static void Main ( string [ ] args ) { const ulong @ ulong = 18446744073709551615 ; const double @ double = 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999.9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999 ; } } } using System ; namespace FloatingPoint { class Program { static void Main ( string [ ] args ) { const double x01 = 0.9 ; const double x02 = 0.99 ; const double x03 = 0.999 ; const double x04 = 0.9999 ; const double x05 = 0.99999 ; const double x06 = 0.999999 ; const double x07 = 0.9999999 ; const double x08 = 0.99999999 ; const double x09 = 0.999999999 ; const double x10 = 0.9999999999 ; const double x11 = 0.99999999999 ; const double x12 = 0.999999999999 ; const double x13 = 0.9999999999999 ; const double x14 = 0.99999999999999 ; const double x15 = 0.999999999999999 ; const double x16 = 0.9999999999999999 ; const double x17 = 0.99999999999999999 ; const double x18 = 0.999999999999999999 ; const double x19 = 0.9999999999999999999 ; const double x20 = 0.99999999999999999999 ; Console.WriteLine ( x01 ) ; Console.WriteLine ( x02 ) ; Console.WriteLine ( x03 ) ; Console.WriteLine ( x04 ) ; Console.WriteLine ( x05 ) ; Console.WriteLine ( x06 ) ; Console.WriteLine ( x07 ) ; Console.WriteLine ( x08 ) ; Console.WriteLine ( x09 ) ; Console.WriteLine ( x10 ) ; Console.WriteLine ( x11 ) ; Console.WriteLine ( x12 ) ; Console.WriteLine ( x13 ) ; Console.WriteLine ( x14 ) ; Console.WriteLine ( x15 ) ; Console.WriteLine ( x16 ) ; Console.WriteLine ( x17 ) ; Console.WriteLine ( x18 ) ; Console.WriteLine ( x19 ) ; Console.WriteLine ( x20 ) ; } } } /* output:0.90.990.9990.99990.999990.9999990.99999990.999999990.9999999990.99999999990.999999999990.9999999999990.99999999999990.999999999999990.99999999999999911111*/ .method private hidebysig static void Main ( string [ ] args ) cil managed { .entrypoint // Code size 302 ( 0x12e ) .maxstack 1 IL_0000 : nop IL_0001 : ldc.r8 0.90000000000000002 IL_000a : call void [ mscorlib ] System.Console : :WriteLine ( float64 ) IL_000f : nop IL_0010 : ldc.r8 0.98999999999999999 IL_0019 : call void [ mscorlib ] System.Console : :WriteLine ( float64 ) IL_001e : nop IL_001f : ldc.r8 0.999 IL_0028 : call void [ mscorlib ] System.Console : :WriteLine ( float64 ) IL_002d : nop IL_002e : ldc.r8 0.99990000000000001 IL_0037 : call void [ mscorlib ] System.Console : :WriteLine ( float64 ) IL_003c : nop IL_003d : ldc.r8 0.99999000000000005 IL_0046 : call void [ mscorlib ] System.Console : :WriteLine ( float64 ) IL_004b : nop IL_004c : ldc.r8 0.99999899999999997 IL_0055 : call void [ mscorlib ] System.Console : :WriteLine ( float64 ) IL_005a : nop IL_005b : ldc.r8 0.99999990000000005 IL_0064 : call void [ mscorlib ] System.Console : :WriteLine ( float64 ) IL_0069 : nop IL_006a : ldc.r8 0.99999998999999995 IL_0073 : call void [ mscorlib ] System.Console : :WriteLine ( float64 ) IL_0078 : nop IL_0079 : ldc.r8 0.99999999900000003 IL_0082 : call void [ mscorlib ] System.Console : :WriteLine ( float64 ) IL_0087 : nop IL_0088 : ldc.r8 0.99999999989999999 IL_0091 : call void [ mscorlib ] System.Console : :WriteLine ( float64 ) IL_0096 : nop IL_0097 : ldc.r8 0.99999999999 IL_00a0 : call void [ mscorlib ] System.Console : :WriteLine ( float64 ) IL_00a5 : nop IL_00a6 : ldc.r8 0.99999999999900002 IL_00af : call void [ mscorlib ] System.Console : :WriteLine ( float64 ) IL_00b4 : nop IL_00b5 : ldc.r8 0.99999999999989997 IL_00be : call void [ mscorlib ] System.Console : :WriteLine ( float64 ) IL_00c3 : nop IL_00c4 : ldc.r8 0.99999999999999001 IL_00cd : call void [ mscorlib ] System.Console : :WriteLine ( float64 ) IL_00d2 : nop IL_00d3 : ldc.r8 0.999999999999999 IL_00dc : call void [ mscorlib ] System.Console : :WriteLine ( float64 ) IL_00e1 : nop IL_00e2 : ldc.r8 0.99999999999999989 IL_00eb : call void [ mscorlib ] System.Console : :WriteLine ( float64 ) IL_00f0 : nop IL_00f1 : ldc.r8 1 . IL_00fa : call void [ mscorlib ] System.Console : :WriteLine ( float64 ) IL_00ff : nop IL_0100 : ldc.r8 1 . IL_0109 : call void [ mscorlib ] System.Console : :WriteLine ( float64 ) IL_010e : nop IL_010f : ldc.r8 1 . IL_0118 : call void [ mscorlib ] System.Console : :WriteLine ( float64 ) IL_011d : nop IL_011e : ldc.r8 1 . IL_0127 : call void [ mscorlib ] System.Console : :WriteLine ( float64 ) IL_012c : nop IL_012d : ret } // end of method Program : :Main | C # compiler does not limit the number of digits of fractional part of a floating-point literal |
C_sharp : I 'm trying to post to a local bitcoin full node via json-rpc but I 'm getting an error from the server.Following the documentation here : https : //bitcoincore.org/en/doc/0.17.0/rpc/rawtransactions/createrawtransaction/I can see the following example structure for a createrawtransaction request : My code creates the following structure , which seems to match the structure of the example from bitcoincore.org : But it gives an error : Below is the method I am using to make the RPC request , which I got from the API reference here : https : //en.bitcoin.it/wiki/API_reference_ ( JSON-RPC ) # .NET_.28C.23.29Here is my attempt to use the above method : Other commands such these as do work : This also works : My Question : What have I done wrong with createrawtransaction ? Update 1 : As suggested in the comments , I have changed the StringBuilder , and am now using objects and then serializing the objects using Newtonsoft.Json.Here is my second attempt to use the API reference code from https : //en.bitcoin.it/wiki/API_reference_ ( JSON-RPC ) # .NET_.28C.23.29 : Here is the new serialized JSON : Compared to the old StringBuilder JSON from my first attempt : I am still getting the same error message as before ( see above ) . <code> { `` jsonrpc '' : `` 1.0 '' , `` id '' : '' curltest '' , `` method '' : `` createrawtransaction '' , `` params '' : [ `` [ { \ '' txid\ '' : \ '' myid\ '' , \ '' vout\ '' :0 } ] '' , `` [ { \ '' address\ '' :0.01 } ] '' ] } { `` jsonrpc '' : '' 1.0 '' , '' id '' : '' 1 '' , '' method '' : '' createrawtransaction '' , '' params '' : [ `` [ { \ '' txid\ '' : \ '' 1a43a1f27c5837d5319a45217aa948a4d39c1d89faf497ce59de5bd570a64a26\ '' , \ '' vout\ '' :1 } ] '' , '' [ { \ '' 2NAZpRsvj9BstxxCDkKoe1FVjmPPxdmvqKj\ '' :0.01 } ] '' ] } System.Net.WebException HResult=0x80131509 Message=The remote server returned an error : ( 500 ) Internal Server Error . Source=RawTransactions StackTrace : at RawTransactions.Form1.RequestServer ( String methodName , List ` 1 parameters ) in C : \Users\userthree\Documents\Visual Studio 2017\Projects\RawTransactions\RawTransactions\Form1.cs : line 132 at RawTransactions.Form1.button1_Click ( Object sender , EventArgs e ) in C : \Users\userthree\Documents\Visual Studio 2017\Projects\RawTransactions\RawTransactions\Form1.cs : line 77 at System.Windows.Forms.Control.OnClick ( EventArgs e ) at System.Windows.Forms.Button.OnClick ( EventArgs e ) at System.Windows.Forms.Button.OnMouseUp ( MouseEventArgs mevent ) at System.Windows.Forms.Control.WmMouseUp ( Message & m , MouseButtons button , Int32 clicks ) at System.Windows.Forms.Control.WndProc ( Message & m ) at System.Windows.Forms.ButtonBase.WndProc ( Message & m ) at System.Windows.Forms.Button.WndProc ( Message & m ) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage ( Message & m ) at System.Windows.Forms.Control.ControlNativeWindow.WndProc ( Message & m ) at System.Windows.Forms.NativeWindow.DebuggableCallback ( IntPtr hWnd , Int32 msg , IntPtr wparam , IntPtr lparam ) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW ( MSG & msg ) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop ( IntPtr dwComponentID , Int32 reason , Int32 pvLoopData ) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner ( Int32 reason , ApplicationContext context ) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop ( Int32 reason , ApplicationContext context ) at System.Windows.Forms.Application.Run ( Form mainForm ) at RawTransactions.Program.Main ( ) in C : \Users\userthree\Documents\Visual Studio 2017\Projects\RawTransactions\RawTransactions\Program.cs : line 19 public static string RequestServer ( string methodName , List < string > parameters ) { string ServerIp = `` http : //localhost:18332 '' ; string UserName = `` USERNAME '' ; string Password = `` PASSWORD '' ; HttpWebRequest webRequest = ( HttpWebRequest ) WebRequest.Create ( ServerIp ) ; webRequest.Credentials = new NetworkCredential ( UserName , Password ) ; webRequest.ContentType = `` application/json-rpc '' ; webRequest.Method = `` POST '' ; string respVal = string.Empty ; JObject joe = new JObject ( ) ; joe.Add ( new JProperty ( `` jsonrpc '' , `` 1.0 '' ) ) ; joe.Add ( new JProperty ( `` id '' , `` 1 '' ) ) ; joe.Add ( new JProperty ( `` method '' , methodName ) ) ; JArray props = new JArray ( ) ; foreach ( var parameter in parameters ) { props.Add ( parameter ) ; } joe.Add ( new JProperty ( `` params '' , props ) ) ; // serialize json for the request string s = JsonConvert.SerializeObject ( joe ) ; byte [ ] byteArray = Encoding.UTF8.GetBytes ( s ) ; webRequest.ContentLength = byteArray.Length ; Stream dataStream = webRequest.GetRequestStream ( ) ; dataStream.Write ( byteArray , 0 , byteArray.Length ) ; dataStream.Close ( ) ; StreamReader streamReader = null ; try { WebResponse webResponse = webRequest.GetResponse ( ) ; streamReader = new StreamReader ( webResponse.GetResponseStream ( ) , true ) ; respVal = streamReader.ReadToEnd ( ) ; var data = JsonConvert.DeserializeObject ( respVal ) .ToString ( ) ; return data ; } catch ( Exception exp ) { throw ( exp ) ; } finally { if ( streamReader ! = null ) { streamReader.Close ( ) ; } } return string.Empty ; } private void button1_Click ( object sender , EventArgs e ) { StringBuilder sb1 = new StringBuilder ( ) ; sb1.Append ( `` [ { \ '' '' ) ; sb1.Append ( `` txid '' ) ; sb1.Append ( `` \ '' : \ '' '' ) ; sb1.Append ( Convert.ToString ( data [ `` result '' ] [ Convert.ToInt32 ( txtFromJSON.Text ) ] [ `` txid '' ] ) ) ; sb1.Append ( `` \ '' , \ '' '' ) ; sb1.Append ( `` vout '' ) ; sb1.Append ( `` \ '' : '' ) ; sb1.Append ( Convert.ToString ( data [ `` result '' ] [ Convert.ToInt32 ( txtFromJSON.Text ) ] [ `` vout '' ] ) ) ; sb1.Append ( `` } ] '' ) ; StringBuilder sb2 = new StringBuilder ( ) ; sb2.Append ( `` [ { \ '' '' ) ; sb2.Append ( Convert.ToString ( data [ `` result '' ] [ Convert.ToInt32 ( txtToJSON.Text ) ] [ `` address '' ] ) ) ; sb2.Append ( `` \ '' : '' ) ; sb2.Append ( txtAmountToSpend.Text ) ; sb2.Append ( `` } ] '' ) ; // { `` jsonrpc '' : '' 1.0 '' , '' id '' : '' 1 '' , '' method '' : '' createrawtransaction '' , '' params '' : [ `` [ { \ '' txid\ '' : \ '' 1a43a1f27c5837d5319a45217aa948a4d39c1d89faf497ce59de5bd570a64a26\ '' , \ '' vout\ '' :1 } ] '' , '' [ { \ '' 2NAZpRsvj9BstxxCDkKoe1FVjmPPxdmvqKj\ '' :0.01 } ] '' ] } data = JObject.Parse ( RequestServer ( `` createrawtransaction '' , new List < string > ( ) { Convert.ToString ( sb1 ) , Convert.ToString ( sb2 ) } ) ) ; MessageBox.Show ( Convert.ToString ( data ) ) ; } // { `` jsonrpc '' : '' 1.0 '' , '' id '' : '' 1 '' , '' method '' : '' sendtoaddress '' , '' params '' : [ `` 2N8hwP1WmJrFF5QWABn38y63uYLhnJYJYTF '' , '' 0.1 '' ] } data = JObject.Parse ( RequestServer ( `` sendtoaddress '' , new List < string > ( ) { `` 2N8hwP1WmJrFF5QWABn38y63uYLhnJYJYTF '' , Convert.ToString ( 0.1 ) } ) ) ; // { `` jsonrpc '' : '' 1.0 '' , '' id '' : '' 1 '' , '' method '' : '' listunspent '' , '' params '' : [ ] } data = JObject.Parse ( RequestServer ( `` listunspent '' , new List < String > ( ) { } ) ) ; private void button1_Click ( object sender , EventArgs e ) { JContainer jArray = new JArray ( ) ; JObject jFromTx = new JObject { { `` txid '' , data [ `` result '' ] [ Convert.ToInt32 ( txtFromJSON.Text ) ] [ `` txid '' ] } , { `` vout '' , data [ `` result '' ] [ Convert.ToInt32 ( txtFromJSON.Text ) ] [ `` vout '' ] } } ; jArray.Add ( jFromTx ) ; JObject jToTx = new JObject { { Convert.ToString ( data [ `` result '' ] [ Convert.ToInt32 ( txtToJSON.Text ) ] [ `` address '' ] ) , Convert.ToDouble ( txtAmountToSpend.Text ) } } ; JContainer jArray2 = new JArray { jToTx } ; string strFrom = JsonConvert.SerializeObject ( jArray ) ; string strTo = JsonConvert.SerializeObject ( jArray2 ) ; data = JObject.Parse ( RequestServer ( `` createrawtransaction '' , new List < string > ( ) { strFrom , strTo } ) ) ; } { `` jsonrpc '' : '' 1.0 '' , '' id '' : '' 1 '' , '' method '' : '' createrawtransaction '' , '' params '' : [ `` [ { \ '' txid\ '' : \ '' 1a43a1f27c5837d5319a45217aa948a4d39c1d89faf497ce59de5bd570a64a26\ '' , \ '' vout\ '' :1 } ] '' , '' [ { \ '' 2NAZpRsvj9BstxxCDkKoe1FVjmPPxdmvqKj\ '' :0.01 } ] '' ] } { `` jsonrpc '' : '' 1.0 '' , '' id '' : '' 1 '' , '' method '' : '' createrawtransaction '' , '' params '' : [ `` [ { \ '' txid\ '' : \ '' 1a43a1f27c5837d5319a45217aa948a4d39c1d89faf497ce59de5bd570a64a26\ '' , \ '' vout\ '' :1 } ] '' , '' [ { \ '' 2NAZpRsvj9BstxxCDkKoe1FVjmPPxdmvqKj\ '' :0.01 } ] '' ] } | Trouble posting CREATERAWTRANSACTION to Bitcoin Core via JSON-RPC |
C_sharp : Given an enum like this : I am using the following code to give me an IEnumerable : The code works very good however I have to do this for quite a lot of enums . Is there a way I could create a generic way of doing this ? <code> public enum City { London = 1 , Liverpool = 20 , Leeds = 25 } public enum House { OneFloor = 1 , TwoFloors = 2 } City [ ] values = ( City [ ] ) Enum.GetValues ( typeof ( City ) ) ; var valuesWithNames = from value in values select new { value = ( int ) value , name = value.ToString ( ) } ; | How can I use Generics to create a way of making an IEnumerable from an enum ? |
C_sharp : I have something like this : Why is Math.Round ( ) rounding even numbers down and odd numbers up ? <code> double d1 = Math.Round ( 88.5 , 0 ) ; // result 88double d2 = Math.Round ( 89.5 , 0 ) ; // result 90 | Rounding up and down by Math Round ( ) |
C_sharp : I am working on a legacy ecommerce platform and have noticed a convention when dealing with credit card numbers . C # or in sqlI presume the reasoning is to remove it from memory before setting it to null which may not remove the value . But that reasoning would seem to suggest that SQL Server and/or the .NET VM had vulnerabilities in where just setting it to null would not remove the data completely just say that it is available.Is my understanding of it correct ? Does it still need to beperformed today ? <code> cardnumber = `` 11111111111111111111 '' ; cardnumber = null ; update cards set cardnumber = '11111111111111111111 ' where customerid = @ CustomerIDupdate cards set cardnumber = null where customerid = @ CustomerID | Overwrite then set to null |
C_sharp : The following results do n't make any sense to me . It looks like a negative offset is cast to unsigned before addition or subtraction are performed.Although it might seem strange to use negative offsets , there are use cases for it . In my case it was reflecting boundary conditions in a two-dimensional array.Of course , the overflow does n't hurt too much because I can either use unchecked or move the sign of the value to the operation by inverting and applying it to the modulus of the operand.But this behaviour seems undocumented . According to MSDN I do n't expect negative offsets to be problematic : You can add a value n of type int , uint , long , or ulong to a pointer , p , of any type except void* . The result p+n is the pointer resulting from adding n * sizeof ( p ) to the address of p. Similarly , p-n is the pointer resulting from subtracting n * sizeof ( p ) from the address of p . <code> double [ ] x = new double [ 1000 ] ; int i = 1 ; // for the overflow it makes no difference if it is long , int or shortint j = -1 ; unsafe { fixed ( double* px = x ) { double* opx = px+500 ; // = 0x33E64B8 //unchecked // { double* opx1 = opx+i ; // = 0x33E64C0 double* opx2 = opx-i ; // = 0x33E64B0 double* opx3 = opx+j ; // = 0x33E64B0 if unchecked ; throws overflow exception if checked double* opx4 = opx-j ; // = 0x33E64C0 if unchecked ; throws overflow exception if checked // } } } | Pointer offset causes overflow |
C_sharp : I have a situation where I need to dynamically build up a list of filters to apply to a list of objects . Those objects can be anything that implements an interface which contains all of the properties I need to filter on.I have a list of criteria defined like so ... and add criteria like so ... I then apply the criteria to my query like so ... which uses the following extension method ... The compiler is telling me ... When I hover over the red line under the error in the IDE it 's saying it can not resolve method betweenIf I try casting the expression to Expression < Func < T , bool > > , which ought to work as T is constrained to implement the IStuff interface . I getEDITThanks to Raphaël 's answer I fixed the extension method and eventually found the real problem I had , which was a casting problem when I was calling the code . Easily fixed by adding a .Cast < SomeStuff > ( ) after the ApplyCriteria call.BeforeAfter <code> public interface IStuff { bool SuitableForSomething { get ; set ; } bool SuitableForSomethingElse { get ; set ; } } public class SomeStuff : IStuff { ... } public class SomeOtherStuff : IStuff { ... } public List < Expression < Func < IStuff , bool > > > Criteria { get ; private set ; } Criteria.Add ( x = > x.SuitableForSomething ) ; Criteria.Add ( x = > x.SuitableForSomethingElse ) ; var stuff= _stuffCache .GetAll ( ) .AsQueryable ( ) .ApplyCriteria ( Criteria ) ; public static IQueryable < T > ApplyCriteria < T > ( this IQueryable < T > stuff , List < Expression < Func < IStuff , bool > > > criteria ) where T : IStuff { foreach ( var expression in criteria ) { stuff = Queryable.Where ( stuff , expression ) ; } return stuff ; } can not convert from 'System.Linq.Expressions.Expression < System.Func < IStuff , bool > > 'to 'System.Linq.Expressions.Expression < System.Func < T , int , bool > > ' IQueryable < IStuff > Where < IStuff > ( this IQueryable < IStuff > , Expression < Func < IStuff , bool > > ) in class Queryableand IQueryable < T > Where < T > ( this IQueryable < T > , Expression < Func < T , int , bool > > ) in class Queryable Can not cast expression of type 'Expression < Func < IStuff , bool > > ' to type 'Expression < Func < T , bool > > ' var stuff= _stuffCache .GetAll ( ) .AsQueryable ( ) .ApplyCriteria ( Criteria ) ; var stuff= _stuffCache .GetAll ( ) .AsQueryable ( ) .ApplyCriteria ( Criteria ) .Cast < SomeStuff > ( ) ; | C # generic constraint not working as expected |
C_sharp : I want to build my grammar to accept multiple number . It has a bug when I repeat the number like saying 'twenty-one ' . So I kept reducing my code to find the problem . I reached the following piece of code for the grammar builder : Now when I pronounce `` one one '' it still gives me this exception Which when I googled for it , it states that this is an exception outside my code , I am wondering is this a bug in Microsoft.Speech dll or I am missing somethingEdit 1 : I played around with the code , and made the recognition to be Async as follow : instead of now when I say 'twenty-one'for example it gets this exception : base = { `` Duplicated semantic key 'op1 ' in rule 'root . `` } I know the problem is with the grammar , but I did made it repeated for the 'op1 ' . What am I missing ? ? <code> string [ ] numberString = { `` one '' } ; Choices numberChoices = new Choices ( ) ; for ( int i = 0 ; i < numberString.Length ; i++ ) { numberChoices.Add ( new SemanticResultValue ( numberString [ i ] , numberString [ i ] ) ) ; } gb [ 1 ] .Append ( new SemanticResultKey ( `` op1 '' , ( GrammarBuilder ) numberChoices ) , 1 , 2 ) ; sre.RecognizeAsync ( RecognizeMode.Multiple ) ; sre.Recognize ( ) ; | TargetInvocationException when using SemanticResultKey |
C_sharp : a few months ago I wrote this code because it was the only way I could think to do it ( while learning C # ) , well . How would you do it ? Is unchecked the proper way of doing this ? <code> unchecked //FromArgb takes a 32 bit value , though says it 's signed . Which colors should n't be . { _EditControl.BackColor = System.Drawing.Color.FromArgb ( ( int ) 0xFFCCCCCC ) ; } | How to do this without unchecked ? |
C_sharp : My C # code uses impersonation by calling Win32 functions via P/Invokealso I have AppDomain.CurrentDomain.UnhandledException handler installed that also logs all unhandled exception.I 'm sure that the code that logs exceptions works fine both with and without impersonation.Now the problem is that in the above code it looks like catch is not entered and UnhandledException is also not called . The only trace of the exception is an entry in the Event Viewer.If I add a finally like this : then the exception is logged okay both from catch and from UnhandledException handler.What 's happening ? Does the thread being impersonated prevent usual exception handling ? <code> internal class Win32Native { [ DllImport ( `` advapi32.dll '' , SetLastError = true ) ] public static extern int ImpersonateLoggedOnUser ( IntPtr token ) ; [ DllImport ( `` advapi32.dll '' , SetLastError = true ) ] public static extern int RevertToSelf ( ) ; } try { var token = obtainTokenFromLogonUser ( ) ; Win32Native.ImpersonateLoggedOnUser ( token ) ; throw new Exception ( ) ; // this is for simulation Win32Native.RevertToSelf ( ) } catch ( Exception e ) { LogException ( e ) ; throw ; } try { var token = obtainTokenFromLogonUser ( ) ; Win32Native.ImpersonateLoggedOnUser ( token ) ; try { throw new Exception ( ) ; // this is for simulation } finally { Win32Native.RevertToSelf ( ) } } catch ( Exception e ) { LogException ( e ) ; throw ; } | Why is exception from impersonated code not caught ? |
C_sharp : I was reading Pulling the switch here and came across this code . Can somoone please explain what is ( ) = > { } and what should I read up to understand that line of code ? <code> var moveMap = new Dictionary < string , Action > ( ) { { `` Up '' , MoveUp } , { `` Down '' , MoveDown } , { `` Left '' , MoveLeft } , { `` Right '' , MoveRight } , { `` Combo '' , ( ) = > { MoveUp ( ) ; MoveUp ( ) ; MoveDown ( ) ; MoveDown ( ) ; } } } ; moveMap [ move ] ( ) ; | What does ( ) = > { } mean ? |
C_sharp : I want to specify that one property in an XML serializable class is an attribute of another property in the class , not of the class itself . Is this possible without creating additional classes ? For example , if I have the following C # classhow can I specify that IsAlertOneEnabled is an attribute of AlertOne so that the XML serializes to the following ? <code> class Alerts { [ XmlElement ( `` AlertOne '' ) ] public int AlertOneParameter { get ; set ; } public bool IsAlertOneEnabled { get ; set ; } } < Alerts > < AlertOne Enabled= '' True '' > 99 < /AlertOne > < /Alerts > | How to specify one property is attribute of another In C # XML serialization ? |
C_sharp : So I have a simple enough console app : I 've built it with release configuration . When I run it and open task manager , I see ithas 4 threads . Why is this happening even though I 'm not creating any threads ? This ca n't possibly be each application . I tried opening notepad and it has just 1 thread . Although it is a native app and my console app is managed . Any ideas ? <code> class Program { static void Main ( string [ ] args ) { Console.ReadKey ( ) ; } } | Free multiple threads ? |
C_sharp : I have an interface to a .NET service layer , which , in turn , will communicate with a third-party system via a web service . This handles a number of different tasks related to the third-party system 's functionality ( it is actually a bespoke CRM system , but as the context is n't relevant I will swap this out for something trivial ) .The interface looks something like this : Now , my models currently work as follows : I have a BaseResponseModel , from which each SomethingModel inherits . Each SomethingModel contains some basic properties and also wraps a Something - like so : Base response modelSpecific response modelsHere , Car and Person simply contain a bunch of public properties . Then , each method of my IMyService takes its arguments , formats a request to an .asmx web service , parses the response into its response model and returns it to the caller ( an .ascx codebehind ) .However , the number of different ... Model classes ( not to mention that they all have different property names for their wrapped objects ) is becoming ugly . I am of a mind to do something along the lines of the following : My ASP.NET controls will then receive ServiceResponse < T > from every method in IMyService.Is this the `` conventionally correct '' usage of generics in C # ? Or is this simply masking deeper architectural flaws with my solution ? Is there something missing from my proposed solution ( though note that the implementations of the different Get and Add methods are n't as generic as the prototypes make them seem ) ? Disclaimer : Apologies if this question is `` too subjective , '' but it seemed too specific to be a theoretical question for Programmers.SE and a little too generic to be a question for CodeReview.SE . I am open to suggestions on how to improve the question if necessary . <code> public interface IMyService { CarModel GetCar ( string registration ) ; CarModel AddCar ( Car car ) ; PersonModel GetPerson ( string personId ) ; PersonModel AddPerson ( Person person ) ; } public class BaseResponseModel { public List < string > Errors { get ; set ; } public bool HasErrors { get { return ( Errors ! = null & & Errors.Count > 0 ) ; } } } public class CarModel : BaseResponseModel { public Car Car { get ; set ; } } public class PersonModel : BaseResponseModel { public Person Person { get ; set ; } } public class Car { public string Registration { get ; set ; } } public class ServiceResponse < T > { public List < string > Errors { get ; set ; } public bool HasErrors { ... } public T Result { get ; set ; } } public interface IMyService { ServiceResponse < Car > GetCar ( string registration ) ; ServiceResponse < Car > AddCar ( Car car ) ; ServiceResponse < Person > GetPerson ( string id ) ; ServiceResponse < Person > AddPerson ( Person person ) ; } | Generics and convention in C # |
C_sharp : For some reason this statement is working fine : But if at the top of the class , I define an alias ( to save space ) : Then the resulting line of code : Gives me an error : '' Delegate 'System.Func < ValidationMessage , int , bool > ' does not take 1 arguments '' . What 's odd about that is that is n't the Delegate I 'm using . I 'm using the 'System.Func < ValidationMessage , bool > ' overload of .Where < > ( ) - same as when I was n't using the alias.Note that everywhere else the alias is being used works fine , it 's only inside these linq delegates that it breaks . Why is this happening ? <code> vms.Where ( vm = > vm.MessageType == ValidationMessage.EnumValidationMessageType.Warning ) using MsgType = ValidationMessage.EnumValidationMessageType ; vms.Where ( vm = > vm.MessageType == MsgType.Warning ) | Using a type alias in a linq statement is generating an error |
C_sharp : ProblemI currently have a factory that depends on a few parameters to properly decide which object to return . This factory is not yet bound to DI . As I understand it NInject uses providers as a factory.Here is what I currently have . I 'll warn you it 's not pretty.I 'm almost certain this is not the proper way of dynamically injecting dependencies , however it does work . And frankly , looking at what I 've hacked together does n't seem to make much sense.The reason I need to dynamically resolve the dependency is that during the life cycle of the application the end-user can assume several roles . The sample posted above is pretty simply but the parameters ( currently only isNew ) would determine would object to inject.QuestionWhat is the proper way to use a provider with parameters not known at run time ? These parameters would be passed in whenever the user triggers the code that could give them a different role.Thank you.EditBind it with Bind < IRoleFactory > ( ) .To < RoleFactory > ( ) ; and use it like so.This revised version does look better and makes more sense , however I believe I missed some key details in your post . Wanted to add that the isNew parameter would be true if the factory was called from for example a `` Create New Event '' button . <code> public interface IRole { string Name { get ; } } public class FooRole : IRole { public string Name { get { return `` Foo Role '' ; } } } public class BarRole : IRole { public string Name { get { return `` Bar Role '' ; } } } public class FooBarRoleModule : NinjectModule { public override void Load ( ) { Bind < IRole > ( ) .ToProvider < RoleProvider > ( ) ; } } public class RoleProvider : Provider < IRole > { protected override IRole CreateInstance ( IContext context ) { var isNewParameter = context.Parameters .Where ( x = > x.Name == `` isNew '' ) .Select ( x = > x.GetValue ( context ) ) .Cast < bool > ( ) .FirstOrDefault ( ) ; if ( isNewParameter ) return new FooRole ( ) ; return new BarRole ( ) ; } } var role = kernel.Get < IRole > ( new ConstructorArgument ( `` isNew '' , true ) ) ; Console.WriteLine ( role.Name ) ; public class RoleFactory : IRoleFactory { public IRole Create ( bool isNew ) { if ( isNew ) return new BarRole ( ) ; return new FooRole ( ) ; } } var role = kernel.Get < IRoleFactory > ( ) ; Console.WriteLine ( role.Create ( true ) .Name ) ; | Dynamically determining dependency based on user parameters |
C_sharp : I 'm trying to understand the yield keyword better and I think I have a decent enough understanding of it so I ran some tests however I was surpised by the results.If I run the below code I get the following output which shows that it loops over the whole range not just up to number 4.Output : If I run the below code it shows that it only gets to 4 and then stops.Output : I guess I 'm not understading something but it looks as if LINQ is doing the opposite of what I expect it to do ? I though LINQ used yield and deferred execution as well and I 'd expect the results from the second set of code to be the same for the first set of code . <code> public void DoIt ( ) { Console.WriteLine ( `` Method Call '' ) ; var results = GetData ( Enumerable.Range ( 1 , 10 ) ) ; Console.WriteLine ( `` LINQ '' ) ; var filtered = results.Where ( x = > x == 4 ) ; Console.WriteLine ( `` Start result loop '' ) ; foreach ( var item in filtered ) { Console.WriteLine ( `` Item is `` + item ) ; } } private IEnumerable < int > GetData ( IEnumerable < int > Input ) { foreach ( int item in Input ) { if ( item % 2 == 0 ) { Console.WriteLine ( `` Found `` + item ) ; yield return item ; } } } Method CallLINQStart result loopFound 2Found 4Item is 4Found 6Found 8Found 10 public void DoIt ( ) { Console.WriteLine ( `` Method Call '' ) ; var results = GetData ( Enumerable.Range ( 1 , 10 ) ) ; Console.WriteLine ( `` Start result loop '' ) ; foreach ( var item in results ) { if ( item == 4 ) { Console.WriteLine ( `` Item is `` + item ) ; break ; } } } private IEnumerable < int > GetData ( IEnumerable < int > Input ) { foreach ( int item in Input ) { if ( item % 2 == 0 ) { Console.WriteLine ( `` Found `` + item ) ; yield return item ; } } } Method CallStart result loopFound 2Found 4Item is 4 | Understanding the yield keyword and LINQ |
C_sharp : Let 's say we have a Foo class : For you to gain perspective , I can say that data in these files has been recorded for about 2 years at frequency of usually several Foo 's every minute.Now : we have a parameter called TimeSpan TrainingPeriod which is about 15 days for example . What I 'd like to accomplish is to call : and obtain IEnumerable < Foo > TrainingSet , TestSet of it , where TrainingSet consists of the Foos from the first 15 days of recording , and the TestSet of all the rest . Then , out of the TrainingSet we want to calculate some constant-memory data ( like average Value , some linear regression etc . ) , and then start consuming the TestSet , using the calculated values . In other words , my code should semantically be equvalent to : By the way the XML file naming convention ensures me , that Foos will be returned in chronological order.Of course , I do not want to store it all in memory , which happens every time .ToList ( ) is called . So I came up with another solution : However , there is a minor and a major issue about that piece of code . The minor one is that the first file is read twice at least - does n't matter actually . But it looks like TrainingSet and TestSet access the directory independently , read every file twice and select only those holding a particular timestamp constraint . I 'm not too puzzled by that - in fact if it worked I would be puzzled and would have to rethink LINQ once again . But this raises file-access issues , and every file is parsed two times , which is a total waste of CPU time.So my question is : can I achieve this effect using only simple LINQ/C # tools ? I think I can do this in a good ol ' brute-force way , overriding some GetEnumerator ( ) , MoveNext ( ) methods and so on - please do n't bother typing it , I can totally handle this on my own.However , if there is some elegant , short & sweet solution to this , it would be highly appreciated.Thank you ! Another edit : The code I finally came up is the following : Of course still some minor issues are present i.e . veryfying the output of MoveNext ( ) ( is it end of the IEnumerable already ? ) , but the general idea is clear I hope . BUT in the real code it 's not just average I 'm calculating , but different kinds of regression etc . So I 'd like to somehow extract the first part , pass it as an IEnumerable to a class deriving from myto separate responsibilities for extraction of training data and it 's processing . Plus after the process depicted before I get an IEnumerator < Foo > , but I think an IEnumerable < Foo > would be preferred to pass it to my TheRestOfTheDataHandler instance . <code> public class Foo { public DateTime Timestamp { get ; set ; } public double Value { get ; set ; } // some other properties public static Foo CreateFromXml ( Stream str ) { Foo f = new Foo ( ) ; // do the parsing return f ; } public static IEnumerable < Foo > GetAllTheFoos ( DirectoryInfo dir ) { foreach ( FileInfo fi in dir.EnumerateFiles ( `` foo*.xml '' , SearchOption.TopDirectoryOnly ) ) { using ( FileStream fs = fi.OpenRead ( ) ) yield return Foo.CreateFromXML ( fs ) ; } } } var allTheData = GetAllTheFoos ( myDirectory ) ; TimeSpan TrainingPeriod = new TimeSpan ( 15 , 0 , 0 ) ; // hope it says 15 daysvar allTheData = GetAllTheFoos ( myDirectory ) ; List < Foo > allTheDataList = allTheData.ToList ( ) ; var threshold = allTheDataList [ 0 ] .Timestamp + TrainingPeriod ; List < Foo > TrainingSet = allTheDataList.Where ( foo = > foo.Timestamp < threshold ) .ToList ( ) ; List < Foo > TestSet = allTheDataList.Where ( foo = > foo.Timestamp > = threshold ) .ToList ( ) ; TimeSpan TrainingPeriod = new TimeSpan ( 15 , 0 , 0 ) ; var allTheData = GetAllTheFoos ( myDirectory ) ; var threshold = allTheDataList.First ( ) .Timestamp + TrainingPeriod ; // a minor issuevar grouped = from foo in allTheData group foo by foo.Timestamp < Training ; var TrainingSet = grouped.First ( g = > g.Key ) ; var TestSet = grouped.First ( g = > ! g.Key ) ; // the major one public static void Handle ( DirectoryInfo dir ) { var allTheData = Foo.GetAllTheFoos ( dir ) ; var it = allTheData.GetEnumerator ( ) ; it.MoveNext ( ) ; TimeSpan trainingRange = new TimeSpan ( 15 , 0 , 0 , 0 ) ; DateTime threshold = it.Current.Timestamp + trainingRange ; double sum = 0.0 ; int count = 0 ; while ( it.Current.Timestamp < = threshold ) { sum += it.Current.Value ; count++ ; it.MoveNext ( ) ; } double avg = sum / ( double ) count ; // now I can continue on with the 'it ' IEnumerator } public abstract class AbstractAverageCounter { public abstract void Accept ( IEnumerable < Foo > theData ) ; public AverageCounterResult Result { get ; protected set ; } } | Split an single-use large IEnumerable < T > in half using a condition |
C_sharp : In a lot of TDD tutorials I see code like this : This all makes sense but at some point you are going to get to the class that actually uses MyClass and you want to test that the exception is handled : So why not put the try/catch in MyClass in the first place rather than throwing the exception and have the test that test 's for null in the MyClass unit test class and not in the EntryPointClass unit test class ? <code> public class MyClass { public void DoSomething ( string Data ) { if ( String.IsNullOrWhiteSpace ( Data ) ) throw new NullReferenceException ( ) ; } } [ Test ] public DoSomething_NullParameter_ThrowsException ( ) { var logic = MyClass ( ) ; Assert.Throws < NullReferenceException > ( ( ) = > logic.DoSomething ( null ) ) ; } public class EntryPointClass { public void DoIt ( string Data ) { var logicClass = new MyClass ( ) ; try { logicClass.DoSomething ( Data ) ; } catch ( NullReferenceException ex ) { } } } [ Test ] public DoIt_NullParameter_IsHandled ( ) { var logic = new EntryPointClass ( ) try { logic.DoIt ( null ) ; } catch { Assert.Fail ( ) ; } } | Unit Testing and Coding Design |
C_sharp : This is more of a why question . Here it goes.C # 7.0 added a new feature called `` Local Function '' . Below is a code snippet.What I dont understand is , its doing a recursive call to the same method . We can easily achieve this with a normal foreach . Then why a local function . MSDN says methods implemented as iterators commonly need a non-iterator wrapper method for eagerly checking the arguments at the time of the call . ( The iterator itself doesn ’ t start running until MoveNext is called ) .Need some help in understanding the concept that it . <code> public int Fibonacci ( int x ) { if ( x < 0 ) throw new ArgumentException ( `` Less negativity please ! `` , nameof ( x ) ) ; return Fib ( x ) .current ; ( int current , int previous ) Fib ( int i ) { if ( i == 0 ) return ( 1 , 0 ) ; var ( p , pp ) = Fib ( i - 1 ) ; return ( p + pp , p ) ; } } | How is local function in C # 7.0 different from a foreach or a loop ? |
C_sharp : For example I have these two lists : How can I concatenate firstName [ 0 ] and lastName [ 0 ] , firstName [ 1 ] and lastName [ 1 ] , etc and put it in a new list ? <code> List < string > firstName = new List < string > ( ) ; List < string > lastName = new List < string > ( ) ; | Merging 2 Lists |
C_sharp : I ran into this statement in a piece of code : colorList is a list of class System.Drawing.Color.Now the statement is supposed to retrieve the median index of the list .. like the half point of it .. but I ca n't understand how that > > symbol works and how the `` 1 '' is supposed to give the median index .. I would appreciate some help : S <code> Int32 medianIndex = colorList.Count > > 1 ; | What does the `` > > '' operator in C # do ? |
C_sharp : I found article stating that recycling and reusing variables is good practice in unity . So I adopted it.But one thing not clear : does this apply to value type variables ( integers , vectors ) ? is there a point i using this : instead of this : <code> int x ; Vector3 v ; void functionCalledVeryOften ( ) { x=SomeCalculation ( ) ; v=SomeCalc ( ) ; //do something with x and v } void functionCalledVeryOften ( ) { int x=SomeCalculation ( ) ; Vector3 v=SomeCalc ( ) ; //do something with x and v } | is there a point in recycling value types unity |
C_sharp : I have a TreeView that is filled with different types of items . The items can either be of type Node ( then they may have children ) or of type Entry ( then they do n't have children ) . For that , I bound my TreeView to my ViewModel property AllNodesAndEntries which is an ObservableCollection < object > . For different looks of Node and Entry I defined two DataTemplates . Here is the code : Now I want to make the Entry elements unfocusable if a certain condition is met ( that is , if my ViewModel property MyProp is true ) .So I added a trigger into the DataTemplate for Entry like this : But it does not work , I can still select entries after MyProp was set to true . What am I doing wrong ? How do I make it work ? I did put a NotifyPropertyChanged ( nameof ( MyProp ) ) ; in the setter of MyProp , so changes to MyProp will be reported to the View . <code> < TreeView ItemsSource= '' { Binding AllNodesAndEntries } '' > < TreeView.Resources > < HierarchicalDataTemplate ItemsSource= '' { Binding Children } '' DataType= '' { x : Type local : Node } '' > < TextBlock Text= '' { Binding Name } '' Background= '' LightBlue '' / > < /HierarchicalDataTemplate > < DataTemplate DataType= '' { x : Type local : Entry } '' > < TextBlock Text= '' { Binding Name } '' Background= '' LightSalmon '' / > < /DataTemplate > < /TreeView.Resources > < /TreeView > < DataTemplate DataType= '' { x : Type local : Entry } '' > < TextBlock Text= '' { Binding Name } '' Background= '' LightSalmon '' / > < DataTemplate.Triggers > < DataTrigger Binding= '' { Binding MyProp } '' Value= '' True '' > < Setter Property= '' Focusable '' Value= '' False '' / > < /DataTrigger > < /DataTemplate.Triggers > < /DataTemplate > | Disable focusability of certain entries in TreeView |
C_sharp : So i convert a float to a string , which is formatted as a currency.But when I want to convert it back to a float , it would n't be possible , because a float cant store the € symbol . So is there a way to convert the string back to a float , but it disregards the `` € '' ( with the space ) ? <code> float f = 2.99F ; string s = f.ToString ( `` c2 '' ) ; //s = 2.99 € | How to parse a string to a float , without the currency format ? |
C_sharp : I am trying to write unit tests for a new project I have created and I 've run into an issue where I ca n't work out how a class that I am intending to write is actually testable . Below I 've simplified the class that I am trying to write to give you an idea of what I am trying to achieve.So I have an XML parser that will simply access an XML file from a given URL , extract the data that I need and return it as an object . So my code will look something like this ( Validation and population not completed yet but you get the idea ) : Currently my class is n't testable . I ca n't mock the load to throw a WebException to see how my class handles errors and until I pass through a valid URL it will always throw an exception when I run tests against this class . I also can not test the data coming back from the class since I ca n't mock the XML document since it 's loaded from another URL.I could split this out into a mockable object that retrieves the XML from the URL and name it something like IXmlDocumentLoader but later I run into the same problem where I have a class like this : This would make the ParseUserDetails method more testable but now the class XmlDocumentLoader is not testable . So have I just moved the problem elsewhere ? My question is really do all classes have to be testable or am I misunderstanding unit testing ? <code> public UserDetails ParseUserDetails ( string request , string username , string password ) { var response = new XmlDocument ( ) ; response.Load ( string.Format ( request + `` ? user= { 0 } & password= { 1 } '' , username , password ) ) ; // Validation checks return new UserDetails { // Populate object with XML nodes } ; } public class XmlDocumentLoader : IXmlDocumentLoader { public XmlDocument LoadXmlDocument ( string request , string username , string password ) { var response = new XmlDocument ( ) ; response.Load ( string.Format ( request + `` ? user= { 0 } & password= { 1 } '' , username , password ) ) ; return response ; } } | Should all classes be testable ? |
C_sharp : Sorry to ask this as I thought I knew the answer , I want to exit the program if userName is greater than 4 characters or userName is not an account called student . However this even if the userName is only 3 characters and is not student I 'm still hitting Application.Exit . What am I doing wrong ? Shame on me : - ( <code> if ( userName.Length > 4 | userName ! = `` student '' ) { Application.Exit ( ) ; } | C # simple IF OR question |
C_sharp : An interesting question arose today . Let 's say I have a .NET object that implements a certain interface IMyInterface and is also COM Visible.Now , I load the type from its ProgID and cast to a strongly-typed interface , like so : If I execute the above code , when objEarlyBound.Method ( ) executes , am I calling into a COM object or directly into the .NET object ? How can I prove this one way or another ? <code> IMyInterface objEarlyBound = null ; Type t = Type.GetTypeFromProgID ( `` My.ProgId '' ) ; objLateBound = Activator.CreateInstance ( t ) ; objEarlyBound= ( IMyInterface ) objLateBound ; objEarlyBound.Method ( ) ; | Am I calling a .NET object or a COM object ? |
C_sharp : ExpertsI would like to shuffle windows forms automatically every after 5 mins . windows forms contains Multiple querys , Multiple videos , Multiple powerpoints.I am having three windows forms , as follows.Forms 1 code : Forms 2 : Microsoft Powerpoint filemultiple powerpoint files from network folder ( path ) Forms 3 : Multiple video files ( MP4 , FLV , MOV , etc ) Multiple video files from network folder ( Path ) Requirement : Each forms should change and display every after 5 min.example : first form1 should display then after 5 mins form1 should minimized and form2 should show the slideshow and then after 5 mins form2 should minimized and form3 should play the video and then after 5 mins form3 should minimized and pause the video then form1 should display.It should keep doing the same steps as above.Final condition : All forms should stop exactly at 6 pm ( Everyday ) and it should start automatically at 7 am ( Everyday ) .Please advise ... <code> using System ; using System.Collections.Generic ; using System.ComponentModel ; using System.Data ; using System.Drawing ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; using System.Windows.Forms ; namespace Daily_System { public partial class Form1 : Form { public Form1 ( ) { InitializeComponent ( ) ; timer1.Enabled = true ; timer1.Interval = 5000 ; timer1.Tick += timer1_Tick ; timer1.Start ( ) ; } private void Form1_Load ( object sender , EventArgs e ) { this.WindowState = FormWindowState.Maximized ; CenterToScreen ( ) ; } private Timer timer1 = new Timer ( ) ; private void button1_Click_1 ( object sender , EventArgs e ) { this.WindowState = FormWindowState.Minimized ; Form2 f = new Form2 ( ) ; // This is bad timer2.Enabled = true ; } private void timer2_Tick ( object sender , EventArgs e ) { button1.PerformClick ( ) ; } } } using System ; using System.Collections.Generic ; using System.ComponentModel ; using System.Data ; using System.Drawing ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; using System.Windows.Forms ; using PowerPoint = Microsoft.Office.Interop.PowerPoint ; using Core = Microsoft.Office.Core ; namespace Daily_System { public partial class Form2 : Form { public Form2 ( ) { InitializeComponent ( ) ; this.WindowState = FormWindowState.Minimized ; timer1.Enabled = true ; timer1.Interval = 15000 ; timer1.Start ( ) ; } private void Tick ( object sender , EventArgs e ) { Form3 Next = new Form3 ( ) ; Next.Show ( ) ; this.Hide ( ) ; timer1.Stop ( ) ; //Stop timer after tick once } protected override void OnLoad ( EventArgs e ) { base.OnLoad ( e ) ; this.BeginInvoke ( new MethodInvoker ( delegate ( ) { button1.PerformClick ( ) ; } ) ) ; } private void button1_Click ( object sender , EventArgs e ) { Microsoft.Office.Interop.PowerPoint.Application pptApp = new Microsoft.Office.Interop.PowerPoint.Application ( ) ; Microsoft.Office.Core.MsoTriState ofalse = Microsoft.Office.Core.MsoTriState.msoFalse ; Microsoft.Office.Core.MsoTriState otrue = Microsoft.Office.Core.MsoTriState.msoTrue ; pptApp.Visible = otrue ; pptApp.Activate ( ) ; Microsoft.Office.Interop.PowerPoint.Presentations ps = pptApp.Presentations ; var opApp = new Microsoft.Office.Interop.PowerPoint.Application ( ) ; pptApp.SlideShowEnd += PpApp_SlideShowEnd ; var ppPresentation = ps.Open ( @ `` C : \Users\ok\Downloads\Parks-WASD2017.pptx '' , ofalse , ofalse , otrue ) ; var settings = ppPresentation.SlideShowSettings ; settings.Run ( ) ; } private void PpApp_SlideShowEnd ( Microsoft.Office.Interop.PowerPoint.Presentation Pres ) { Pres.Saved = Microsoft.Office.Core.MsoTriState.msoTrue ; Pres.Close ( ) ; } private void Form2_Load ( object sender , EventArgs e ) { } private void button2_Click ( object sender , EventArgs e ) { this.WindowState = FormWindowState.Minimized ; Form3 f = new Form3 ( ) ; // This is bad f.Show ( ) ; /// f.Show ( ) ; timer1.Enabled = true ; this.Hide ( ) ; timer1.Stop ( ) ; //Stop timer after tick once } private void timer1_Tick_1 ( object sender , EventArgs e ) { button2.PerformClick ( ) ; } } } using System ; using System.Collections.Generic ; using System.ComponentModel ; using System.Data ; using System.Drawing ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; using System.Windows.Forms ; namespace Daily_System { public partial class Form3 : Form { public Form3 ( ) { InitializeComponent ( ) ; timer1.Enabled = true ; timer1.Interval = 15000 ; timer1.Start ( ) ; } private void Form3_Load ( object sender , EventArgs e ) { axWindowsMediaPlayer1.settings.autoStart = true ; } private void axWindowsMediaPlayer1_Enter_1 ( object sender , EventArgs e ) { axWindowsMediaPlayer1.URL = @ `` C : \Users\ok\Downloads\ok.mp4 '' ; } private void button1_Click ( object sender , EventArgs e ) { this.WindowState = FormWindowState.Minimized ; Form1 f = new Form1 ( ) ; // This is bad f.Show ( ) ; /// f.Show ( ) ; timer1.Enabled = true ; this.Hide ( ) ; timer1.Stop ( ) ; //Stop timer after tick once } private void timer1_Tick_1 ( object sender , EventArgs e ) { button1.PerformClick ( ) ; } } } | Auto shuffle between windows forms every after 5 min |
C_sharp : This is not a biggie at all , but something that would be very helpful indeed if resolved . When I 'm overloading methods etc there are times when the xml comments are exactly the same , bar 1 or 2 param names . I have to copy/paste the comments down to each overloaded method , where they are the same . Sometimes , however , this can cause misleading information about the method if I update one of them and forget to go back and copy/paste them to all others . If there are alot of overloaded methods , this can be very time consuming and prone to error.So I 'm wondering if there is a way of storing comments in one place ( like a variable ) , which I can simply reference instead . This way , one change will be reflected across all related commetns . Here 's an example : So as you can see , all of the comments are the same except I decided to make a correction on the last one to read 'Go and do something cool ' . Now i 'll have to go and change this is all the other method comments too . Cheers . <code> /// < summary > /// Go and do something /// < /summary > public void DoSomething ( ) { DoSomething ( true , `` Done something '' ) ; } /// < summary > /// Go and do something /// < /summary > /// < param name= '' doIt '' > whether it should be done or not < /param > public void DoSomething ( bool doIt ) { DoSomething ( doIt , `` Done something '' ) ; } /// < summary > /// Go and do something cool /// < /summary > /// < param name= '' doIt '' > whether it should be done or not < /param > /// < param name= '' doneMessage '' > message to show once done < /param > public void DoSomething ( bool doIt , string doneMessage ) { if ( doIt ) Console.WriteLine ( doneMessage ) ; } | Is there a way of referencing the xml comments to avoid duplicating them ? |
C_sharp : We recently updated our applications to make use of SHA-256 code-signing with a new certificate . The assemblies are strong name signed using the Sign the assembly option in Visual Studio 2015 . The post build event in Visual Studio runs two signtool.exe processes to sign both in SHA-256 and for the legacy SHA-1 certificate : Finally we use Advanced Installer as the installation packager and that too is code-signed on the Digital Signature page using the certificate and timestamp as per the .exe signature.The final setup file installs and runs on Internet connected Windows machines as you would expect . You can see the certificate is assigned and valid , as well as the certificate chain through the properties of both the setup.exe and the runtime when installed . Furthermore , Windows recognizes the application as from a trusted source and displays the appropriate verified publisher details.Our customer-base is largely global 100 companies and most of the deployments will be occurring in air-gapped networks . In one of our fist updated deployments in this environment , the certificate could not be verified preventing the installer from completing . This made sense , because the Windows ( 2012 server R2 ) machines were isolated from the Internet and , due to company policies , had Turn off Automatic Root Certificates set to Enabled . This setting can be found in the Computer Configuration - > Administrative Templates - > System - > Internet Communication Management - > Internet Communication Settings folder of the MMC application ( you need the certificates plugin installed ) .When testing on our local test-bed , even machines not connected to the Internet would install the certificates from the setup utility if the above registry setting was the default ( Disabled ) . We could replicate the issue by changing the policy setting to match the customers ' ( Enabled ) .As a workaround , we manually downloaded the Certificate Authorities root certificate and installed it as a Trusted Root Certificate and the install would proceed normally.When we presented this workaround to the customer , the installation still failed despite the Certificate Authorities root certificate being present in the Trusted Root Certificates of the machine.The Certificate Authority customer service team recommended that we drop the timestamp from the signing process to allow the install to proceed - and that 's the only help they offered ( that 's another story ) . However , this means that once the code-signing certificate expires , the application will either cease to run or will present unverified publisher errors . I 'm not totally convinced that this will fix the problem either , because when we tested locally the certificate was still found by the installer and allowed the installation to proceed when the Certificate Authorities root certificate was installed manually.What I am unable to do is replicate the customers environment to exactly reproduce the problem ( which does n't help ) . It is almost as if Windows is bypassing the local machine 's Trusted Root Certificates store . I am assuming that if this is possible it would be so that Windows can verify against a central root certificate store . Is this even possible to set up in Windows ? If so , where would I find either documentation on this or how is this done ? Am I missing something in the code-signing steps or in my understanding of what should be happening on the installing machine while it is checking the certificate ? I am at a loss as to what to do to get this installer working . What I ca n't afford to do is keep going back to the customer to get them to keep testing our installs . First-off it 's really not the right process to debug , as the supplying vendor it is n't the customers problem to solve , but more importantly , I need our team to understand what is causing this and how to remedy it correctly.Ideally I do n't what to drop the timestamp if I do n't have to because down the road this will cause new problems if the software does n't get upgraded before the certificate expires.Any and all help much appreciated . <code> call `` C : \Program Files ( x86 ) \Windows Kits\10\bin\x86\signtool.exe '' sign /f `` < mystrongName.pfx > '' /p `` < password > '' /t < timestampURL > `` $ ( TargetPath ) '' call `` C : \Program Files ( x86 ) \Windows Kits\10\bin\x86\signtool.exe '' sign /f `` < mystrongName.pfx > '' /p `` < password > '' /fd sha256 /tr < timestampURL > /td sha256 /as /v `` $ ( TargetPath ) '' | Air-gapped .NET code-signed application will not install/run |
C_sharp : So I have this 2 methods which suppose to multiply a 1000 items long array of integers by 2.The first method : The second method : Note that I use this code only for performance research and that 's why it looks so disgusting.The surprising result is that Power is faster by almost 50 % than PowerNoLoop even though I have checked the decompiled IL source of both of them and the content of the for loop is exactly the same as each line in PowerNoLoop.How can it be ? <code> [ MethodImpl ( MethodImplOptions.NoOptimization ) ] Power ( int [ ] arr ) { for ( int i = 0 ; i < arr.Length ; i++ ) { arr [ i ] = arr [ i ] + arr [ i ] ; } } [ MethodImpl ( MethodImplOptions.NoOptimization ) ] PowerNoLoop ( int [ ] arr ) { int i = 0 ; arr [ i ] = arr [ i ] + arr [ i ] ; i++ ; arr [ i ] = arr [ i ] + arr [ i ] ; i++ ; arr [ i ] = arr [ i ] + arr [ i ] ; i++ ; ... ... ... ... 1000 Times ... ... .. arr [ i ] = arr [ i ] + arr [ i ] ; } | Weird performance behavior |
C_sharp : Have an app where I would like to upload an image . I am using byte array for this.The image is required but when I put that annotation on the variable and try create an image , it gives me the error message when it should have the image there . It also returns that the Model is Invalid.When I remove the Required , it works but it can also be set as null which is what I do n't want.There does n't seem to be a lot on the topic on Stack Overflow.Here is my ModelAnd my controller : My View just in case its something there : <code> [ Key ] public int InvoiceId { get ; set ; } [ Required ( ErrorMessage = `` Company is required '' ) ] public string Company { get ; set ; } [ Required ( ErrorMessage = `` Description is required '' ) ] public string Description { get ; set ; } [ Required ( ErrorMessage = `` Amount is required '' ) ] public decimal Amount { get ; set ; } [ Required ( ErrorMessage = `` Picture of Invoice Required '' ) ] public byte [ ] PictureOfInvoice { get ; set ; } [ HttpPost ] [ ValidateAntiForgeryToken ] [ Authorize ( Roles = `` Parish Admin , Priest , Administrator '' ) ] public ActionResult Create ( [ Bind ( Include = `` InvoiceId , Company , Description , Amount , PictureOfInvoice , DateReceived , ChurchId '' ) ] Invoice invoice , HttpPostedFileBase File ) { if ( ModelState.IsValid ) { if ( File ! = null & & File.ContentLength > 0 ) { invoice.PictureOfInvoice = new byte [ File.ContentLength ] ; File.InputStream.Read ( invoice.PictureOfInvoice , 0 , File.ContentLength ) ; } else { TempData [ `` Error '' ] = `` Upload an Image '' ; } db.Invoices.Add ( invoice ) ; db.SaveChanges ( ) ; return RedirectToAction ( `` Index '' ) ; } ViewBag.ChurchId = new SelectList ( db.Churches , `` ChurchId '' , `` Name '' , invoice.ChurchId ) ; return View ( invoice ) ; } < h2 > Add New Invoice < /h2 > @ if ( TempData [ `` Error '' ] ! = null ) { < div style= '' color : red '' > @ TempData [ `` Error '' ] < /div > } @ using ( Html.BeginForm ( `` Create '' , `` Invoices '' , FormMethod.Post , new { @ class = `` form-horizontal '' , enctype = `` multipart/form-data '' } ) ) { @ Html.AntiForgeryToken ( ) @ Html.ValidationSummary ( ) < script src= '' @ Url.Content ( `` ~/Scripts/jquery.validate.min.js '' ) '' type= '' text/javascript '' > < /script > < script src= '' @ Url.Content ( `` ~/Scripts/jquery.validate.unobtrusive.min.js '' ) '' type= '' text/javascript '' > < /script > < div class= '' form-horizontal '' > < hr / > @ Html.ValidationSummary ( true , `` '' , new { @ class = `` text-danger '' } ) < div class= '' form-group '' > @ Html.LabelFor ( model = > model.Company , htmlAttributes : new { @ class = `` control-label col-md-2 '' } ) < div class= '' col-md-10 '' > @ Html.TextBoxFor ( model = > model.Company , new { htmlAttributes = new { @ class = `` form-control '' , style = `` width:20em ; '' } } ) @ Html.ValidationMessageFor ( model = > model.Company , `` '' , new { @ class = `` text-danger '' } ) < /div > < /div > < div class= '' form-group '' > @ Html.LabelFor ( model = > model.Amount , htmlAttributes : new { @ class = `` control-label col-md-2 '' } ) < div class= '' col-md-10 '' > @ Html.TextBoxFor ( model = > model.Amount , new { htmlAttributes = new { @ class = `` form-control '' , style = `` width:20em ; '' } } ) @ Html.ValidationMessageFor ( model = > model.Amount , `` '' , new { @ class = `` text-danger '' } ) < /div > < /div > < div class= '' form-group '' > @ Html.LabelFor ( model = > model.DateReceived , `` DateRecieved '' , htmlAttributes : new { @ class = `` control-label col-md-2 '' } ) < div class= '' col-md-10 '' > @ Html.TextBoxFor ( model = > model.DateReceived , new { htmlAttributes = new { @ class = `` form-control '' , style = `` width:20em ; '' } } ) @ Html.ValidationMessageFor ( model = > model.DateReceived , `` '' , new { @ class = `` text-danger '' } ) < /div > < /div > < div class= '' form-group '' > @ Html.LabelFor ( model = > model.Description , htmlAttributes : new { @ class = `` control-label col-md-2 '' } ) < div class= '' col-md-10 '' > @ Html.TextBoxFor ( model = > model.Description , new { htmlAttributes = new { @ class = `` form-control '' , style = `` width:20em ; '' } } ) @ Html.ValidationMessageFor ( model = > model.Description , `` '' , new { @ class = `` text-danger '' } ) < /div > < /div > < div class= '' form-group '' > @ Html.LabelFor ( model = > model.PictureOfInvoice , `` Picture of Invoice '' , htmlAttributes : new { @ class = `` control-label col-md-2 '' } ) < div class= '' col-md-10 '' > < input type= '' file '' name= '' File '' id= '' File '' style= '' width : 50 % ; '' / > @ Html.ValidationMessageFor ( model = > model.PictureOfInvoice , `` '' , new { @ class = `` text-danger '' } ) < output id= '' list '' > < /output > < /div > < /div > < div class= '' form-group '' > @ Html.LabelFor ( model = > model.ChurchId , `` Church Name '' , htmlAttributes : new { @ class = `` control-label col-md-2 '' } ) < div class= '' col-md-10 '' > @ Html.DropDownList ( `` ChurchId '' , null , htmlAttributes : new { @ class = `` form-control '' , style = `` width:20em ; '' } ) @ Html.ValidationMessageFor ( model = > model.ChurchId , `` '' , new { @ class = `` text-danger '' } ) < /div > < /div > < div class= '' form-group '' > < div class= '' col-md-offset-2 col-md-10 '' > < input type= '' submit '' value= '' Create '' class= '' btn btn-default '' / > < /div > < /div > < /div > } < div > < u > @ Html.ActionLink ( `` Back to List '' , `` Index '' ) < /u > < /div > < script src= '' ~/Scripts/jquery.datetimepicker.js '' > < /script > < script > $ ( ' # DateReceived ' ) .datetimepicker ( { format : 'd/m/Y ' , weeks : true , disableWeekDays : [ 0 , 1 , 3 , 4 , 5 , 6 ] , timepicker : false , inline : false } ) ; function handleFileSelect ( evt ) { var files = evt.target.files ; // FileList object // Loop through the FileList and render image files as thumbnails . for ( var i = 0 , f ; f = files [ i ] ; i++ ) { // Only process image files . if ( ! f.type.match ( 'image . * ' ) ) { continue ; } var reader = new FileReader ( ) ; // Closure to capture the file information . reader.onload = ( function ( theFile ) { return function ( e ) { // Render thumbnail . var span = document.createElement ( 'span ' ) ; span.innerHTML = [ ' < img class= '' thumb '' src= '' ' , e.target.result , ' '' title= '' ' , escape ( theFile.name ) , ' '' / > ' ] .join ( `` ) ; document.getElementById ( 'list ' ) .insertBefore ( span , null ) ; } ; } ) ( f ) ; // Read in the image file as a data URL . reader.readAsDataURL ( f ) ; } } document.getElementById ( 'File ' ) .addEventListener ( 'change ' , handleFileSelect , false ) ; < /script > | Can not make Byte a Required Field |
C_sharp : How does one add a new function to a delegate without using the += notation ? I wonder how to do his from another CLR langage , namely F # . ( I know there are much nicer way to deal with events in F # , but I am being curious.. ) Edit As pointed out by Daniel in the comments , the fact that one has no direct way of doing this probably is a design decision by dotnet team to not mutate the queue too much . <code> static int Square ( int x ) { return x * x ; } static int Cube ( int x ) { return x * x * x ; } delegate int Transformer ( int x ) ; Transformer d = Square ; d += Cube ; | Adding delegate in C # |
C_sharp : Given the class below , to launch a splash screen on an alternate thread : This is called and closed with the following respective commands Fine.I am not exactly new to the TPL , of course we can show the form on another thread using something as simple as : My issue is closing this SomeForm down when you are ready . There must be a better way than creating a public static method in the SomeForm class like My question is , what is the best way to do the same thing as shown using the SplashForm class above using the Task Parrallel Library ( TPL ) ? Specifically , the best way to close the form invoked on another thread from the UI . <code> public partial class SplashForm : Form { private static Thread _splashThread ; private static SplashForm _splashForm ; public SplashForm ( ) { InitializeComponent ( ) ; } // Show the Splash Screen ( Loading ... ) public static void ShowSplash ( ) { if ( _splashThread == null ) { // Show the form in a new thread . _splashThread = new Thread ( new ThreadStart ( DoShowSplash ) ) ; _splashThread.IsBackground = true ; _splashThread.Start ( ) ; } } // Called by the thread . private static void DoShowSplash ( ) { if ( _splashForm == null ) _splashForm = new SplashForm ( ) ; // Create a new message pump on this thread ( started from ShowSplash ) . Application.Run ( _splashForm ) ; } // Close the splash ( Loading ... ) screen . public static void CloseSplash ( ) { // Need to call on the thread that launched this splash . if ( _splashForm.InvokeRequired ) _splashForm.Invoke ( new MethodInvoker ( CloseSplash ) ) ; else Application.ExitThread ( ) ; } } SplashForm.ShowSplash ( ) ; SplashForm.CloseSplash ( ) ; Task task = Task.Factory.StartNew ( ( ) = > { SomeForm someForm = new SomeForm ( ) ; someForm.ShowDialog ( ) ; } ; private static SomeForm _someForm ; public static void CloseSomeForm ( ) { if ( _someForm.InvokeRequired ) _someForm.Invoke ( new MethodInvoker ( CloseSomeForm ) ) ; } | TPL Equivalent of Thread Class 'Splash-Type ' Screen |
C_sharp : I am using an expression to identify a specific method in a class , and return the attribute of the method . When the method is async , the compiler gives me a warning that the method should be awaited.Are there any other ways I could identify the method , or any way to suppress the warning , without using pragma ? I would like not to use a string to identify the method.Resharper suggests async/await , but async lambda expression can not be converted to expression trees.Other answers are extension methods for task , but then I would not be able to get the method with the attribute.Example code : <code> class Program { static void Main ( string [ ] args ) { var attributeProvider = new AttributeProvider ( ) ; var attributeText = attributeProvider.GetAttribute < Program > ( p = > p.MethodA ( ) ) ; //Warning : Because this call is not awaited , ... } [ Text ( `` text '' ) ] public async Task < string > MethodA ( ) { return await Task.FromResult ( `` '' ) ; } } public class AttributeProvider { public string GetAttribute < T > ( Expression < Action < T > > method ) { var expr = ( MethodCallExpression ) method.Body ; var attribute = ( TextAttribute ) Attribute.GetCustomAttribute ( expr.Method , typeof ( TextAttribute ) ) ; return attribute.Text ; } } public class TextAttribute : Attribute { public string Text { get ; set ; } public TextAttribute ( string text ) { Text = text ; } } | Expressions to identify async methods causes compiler warning |
C_sharp : I 'm porting a Win8.1 app to UWP for Win10 and experiencing a strange issue with the AppBar . We 've tried using CommandBar instead of AppBar , but the issue still occurs for us . We 're on the latest version of MyToolkit ( 2.5.16 as of this writing ) . Our views are derived like so : SomeView derives from BaseView dervices from MtPage ( derives from Page ) So , for a particular view ( in this case , HomeView ) , the XAML looks like : Where NavigationView is a UserControl that has some buttons , and NavigationViewContext and NavigationViewModel describe which buttons should be active on which page , and so forth.The problem is that this results in a sort of half-open , half-closed AppBar appearance ( almost but not quite exactly as if ClosedDisplayMode were set to Compact ) like so : After adding ClosedDisplayMode= '' Minimal '' to the < AppBar > control , as alluded to in this question , the live visual tree confirms that the AppBar has IsOpen = 0 and AppBarClosedDisplayMode.Minimal ... but it still stubbornly appears half-open as in the screenshot above.Strangely , if the user navigates away from HomeView to some other view and then back to it , the AppBar is correctly rendered with AppBarClosedDisplayMode.Minimal ( ! ) : We 've tried handling the view 's NavigatedTo event and manually forcing ClosedDisplayMode to Minimal , but that does n't affect the rendered output ( and in any case , the live visual tree confirms that that is already being correctly set to Minimal ) . Any ideas why this is happening , and/or how to cause the AppBar to be rendered with ClosedDisplayMode = Minimal without having to navigate first ? I 'm sure I could probably brute force this somehow , but I feel like there 's probably a better way or I 'm missing something pretty simple . <code> < views : BaseView x : Name= '' pageRoot '' x : Class= '' OurApp.HomeView '' 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 '' xmlns : controls= '' using : OurApp.Controls '' xmlns : views= '' using : OurApp.Views '' xmlns : viewModels= '' using : ViewModels '' xmlns : fake= '' using : ViewModels.Fake '' mc : Ignorable= '' d '' > < views : BaseView.TopAppBar > < AppBar > < controls : NavigationView x : Name= '' NavigationView '' > < controls : NavigationView.Context > < viewModels : NavigationViewModel / > < /controls : NavigationView.Context > < /controls : NavigationView > < /AppBar > < /views : BaseView.TopAppBar > < ! -- other stuff not relevant to AppBars , etc -- > < /views : BaseView > | Why does my AppBar appear as ClosedDisplayMode.Compact on Page load regardless of actual setting ? |
C_sharp : What does the @ sign does when inserted in front of parameters SQL query ? for example : <code> using ( SqlCommand cmd = new SqlCommand ( `` INSERT INTO [ User ] values ( @ Forename , @ Surname , @ Username , @ Password ) '' , con ) ) { cmd.Parameters.AddWithValue ( `` @ Forename '' , txtForename.Text ) ; cmd.Parameters.AddWithValue ( `` @ Surname '' , txtSurname.Text ) ; cmd.Parameters.AddWithValue ( `` @ UserName '' , txtUsername.Text ) ; cmd.Parameters.AddWithValue ( `` @ Password '' , txtPassword.Text ) ; cmd.ExecuteNonQuery ( ) ; } | What does the @ in front of a parameter name do ? |
C_sharp : I know a lot has been written about Linq and it 's inner workings . Inspired by Jon Skeets EduLinq , I wanted to to demystify what 's going on behind the Linq Operators . So what I tried to do is to implement Linqs Select ( ) method which sounds pretty boring at first sight . But what I 'm actually trying to do is to implement it without the use of the yield keyword.So here is what I got so far : It seems to work . However , I have trouble to follow it 's control flow . As you can see , I chain to projections . This causes to let strange things ( strange for me ! ) happen in the MoveNext ( ) method . If you set breakpoints in every line of the MoveNext ( ) method you will see that the control flow actually jumps between the different instances and never works through the method in one batch . It 's jumping as if it were using different threads or if we were using yield . But in the end , it 's just a normal method so I wonder what 's going on there ? <code> class Program { static void Main ( string [ ] args ) { var list = new int [ ] { 1 , 2 , 3 } ; var otherList = list.MySelect ( x = > x.ToString ( ) ) .MySelect ( x = > x + `` test '' ) ; foreach ( var item in otherList ) { Console.WriteLine ( item ) ; } Console.ReadLine ( ) ; } } public static class EnumerableEx { public static IEnumerable < R > MySelect < T , R > ( this IEnumerable < T > sequence , Func < T , R > apply ) { return new EnumerableWrapper < R , T > ( sequence , apply ) ; } } public class EnumerableWrapper < T , O > : IEnumerable < T > { private readonly IEnumerable < O > _sequence ; private readonly Func < O , T > _apply ; public EnumerableWrapper ( IEnumerable < O > sequence , Func < O , T > apply ) { _sequence = sequence ; _apply = apply ; } public IEnumerator < T > GetEnumerator ( ) { return new EnumeratorWrapper < T , O > ( _sequence , _apply ) ; } IEnumerator IEnumerable.GetEnumerator ( ) { return GetEnumerator ( ) ; } } public class EnumeratorWrapper < T , O > : IEnumerator < T > { private readonly IEnumerator < O > _enumerator ; private readonly Func < O , T > _apply ; public EnumeratorWrapper ( IEnumerable < O > sequence , Func < O , T > apply ) { _enumerator = sequence.GetEnumerator ( ) ; _apply = apply ; } public void Dispose ( ) { } public bool MoveNext ( ) { var hasItems = _enumerator.MoveNext ( ) ; if ( hasItems ) Current = _apply ( _enumerator.Current ) ; return hasItems ; } public void Reset ( ) { _enumerator.Reset ( ) ; } public T Current { get ; private set ; } object IEnumerator.Current { get { return Current ; } } } | Implementing Linqs Select without the yield keyword . Ca n't follow the control flow |
C_sharp : I have an total amount payable by an Employer this amount needs to be split amongst staff.For exampleThe total amount payable is the sum of all items , in this case $ 400The problem is I must call a 3rd party system to assign these amounts one by one . But I can not let the balance go below $ 0 or above the total amount ( $ 400 ) during the allocation.So if I insert in the above order a , b , c will work so the current allocated sum = 100 + 200 - 200 = $ 100.However when I try to allocate d. The system will try to add - $ 200 which will make the current allocated sum - $ 100 which is < $ 0 which is not allowed so it will be rejected by the system.If I sort the list so negative items are last . i.e.a will work , b will work , but when it tries to insert e there will be insufficient funds error because we have exceeded the maximum of $ 400 . I have come to the realisation that there is no silver bullet and there will always be scenarios what will break . However I wanted to come up with a solution that would work most of the time.Normal sample of data would have between 5 - 100 items . With only 2-15 % of those containing negative amounts.Is there a clever way I can sort the list ? Or would it be better just to try an allocated multiple times . For example split the positive and negatives into two list . Insert positives until one errors , then insert negatives until it errors then switch back and forth between the list until it is all allocated or until both of them error . <code> a $ 100b $ 200c - $ 200d - $ 200e $ 500 a $ 100b $ 200e $ 500c - $ 200d - $ 200 | Allocate money in particular order |
C_sharp : I just stumbled upon this fragment of code , I was wondering why the Count is done during the loop.If the count can change , shouldn ’ t we just do it like this instead : for ( int i = source.Count ( ) - 1 ; i > = 0 ; i -- ) Otherwise , I think we should calculate the count before the looping starts , instead of every time.What would be the correct way to do this ? <code> /// < summary > /// find the first index in a sequence to satisfy a condition /// < /summary > /// < typeparam name= '' T '' > type of elements in source < /typeparam > /// < param name= '' source '' > sequence of items < /param > /// < param name= '' predicate '' > condition of item to find < /param > /// < returns > the first index found , or -1 if not found < /returns > public static int FindIndex < T > ( this IEnumerable < T > source , Predicate < T > predicate ) { for ( int i = 0 ; i < source.Count ( ) ; i++ ) { if ( predicate ( source.ElementAt ( i ) ) ) return i ; } return -1 ; // Not found } | IEnumerable.Count ( ) O ( n ) |
C_sharp : Consider this code : Inside the function , I want to know if a value has been sent to Variable1 & Variable2 , prior to the function call , even if the DEFAULT values have been sent , that 's ok ( null for string & 0 for int ) <code> public string Variable1 { get ; set ; } public int Variable2 { get ; set ; } public void Function ( ) { // Has been Variable1 Initialized ? } | Ensure Variable Initialization C # |
C_sharp : When I am using this code as web view , it works fine , but when with developer option in Chrome I select Mobile View , FormCollection shows empty strings in the controllerVIEW ( Edit updtaed ) ControllerNormal View ( Web View ) Mobile View <code> < div class= '' page product-details-page deal-product-details-page '' > @ using ( Html.BeginForm ( `` AddProductToCart_Details '' , `` DealProduct '' , new { productId = Model.Id , shoppingCartTypeId = 1 } , FormMethod.Post ) ) { < div class= '' page-body '' > @ using ( Html.BeginRouteForm ( `` Product '' , new { SeName = Model.SeName } , FormMethod.Post , new { id = `` product-details-form '' } ) ) { @ { var dataDictAttributes = new ViewDataDictionary ( ) ; dataDictAttributes.TemplateInfo.HtmlFieldPrefix = string.Format ( `` attributes_ { 0 } '' , Model.Id ) ; @ Html.Partial ( `` ~/Views/Product/_ProductAttributes.cshtml '' , Model.ProductAttributes , dataDictAttributes ) } < ! -- gift card -- > @ { var dataDictGiftCard = new ViewDataDictionary ( ) ; dataDictGiftCard.TemplateInfo.HtmlFieldPrefix = string.Format ( `` giftcard_ { 0 } '' , Model.Id ) ; @ Html.Partial ( `` ~/Views/Product/_GiftCardInfo.cshtml '' , Model.GiftCard , dataDictGiftCard ) } < ! -- rental info -- > @ { var dataDictRental = new ViewDataDictionary ( ) ; dataDictRental.TemplateInfo.HtmlFieldPrefix = string.Format ( `` rental_ { 0 } '' , Model.Id ) ; @ Html.Partial ( `` ~/Views/Product/_RentalInfo.cshtml '' , Model , dataDictRental ) } < ! -- price & add to cart -- > @ { var dataDictPrice = new ViewDataDictionary ( ) ; dataDictPrice.TemplateInfo.HtmlFieldPrefix = string.Format ( `` price_ { 0 } '' , Model.Id ) ; @ Html.Partial ( `` ~/Views/Product/_ProductPrice.cshtml '' , Model.ProductPrice , dataDictPrice ) @ Html.Partial ( `` ~/Views/Product/_ProductTierPrices.cshtml '' , Model.TierPrices ) } < ! -- wishlist , compare , email a friend -- > < ! -- attributes -- > @ { var item = @ Model.AssociateProductAttributesList.Where ( x = > x.Item1 == data.Id ) .Select ( x = > x.Item2 ) .ToList ( ) [ 0 ] ; bool isAttributes =false ; } < div class= '' popup '' data-popup= '' popup- @ data.Id '' > < div class= '' popup-inner '' > < h2 > @ data.Name < /h2 > < p > @ data.ShortDescription < /p > < br / > @ foreach ( System.Collections.DictionaryEntry value in item ) { var val = data.Id + `` _ '' + value.Key.ToString ( ) ; isAttributes = true ; @ * < div class= '' attributes '' > * @ < dl > < dt id= '' product_attribute_label_19 '' > < label class= '' text-prompt '' > @ value.Key.ToString ( ) < /label > < /dt > < dd id= '' product_attribute_input_19 '' class= '' product_attribute_inputdiv_ @ val '' > @ Html.DropDownList ( `` Attributes , '' + data.Id + `` , '' + value.Key.ToString ( ) , new SelectList ( ( System.Collections.IEnumerable ) value.Value , `` Id '' , `` Name '' ) , `` -- - Please select -- - '' ) < /dd > < /dl > @ * < /div > * @ } < br / > < div onclick= '' ImageBlur ( 'div_ @ data.Id ' ) '' class= '' buttons '' style= '' text-align : left ; '' > < input class= '' button-1 '' data-popup-close= '' popup- @ data.Id '' type= '' button '' value= '' Add to back '' / > < /div > < a class= '' popup-close '' data-popup-close= '' popup- @ data.Id '' href= '' # '' > x < /a > < /div > < /div > @ if ( item.Count == 0 ) { @ Html.Hidden ( `` Attributes , '' + data.Id + `` , '' , `` 0 '' ) < div class= '' popup '' data-popup= '' popup- @ data.Id '' > < div class= '' popup-inner '' > < h2 > @ data.Name < /h2 > < p > @ data.ShortDescription < /p > < div onclick= '' ImageBlur ( 'div_ @ data.Id ' ) '' class= '' buttons '' style= '' text-align : left ; '' > < input class= '' button-1 '' data-popup-close= '' popup- @ data.Id '' type= '' button '' value= '' Add to back '' / > < /div > < a class= '' popup-close '' data-popup-close= '' popup- @ data.Id '' href= '' # '' > x < /a > < /div > < /div > } @ if ( isAttributes ) { < a style= '' color : blue ; '' data-popup-open= '' popup- @ data.Id '' href= '' # '' > < img id= '' imgdiv_ @ data.Id '' src= '' ~/Themes/Playground/Content/img/dealselectattribut.png '' class= '' select-atr-img '' style= '' width : 50 % ; margin-bottom : 10px ; '' / > < /a > } < /div > } < /div > < div > < /div > @ { var dataDictAddToCart = new ViewDataDictionary ( ) ; dataDictAddToCart.TemplateInfo.HtmlFieldPrefix = string.Format ( `` addtocart_ { 0 } '' , Model.Id ) ; < div class= '' overview '' style= '' width:100 % ; margin-left : auto '' > @ Html.Partial ( `` ~/Views/Product/_AddToCart.cshtml '' , Model.AddToCart , dataDictAddToCart ) < /div > } < /div > } < /div > } < /div > public ActionResult AddProductToCart_Details ( int productId , int shoppingCartTypeId , FormCollection form ) { if ( _productService.IsDealProducts ( productId ) ) { if ( ! IsCompleteSelected ( form ) ) { return Json ( new { success = false , message = `` Plese select all associated product attribute `` } ) ; } } //more code here } | FormCollection Empty in ASP.NET Mobile View |
C_sharp : I 'm trying to write generic algorithms in C # that can work with geometric entities of different dimension . In the following contrived example I have Point2 and Point3 , both implementing a simple IPoint interface.Now I have a function GenericAlgorithm that calls a function GetDim . There are multiple definitions of this function based on the type . There is also a fall-back function that is defined for anything that implements IPoint . I initially expected the output of the following program to be 2 , 3 . However , it is 0 , 0 . OK , so for some reason the concrete type information is lost in GenericAlgorithm . I do n't fully understand why this happens , but fine . If I ca n't do it this way , what other alternatives do I have ? <code> interface IPoint { public int NumDims { get ; } } public struct Point2 : IPoint { public int NumDims = > 2 ; } public struct Point3 : IPoint { public int NumDims = > 3 ; } class Program { static int GetDim < T > ( T point ) where T : IPoint = > 0 ; static int GetDim ( Point2 point ) = > point.NumDims ; static int GetDim ( Point3 point ) = > point.NumDims ; static int GenericAlgorithm < T > ( T point ) where T : IPoint = > GetDim ( point ) ; static void Main ( string [ ] args ) { Point2 p2 ; Point3 p3 ; int d1 = GenericAlgorithm ( p2 ) ; int d2 = GenericAlgorithm ( p3 ) ; Console.WriteLine ( `` { 0 : d } '' , d1 ) ; // returns 0 ! ! Console.WriteLine ( `` { 0 : d } '' , d2 ) ; // returns 0 ! ! } } | C # generics method selection |
C_sharp : I have a list of sorts stored in this format : And I need to turn it into a lambda expression of type Action < DataSourceSortDescriptorFactory < TModel > > So assuming I have the following collection of Report Sorts as : I would need to transform it into such a statement to be used like so : And the sort method signature is : So I have some method right now : ... and I have no idea what to do here.EDIT : Answer is : I was thinking at first I had to dynamically build a lambda expression from scratch using the Expression class . Luckily that was n't the case . <code> public class ReportSort { public ListSortDirection SortDirection { get ; set ; } public string Member { get ; set ; } } new ReportSort ( ListSortDirection.Ascending , `` LastName '' ) , new ReportSort ( ListSortDirection.Ascending , `` FirstName '' ) , .Sort ( sort = > { sort.Add ( `` LastName '' ) .Ascending ( ) ; sort.Add ( `` FirstName '' ) .Ascending ( ) ; } ) public virtual TDataSourceBuilder Sort ( Action < DataSourceSortDescriptorFactory < TModel > > configurator ) public static Action < DataSourceSortDescriptorFactory < TModel > > ToGridSortsFromReportSorts < TModel > ( List < ReportSort > sorts ) where TModel : class { Action < DataSourceSortDescriptorFactory < TModel > > expression ; //stuff I do n't know how to do return expression ; } var expression = new Action < DataSourceSortDescriptorFactory < TModel > > ( x = > { foreach ( var sort in sorts ) { if ( sort.SortDirection == System.ComponentModel.ListSortDirection.Ascending ) { x.Add ( sort.Member ) .Ascending ( ) ; } else { x.Add ( sort.Member ) .Descending ( ) ; } } } ) ; | Dynamically build lambda expression from a collection of objects ? |
C_sharp : I have two similar methods that basically does the same thing only with different objects.What 's the best way to make a generic method out of this if possible ? The two objects : The two methods that I potentially want to make into a generic : I must note that : - I have no control over how the table fields are named ( ie . p_description ) .- StoreTable in the DB , for example , may have other properties ( like telephone , postal code , etc ) but I 'm only interested in showing what I 've shown in the code.- The same goes for the ProjectTable . <code> public class StoreObject { int Key ; string Address ; string Country ; int Latitude ; int Longitude ; } public class ProjectObject { int ProjectKey ; string Address ; string Description ; } public StoreObject GetStoreByKey ( int key ) { using ( DBEntities dbe = new DBEntities ( ) ) { StoreObject so = new StoreObject ( ) ; var storeObject = ( from s in dbe.StoreTables where s.Key == key select s ) .First ( ) ; so.Key = storeObject.key ; so.Address = storeObject.address ; so.Country = storeObject.country ; so.Latitude = storeObject.latitude ; so.Longitude = storeObject.longitude ; return so ; } } public ProjectObject GetProjectByKey ( int projectKey ) { using ( DBEntities dbe = new DBEntities ( ) ) { ProjectObject po = new ProjectObject ( ) ; var projectObject = ( from p in dbe.ProjectTables where p.ProjectKey == projectKey select p ) .First ( ) ; po.Key = projectObject.p_key ; po.Address = projectObject.p_address ; po.Description = projectObject.p_description ; return po ; } } | How to create a generic method out of two similar yet different methods ? |
C_sharp : According to the Best Practices section of the MSDN documentation for the System.Enum class : Do not define an enumeration value solely to mirror the state of the enumeration itself . For example , do not define an enumerated constant that merely marks the end of the enumeration . If you need to determine the last value of the enumeration , check for that value explicitly . In addition , you can perform a range check for the first and last enumerated constant if all values within the range are valid.If I understand correctly , we should n't declare an enum as follows.Why is this considered bad practice ? <code> public enum DrawOrder { VeryBottom = 0 , Bottom = 1 , Middle = 2 , Top = 3 , Lowest = VeryBottom , //marks a position in the enum Highest = Top , //marks a position in the enum } | Why are position markers , like first or last , in an Enumeration considered bad practice ? |
C_sharp : I am new to .Net Framework and I want to add validations to my windows form application in Visual Studio 2010 IDE . I have searched for different ways to do it but I am not sure where can i add that code in my form ? One of the example being the code below . Do I add this code on form load method or on submit button or somewhere else ? <code> using System ; using System.Data.Entity ; using System.ComponentModel.DataAnnotations ; namespace MvcMovie.Models { public class Movie { public int ID { get ; set ; } [ Required ( ErrorMessage = `` Title is required '' ) ] public string Title { get ; set ; } [ Required ( ErrorMessage = `` Date is required '' ) ] public DateTime ReleaseDate { get ; set ; } [ Required ( ErrorMessage = `` Genre must be specified '' ) ] public string Genre { get ; set ; } [ Required ( ErrorMessage = `` Price Required '' ) ] [ Range ( 1 , 100 , ErrorMessage = `` Price must be between $ 1 and $ 100 '' ) ] public decimal Price { get ; set ; } [ StringLength ( 5 ) ] public string Rating { get ; set ; } } public class MovieDBContext : DbContext { public DbSet < Movie > Movies { get ; set ; } } } | Validating my form |
C_sharp : This question has been bugging me for a while : I 've read in MSDN 's DirectX article the following : The destructor ( of the application ) should release any ( Direct2D ) interfaces stored ... Now , if all of the application 's data is getting released/deallocated at the termination ( source ) why would I go through the trouble to make a function in-order-to/and release them individually ? it makes no sense ! I keep seeing this more and more over the time , and it 's obviously really bugging me.The MSDN article above is the first time I 've encountered this , so it made sense to mention it of all other cases . Well , since so far I did n't actually ask my questions , here they are : Do I need to release something before termination ? ( do explain why please ) Why did the author in MSDN haven chosen to do that ? Does the answer differ from native & managed code ? I.E . Do I need to make sure everything 's disposed at the end of the program while I 'm writing a C # program ? ( I do n't know about Java but if disposal exists there I 'm sure other members would appreciate an answer for that too ) .Thank you ! <code> DemoApp : :~DemoApp ( ) { SafeRelease ( & m_pDirect2dFactory ) ; SafeRelease ( & m_pRenderTarget ) ; SafeRelease ( & m_pLightSlateGrayBrush ) ; SafeRelease ( & m_pCornflowerBlueBrush ) ; } | Cleanup before termination ? |
C_sharp : I thought the method that is getting called is decided runtime , or have I missed something ? Sample code : I thought I would get : as output but it prints Base impl . Is there anything I can do to get the overloaded method without casting the input ? <code> class Program { static void Main ( string [ ] args ) { var magic = new MagicClass ( ) ; magic.DoStuff ( new ImplA ( ) ) ; magic.DoStuff ( new ImplB ( ) ) ; Console.ReadLine ( ) ; } } class MagicClass { internal void DoStuff < T > ( T input ) where T : SomeBase { HiThere ( input ) ; } void HiThere ( SomeBase input ) { Console.WriteLine ( `` Base impl '' ) ; } void HiThere ( ImplA input ) { Console.WriteLine ( `` ImplA '' ) ; } void HiThere ( ImplB input ) { Console.WriteLine ( `` ImplB '' ) ; } } abstract class SomeBase { } class ImplA : SomeBase { } class ImplB : SomeBase { } ImplAImplB | Why is n't the overloaded method getting called ? |
C_sharp : Starting from C # 7.0 the throw keyword can be used both as an expression and as a statement , which is nice.Though , consider these overloadsWhen invoking like thisor even like this ( with a statement lambda ) the M ( Func < > ) overload is selected by the compiler indicating that the throw is here considered as an expression.How can I elegantly and intent-clear force the compiler to select the M ( Action ) overload ? One way to do it is thisbut the reason for the return statement seems non-obvious , and runs the risk of being changed by the next developer especially since Resharper warns about the unreachable code . ( Of course I can change the method naming to avoid overloading , but that is not the question . : - ) <code> public static void M ( Action doIt ) { /*use doIt*/ } public static void M ( Func < int > doIt ) { /*use doIt*/ } M ( ( ) = > throw new Exception ( ) ) ; M ( ( ) = > { throw new Exception ( ) ; } ) ; M ( ( ) = > { throw new Exception ( ) ; return ; } ) ; | How can I force a throw to be a statement and not an expression ( in a lambda expression ) ? |
C_sharp : I come across this regularly when refactoring code . Say I have a base class and I read some configuration parameters and stuff them into properties like this And then I call a method in another class like thisIs it better to do that ? What if I only needed the AppSettings values inside of the OtherClass class ? then I could just load them up as private props and initialize them in the constructor and the referencing class/caller would n't need to be concerned with the settings.My implementation would then simply be This one bugs me but I am not really sure why . Which is a better practice and why ? And I apologise I am missing something obvious . It happens sometimes lol.Thanks -Frank <code> public BaseClass ( ) { _property1 = ConfigurationManager.AppSettings [ `` AppSetting1 '' ] ; _property2 = ConfigurationManager.AppSettings [ `` AppSetting2 '' ] ; _property3 = ConfigurationManager.AppSettings [ `` AppSetting3 '' ] ; } OtherClass otherClass = new OtherClass ( ) ; var foo = otherClass.SomeMethod ( _property1 , _property2 , _property3 ) ; public OtherClass ( ) { _property1 = ConfigurationManager.AppSettings [ `` AppSetting1 '' ] ; _property2 = ConfigurationManager.AppSettings [ `` AppSetting2 '' ] ; _property3 = ConfigurationManager.AppSettings [ `` AppSetting3 '' ] ; } OtherClass otherClass = new OtherClass ( ) ; var foo = otherClass.SomeMethod ( ) ; | Passing config values as parameters to an instance method C # |
C_sharp : In all the .NET book I 've read the guide line for implementing events explains that you need to subclass EventArgs and use EventHandler . I looked up more info on http : //msdn.microsoft.com/en-us/library/ms229011.aspx , and it says `` Do use System.EventHandler instead of manually creating new delegates to be used as event handlers . '' I understand that there are important reasons to use EventArgs , but my question is not `` Should I do it this way ? `` , but `` Can I do it this way ? '' . Is there any reason that I ca n't use a generic delegate instead of an EventHandler with my events ? For example , if I want a strongly-typed sender ( anyone else get annoyed by that object sender ? ) .To explain what I mean better , is there any reason the following wo n't work ? <code> public class IoC { public AbstractFactory GetAbstractFactory ( ) { var factory = new AbstractFactory ( ) ; factory.CreateObject += ( ) = > new object ( ) ; return factory ; } } public class AbstractFactory { public event Func < object > CreateObject ; private object OnObjectCreated ( ) { if ( CreateObject == null ) { throw new Exception ( `` Not injected . `` ) ; } return CreateObject ( ) ; } private object _injectedObject ; public object InjectedObject { get { if ( _injectedObject == null ) { _injectedObject = OnObjectCreated ( ) ; } return _injectedObject ; } } } | Is there a special association between the EventArgs class and the event keyword ? |
C_sharp : I have a problem with this code : I set TermEndDate = DateTime.Now but no message raises ! My test code is : <code> RuleFor ( field = > field.TermEndDate ) .NotEmpty ( ) .When ( x = > x.TermEndDate == x.TermStartDate ) .WithMessage ( `` error ... '' ) ; var now = DateTime.Now ; var command = new AddTermCommand { SchoolId = Guid.NewGuid ( ) , TermStartDate = now , TermEndDate = now } ; var cmd = command.Validate ( ) ; if ( ! cmd.IsValid ) Console.WriteLine ( cmd.Errors.First ( ) .ErrorMessage ) ; | FluentValidation when does not raises any message |
C_sharp : If I create a .NET class which subscribes to an event with an anonymous function like this : Will this event handler be a root keeping my class from being garbage collected ? If not , wohoo ! But if so , can you show me the removal syntax ? Just using -= with the same code seems wrong . <code> void MyMethod ( ) { Application.Current.Deactivated += ( s , e ) = > { ChangeAppearance ( ) ; } ; } | Do I need to remove this sort of event handler ? |
C_sharp : I have:1 ) How I may get List < Graph > from database where Points is not empty ? 2 ) How to execute it ? The exception is : LINQ to Entities does not recognize the method ' ... ' method , and this method can not be translated into a store expression . <code> private Dictionary < int , Сolor [ ] > colorSet = new Dictionary < int , Сolor [ ] > ( ) { { 1 , new Сolor [ 2 ] { Сolor.Red , Сolor.Green } } , { 2 , new Сolor [ 2 ] { Сolor.Yellow , Сolor.Blue } } , ... } ; public class Graph { public Сolor Сolor { get ; set ; } public ICollection < Point > Points { get ; set ; } } List < Graph > graphs = context.Graphs.Where ( g = > g.Points.Count > 0 ) .ToList ( ) List < Graph > graphs = context.Graphs.Where ( g = > colorSet [ 1 ] .Contains ( g.Color ) ) .ToList ( ) | C # Linq - get objects with not empty collection |
C_sharp : Consider the following code : Now when I call both generic functions , one succeeds and one fails : Apparently , G.enericFunction2 executes the default operator== implementation instead of my override . Can anybody explain why this happens ? <code> class CustomClass { public CustomClass ( string value ) { m_value = value ; } public static bool operator == ( CustomClass a , CustomClass b ) { return a.m_value == b.m_value ; } public static bool operator ! = ( CustomClass a , CustomClass b ) { return a.m_value ! = b.m_value ; } public override bool Equals ( object o ) { return m_value == ( o as CustomClass ) .m_value ; } public override int GetHashCode ( ) { return 0 ; /* not needed */ } string m_value ; } class G { public static bool enericFunction1 < T > ( T a1 , T a2 ) where T : class { return a1.Equals ( a2 ) ; } public static bool enericFunction2 < T > ( T a1 , T a2 ) where T : class { return a1==a2 ; } } var a = new CustomClass ( `` same value '' ) ; var b = new CustomClass ( `` same value '' ) ; Debug.Assert ( G.enericFunction1 ( a , b ) ) ; // SucceedsDebug.Assert ( G.enericFunction2 ( a , b ) ) ; // Fails | Using overloaded operator== in a generic function |
C_sharp : I happened to read this line of code : Where can I find the document on msdn about the syntax of using `` this '' in property ? And is there any book covers this kind of tricky syntax of C # other than the common stuff ? <code> public MyArray this [ int index ] { get { return array [ index ] ; } } | What is this syntax : using `` this '' in property in C # ? |
C_sharp : I 'm working on a progress wizard . I defined it as a style based on the ItemsControl . I have an ItemTemplateSelector with two DataTemplates , one for the first item and one for the rest of the items . I have it working correctly except for one really small issue that is super tricky to fix . There is a gap between the first item and the second item . This is what the control should look like : The gap occurs because I 'm using a uniform grid and so all of the columns are sized the same , even though the first one has no line . Using a uniform grid is important though because I want everything on one row and I want the control to stretch to fill the available space as it grows . I 've tried not using the uniform grid but I end up either having issues with the margins or with not filling the available space . how can I fix this gap ? Here 's the code : <code> < Style x : Key= '' WizardProgressBar '' TargetType= '' { x : Type ItemsControl } '' > < Style.Resources > < DataTemplate x : Key= '' FirstItem '' > < Grid > < Grid.ColumnDefinitions > < ColumnDefinition Width= '' Auto '' / > < /Grid.ColumnDefinitions > < Ellipse Name= '' ellipse '' HorizontalAlignment= '' Left '' Height= '' 32 '' Width= '' 32 '' / > < /Grid > < DataTemplate.Triggers > < DataTrigger Binding= '' { Binding Completed } '' Value= '' False '' > < Setter TargetName= '' ellipse '' Property= '' Stroke '' Value= '' { DynamicResource DisabledBrush } '' / > < /DataTrigger > < DataTrigger Binding= '' { Binding InProgress } '' Value= '' True '' > < Setter TargetName= '' ellipse '' Property= '' Stroke '' Value= '' { DynamicResource PrimaryTextBrush } '' / > < /DataTrigger > < /DataTemplate.Triggers > < /DataTemplate > < DataTemplate x : Key= '' OtherItem '' > < Grid > < Grid.ColumnDefinitions > < ColumnDefinition Width= '' * '' / > < ColumnDefinition Width= '' Auto '' / > < /Grid.ColumnDefinitions > < Ellipse Name= '' ellipse '' Grid.Column= '' 1 '' HorizontalAlignment= '' Left '' Height= '' 32 '' Width= '' 32 '' / > < Line Name= '' leftPath '' Grid.Column= '' 0 '' X1= '' 0 '' Y1= '' 16 '' X2= '' { Binding ActualWidth , Mode=OneWay , RelativeSource= { RelativeSource FindAncestor , AncestorType= { x : Type Grid } } } '' Y2= '' 16 '' / > < /Grid > < DataTemplate.Triggers > < DataTrigger Binding= '' { Binding Completed } '' Value= '' False '' > < Setter TargetName= '' ellipse '' Property= '' Stroke '' Value= '' { DynamicResource DisabledBrush } '' / > < Setter TargetName= '' leftPath '' Property= '' Stroke '' Value= '' { DynamicResource DisabledBrush } '' / > < /DataTrigger > < DataTrigger Binding= '' { Binding InProgress } '' Value= '' True '' > < Setter TargetName= '' ellipse '' Property= '' Stroke '' Value= '' { DynamicResource PrimaryTextBrush } '' / > < Setter TargetName= '' leftPath '' Property= '' Stroke '' Value= '' { DynamicResource PrimaryTextBrush } '' / > < /DataTrigger > < /DataTemplate.Triggers > < /DataTemplate > < /Style.Resources > < Setter Property= '' ItemsPanel '' > < Setter.Value > < ItemsPanelTemplate > < UniformGrid Rows= '' 1 '' / > < /ItemsPanelTemplate > < /Setter.Value > < /Setter > < Setter Property= '' ItemTemplateSelector '' > < Setter.Value > < wpf : ItemsDataTemplateSelector FirstItem= '' { StaticResource FirstItem } '' OtherItem= '' { StaticResource OtherItem } '' / > < /Setter.Value > < /Setter > < /Style > public class ItemsDataTemplateSelector : DataTemplateSelector { public DataTemplate FirstItem { get ; set ; } public DataTemplate OtherItem { get ; set ; } public override DataTemplate SelectTemplate ( object item , DependencyObject container ) { var itemsControl = ItemsControl.ItemsControlFromItemContainer ( container ) ; var returnTemplate = ( itemsControl.ItemContainerGenerator.IndexFromContainer ( container ) == 0 ) ? FirstItem : OtherItem ; return returnTemplate ; } } | Uniform Grid as Panel Template for All Items in ItemsControl Except the First |
C_sharp : In C # , is it possible to write something like this : I know that the above implementation does not compile , but what I am actually trying to achive is implementing some kind of generic wrapper to an unknown type , so that an client can call the wrapper just as he would call the type , provided by the parameter T , instead of calling it using something like wrapper.Instance.SomeMember ( ) .Thanks in advance ! <code> public class MyClass < T > : T where T : class , new ( ) { } | Is it possible to make an object expose the interface of an type parameter ? |
C_sharp : There 's probably 5 or 6 SO posts that tangentially touch on this , but none really answer the question.I have a Dictionary object I use kind of as a cache to store values . The problem is I do n't know how big it is getting -- over time it might be growing big or not , but I can not tell and so I ca n't gauge its effectiveness , or make conclusions about how a user is using the software . Because this is a piece that will go into production and monitor something over a very long period of time , it does n't make sense to attach memory profiler or anything debuggy like that.Ideally , I would simply place a call in my Timer that would do something like : Can this be done without attaching some debug tool so that it can be used deployed scenario ? <code> private void someTimer_Tick ( object sender , EventArgs e ) { ... float mbMem = cacheMap.GetMemorySize ( ) ; RecordInLog ( DateTime.Now.ToString ( ) + `` : mbMem is using `` + mbMem.ToString ( ) + `` MB of memory '' ) ; ... } | Logging the memory usage of an object |
C_sharp : Why do explicit C # interface calls within a generic method that has an interface type constraint always call the base implementation ? For example , consider the following code : This code outputs the following : IDerived.Method IBase.MethodInstead of what one might expect : IDerived.Method IDerived.MethodThere seems to be no way ( short of reflection ) to call a hidden , more derived explicit interface implementation of a type decided at runtime.EDIT : To be clear , the following if check evaluates to true in the GenericMethod call above : if ( typeof ( T ) == typeof ( IDerived ) ) So the answer is not that T is always treated as IBase due to the generic type constraint `` where T : class , IBase '' . <code> public interface IBase { string Method ( ) ; } public interface IDerived : IBase { new string Method ( ) ; } public class Foo : IDerived { string IBase.Method ( ) { return `` IBase.Method '' ; } string IDerived.Method ( ) { return `` IDerived.Method '' ; } } static class Program { static void Main ( ) { IDerived foo = new Foo ( ) ; Console.WriteLine ( foo.Method ( ) ) ; Console.WriteLine ( GenericMethod < IDerived > ( foo ) ) ; } private static string GenericMethod < T > ( object foo ) where T : class , IBase { return ( foo as T ) .Method ( ) ; } } | Why do explicit interface calls on generics always call the base implementation ? |
C_sharp : I 've two interfaces : And two classes implementing these interfaces like this : When trying to use these classes as shown : I get this compiler error : can not convert from 'ClassB ' to 'IAmB < IAmA > ' I know I can make the compiler happy using : But I need to be able to be the Type parameter for IAmB < > in ClassB an implementation of IAmA . <code> public interface IAmA { } public interface IAmB < T > where T : IAmA { } public class ClassA : IAmA { } public class ClassB : IAmB < ClassA > { } public class Foo { public void Bar ( ) { var list = new List < IAmB < IAmA > > ( ) ; list.Add ( new ClassB ( ) ) ; } } public class ClassB : IAmB < IAmA > { } | C # Generics , interfaces and inheritance |
C_sharp : I have the following code in my classThis code works in that when I dispose my class any events that are hooked up to the Received event , will be removed individually.I 've been wondering if rather than being so verbose about it , if the following terse version will have the same effectBasically this comes down to how the operator overloads have been created by Microsoft when implementing the delegate overloads . I know that all the documentation says to use the += to subscribe and -= to unsubscribe from an event . I 've also seen the document say that the event will be assigned to null when the last subscriber is removed . What the documentation does not say is whether assigning the event to null , will have the effect of unsubscribing all the events ? I 'd love to know if this is possible , and if there is any documentation that says that the possible terse code is correct behaviour . Update : I 've been doing some more digging with the c # compiler and have found that the assignment to null only works within the class where the event is defined . The += and -= is always available from both inside and outside the class . This leads me to be thinking that using the = null version is acceptable . However , this is speculation , I still have not seen any documentation that states explicitly states this is supported functionality . <code> public class Receiver : IReceiver { public event EventHandler Received ; public void Dispose ( ) { Dispose ( true ) ; GC.SuppressFinalize ( this ) ; } protected virtual void Dispose ( bool disposing ) { if ( disposing ) { if ( Received ! = null ) { foreach ( EventHandler delegateMember in Received.GetInvocationList ( ) ) { Received -= delegateMember ; } } } } } protected virtual void Dispose ( bool disposing ) { if ( disposing ) { Received = null ; } } | Can you use equals assignment when removing delegate members in a disposing method ? |
C_sharp : I was going through the Martin Odersky 's book Programming in Scala with it 's section on abstract modules , and his paper Scalable Component Abstractions : http : //lampwww.epfl.ch/~odersky/papers/ScalableComponent.pdfMy takeaway is that by making your modules abstract classes instead of objects ( or classic static , global modules like in Java ) : you can the instantiate multiple subclasses and instances of a module with different concrete characteristics . This lets you configure the module differently depending on the circumstances ( e.g . substituting the database component during testing , or the IO component when in a dev environment ) as well as instantiating multiple modules each with their own set of module-scoped mutable state . From what I can understand , on a basic level , it 's only hard requirement is that you can have nested classes , such that the enclosing class can act as a module . It 's other practical requirement is that you can spread out the class definition over multiple files , since a module with a bunch of classes in it is probably more lines of code than most would accept in a single source file.Scala does this with Traits , which bring some other goodies which are nice but not central to the whole spread abstract-module-class over multiple source files idea . C # has partial classes , which provide the same functionality , and also allows nested classes . Presumably some other languages have similar support for nested classes , as well as splitting a class over multiple files . Does this sort of pattern occur anywhere in C # or any other languages ? I would think large projects in many languages face the problem that abstract modules are meant to solve . Is there any reason this `` abstract-class as abstract-module '' thing does n't work , and therefore is not used ? It seems to me a much cleaner solution than the various DI frameworks with offer kind of the same functionality . <code> abstract class myModule { // this is effectively an abstract module , whose concrete // components can be configured by subclassing and instantiating it class thing { } class item { } object stuff { } class element { } object utils { } } | Scala-style abstract modules in C # or other languages ? |
C_sharp : When I insert these values in SqlServer database , the millisecond value changes in a weird wayWhat 's wrong ? Edit : Relevant code : <code> 09/30/2013 05:04:56.599 09/30/2013 05:04:56.59909/30/2013 05:04:56.59909/30/2013 05:04:57.082 2013-09-30 05:04:56.600 2013-09-30 05:04:56.600 2013-09-30 05:04:56.600 2013-09-30 05:04:57.083 com = new SqlCommand ( ) ; com.Connection = con ; com.CommandText = @ '' INSERT INTO [ AuthSourceTimings ] ( [ FileName ] , [ JobID ] , [ JobCreationTime ] , [ JobSendTime ] , [ JobAckTime ] , [ JobDoneTime ] ) VALUES ( @ FileName , @ JobID , @ JobCreationTime , @ JobSendTime , @ JobAckTime , @ JobDoneTime ) `` ; com.Parameters.AddWithValue ( `` @ FileName '' , fileName ) ; com.Parameters.AddWithValue ( `` @ JobID '' , t.JobID ) ; com.Parameters.AddWithValue ( `` @ JobCreationTime '' , t.JobCreationTime == DateTime.MinValue ? ( object ) DBNull.Value : ( object ) t.JobCreationTime ) ; com.Parameters.AddWithValue ( `` @ JobSendTime '' , t.JobSendTime == DateTime.MinValue ? ( object ) DBNull.Value : ( object ) t.JobSendTime ) ; com.Parameters.AddWithValue ( `` @ JobAckTime '' , t.JobAcknowledgementTime == DateTime.MinValue ? ( object ) DBNull.Value : ( object ) t.JobAcknowledgementTime ) ; com.Parameters.AddWithValue ( `` @ JobDoneTime '' , t.JobCompletionTime == DateTime.MinValue ? ( object ) DBNull.Value : ( object ) t.JobCompletionTime ) ; com.ExecuteNonQuery ( ) ; | DateTime inserted in SqlServer changes value |
C_sharp : I have a struct that is defined in a COM library.In my ViewModel I have created an observable instance of this , and want to bind each member of the struct to different controls in a view.ConfigStaticDataDetails variable is updated through a delegate in the COM.Is there a way to catch updates to the members of the struct so that my view reflects the update ? Part of the struct : My : variable : And in XAML : I have tried different ways , but this my current code ( which does n't work ) . <code> public struct ConfigStaticData { public string Callsign ; } private ConfigStaticData _ConfigStaticDataDetails ; public ConfigStaticData ConfigStaticDataDetails { get { return _ConfigStaticDataDetails ; } set { _ConfigStaticDataDetails = value ; OnPropertyChanged ( `` ConfigStaticDataDetails '' ) ; } } < TextBox Name= '' ConfigStaticDataCallsignLabelTxt '' Margin= '' 0,2,0,2 '' Width= '' 230 '' Style= '' { DynamicResource EditableTextBox } '' Text= '' { Binding Source=ConfigStaticDataDetails , Path=Callsign } '' / > | Can I catch updates to members of an observable struct in WPF ? |
C_sharp : I get very strange behaviour of string.Format . I form message like this : The letters in beginning are in Russian . But then , in calling method , i get this string : Äèñïåò÷åð çàêðûë ñîáûòèå Тревога ( `` Тревога на объекте с точки зрения диспетчера '' ) . This seems like string.Format returned non-unicode characters for the hard-coded words . How can i deal with this problem ? P.S . I also faced this in another parts of my app . <code> protected override string GetMessageText ( ManualEventFact reason ) { var messageText = string.Format ( `` Диспетчер закрыл событие { 0 } ( \ '' { 1 } \ '' ) '' , reason.EventTemplate.DisplayName , reason.Text ) ; return messageText ; } | C # String.Format ( ) returns bad characters |
C_sharp : I 'm interested in this part : What 's wrong : One of the parameters of a binary operator must be the containing typeHow I can normaly code this part for mathematic operations ? <code> public class Racional < T > { private T nominator ; private T denominator ; public T Nominator { get { return nominator ; } set { nominator = value ; } } public T Denominator { get { return denominator ; } set { denominator = value ; } } public Racional ( T nominator , T denominator ) { this.nominator = nominator ; this.denominator = denominator ; } public static Racional < int > operator * ( Racional < int > a , Racional < int > b ) { return ( ( int ) ( a.nominator + b.nominator , a.denominator + b.denominator ) ) ; } public override string ToString ( ) { return `` ( `` + this.nominator + `` `` + this.denominator + `` ) '' ; } } public static Racional < int > operator * ( Racional < int > a , Racional < int > b ) { return ( ( int ) ( a.nominator + b.nominator , a.denominator + b.denominator ) ) ; } | Help with mathematic operands in class ( c # ) |
C_sharp : I 'm doing a Unity project where I have the need to convert UTM coordinates to latitudes and longitudes . I have tried several C # solutions , but none of them were accurate enough . But I found some Javascript code that gives out the exact result I 'm looking for ( https : //www.movable-type.co.uk/scripts/latlong-utm-mgrs.html ) . The problem is , when I turned the code into C # , it gives out a different result . Here are the pieces of code I see the problem in : Javascript : And the C # code I converted myself : They should be identical , but the value of A is different . In Javascript it 's 6367449.145823415 ( what I want ) , but C # gives 6367444.6571225897487819833001 . I could just use the Javascript code in my project , but conveniently Unity stopped supporting Javascript just last year . The inputs are the same for both functions . What could be the issue here ? <code> var a = 6378137 ; var f = 1/298.257223563 ; var e = Math.sqrt ( f* ( 2-f ) ) ; var n = f / ( 2 - f ) ; var n2 = n*n , n3 = n*n2 , n4 = n*n3 , n5 = n*n4 , n6 = n*n5 ; var A = a/ ( 1+n ) * ( 1 + 1/4*n2 + 1/64*n4 + 1/256*n6 ) ; var a = 6378137 ; var f = 1 / 298.257223563 ; var e = Math.Sqrt ( f * ( 2 - f ) ) ; var n = f / ( 2 - f ) ; var n2 = n * n ; var n3 = n2 * n ; var n4 = n3 * n ; var n5 = n4 * n ; var n6 = n5 * n ; var A = a / ( 1 + n ) * ( 1 + 1 / 4 * n2 + 1 / 64 * n4 + 1 / 256 * n6 ) ; | C # and Javascript code calculations giving different results |
C_sharp : We use ASP.NET core and have this code : After zipping sourceDirectoryName that contains russian symbols if we open this archive with windows explorer , we see the following : and where the name marked with green is correct , and the name marked with red has its name encoding changed.If we use the following code : We have the same problem . How to fix this problem ? <code> public static void Compress ( string sourceDirectoryName , string destinationArchiveFileName ) { var directoryName = Path.GetFileName ( sourceDirectoryName ) ; var remotePath = sourceDirectoryName.Split ( new [ ] { directoryName } , StringSplitOptions.RemoveEmptyEntries ) .First ( ) ; using ( var zipStream = new MemoryStream ( ) ) { using ( var zip = new ZipArchive ( zipStream , ZipArchiveMode.Create , true , Encoding.UTF8 ) ) { zip.CreateEntry ( string.Concat ( directoryName , directorySlash ) ) ; foreach ( var path in Directory.EnumerateFileSystemEntries ( sourceDirectoryName , `` * '' , SearchOption.AllDirectories ) ) { if ( ! Directory.Exists ( path ) ) zip.CreateEntryFromFile ( path , path.RemoveSubString ( remotePath ) .ReplacePathSeparatorOnSlash ( ) ) ; else zip.CreateEntry ( string.Concat ( path.RemoveSubString ( remotePath ) .ReplacePathSeparatorOnSlash ( ) , directorySlash ) ) ; } } using ( var outputZip = new FileStream ( destinationArchiveFileName , FileMode.Create ) ) { zipStream.Seek ( 0 , SeekOrigin.Begin ) ; zipStream.CopyTo ( outputZip ) ; } } } ZipFile.CreateFromDirectory ( sourceDirectoryName , destinationArchiveFileName ) ; | After zipping folder all zip entries change encoding |
C_sharp : When I use a method with a generic parameter to create another object , the generic object is n't selecting the most specific constructor . That sounds confusing , so here 's some sample code to demonstrate what I mean ... Can anyone explain why the output of this program is : ... and how to make the generic Add < T > function call the correct constructor of C ? ? Here 's the code : <code> guid < -- easy - no problem hereobject < -- WHY ? This should also be `` guid '' ? ! void Main ( ) { B b = new B ( ) ; C c = new C ( Guid.Empty ) ; b.Add < Guid > ( Guid.Empty ) ; } public class B { List < C > cs = new List < C > ( ) ; public void Add < T > ( T v ) { cs.Add ( new C ( v ) ) ; } } public class C { public C ( Guid c ) { Console.WriteLine ( `` guid '' ) ; } public C ( object c ) { Console.WriteLine ( `` object '' ) ; } } | Generic method is n't choosing the most specific constructor signature ? |
C_sharp : One of the requirements of the system that I am helping to develop is the ability to import files and we have a set of adapters to process the different types of file ( csv , xml etc . ) we would expect to encounter . During the early part of development we were hard-coding the data adapters via reference and using commands . Obviously when this goes live we would want the situation where we could just write a new adapter and throw the dll into a folder and run the procedure without recompiling the code.To implement this I adapted the code from this question . The code in question is located in the constructor as followsLater when the method runs we have thiswhich successfully loads the data adapters and allows them to be used as I would expect.Now for the question , in the first bit of code we have the line If I change it to the routine crashes before the second bit of code runs at this routineEdit : added the exceptionEndEdit : The DataValidators definately runs before the DataAdapters routine . DataValidators are just bits of code contained in the main code base and check to ensure the imported data is of the expected format . At this point we are just loading them so we can make sure the required ones exist.Looking at the loaded assemblies , both versions of the code load the adapters as required , but the second version loads more than the first as I would expect.So , why does the second version of tempfiles crash at what looks like a completely unrelated part of the code ? And if we add enough data adapters will it cause the code to crash ? <code> string dllLocation = @ '' C : MyLocation\dllLocation '' ; DirectoryInfo dir = new DirectoryInfo ( dllLocation ) ; var tempfiles = dir.GetFiles ( `` *Adapter*.dll '' , SearchOption.AllDirectories ) ; // This will need to be changed when we go live foreach ( var file in tempfiles ) { Assembly tempAssembly = null ; //Before loading the assembly , check all current loaded assemblies in case already loaded //has already been loaded as a reference to another assembly //Loading the assembly twice can cause major issues foreach ( Assembly loadedAssembly in AppDomain.CurrentDomain.GetAssemblies ( ) ) { //Check the assembly is not dynamically generated as we are not interested in these if ( loadedAssembly.ManifestModule.GetType ( ) .Namespace ! = `` System.Reflection.Emit '' ) { //Get the loaded assembly filename string loadedFilename = loadedAssembly.CodeBase.Substring ( loadedAssembly.CodeBase.LastIndexOf ( '/ ' ) + 1 ) ; //If the filenames match , set the assembly to the one that is already loaded if ( loadedFilename.ToUpper ( ) == file.Name.ToUpper ( ) ) { tempAssembly = loadedAssembly ; break ; } } } //If the assembly is not aleady loaded , load it manually if ( tempAssembly == null ) { tempAssembly = Assembly.LoadFrom ( file.FullName ) ; } Assembly a = tempAssembly ; private IEnumerable < IUniversalDataAdapter > DataAdapters { get { foreach ( var asm in AppDomain.CurrentDomain.GetAssemblies ( ) ) { foreach ( var type in asm.GetTypes ( ) .Where ( x = > x.GetInterfaces ( ) .Contains ( typeof ( IUniversalDataAdapter ) ) ) ) { if ( type.IsAbstract ) continue ; // ca n't create abstract classes if ( ! dataAdapters.Any ( y = > y.GetType ( ) .Equals ( type ) ) ) { IUniversalDataAdapter adapter = ( IUniversalDataAdapter ) Activator.CreateInstance ( type ) ; dataAdapters.Add ( adapter ) ; } } } return dataAdapters ; } } var tempfiles = dir.GetFiles ( `` *Adapter*.dll '' , SearchOption.AllDirectories ) ; var tempfiles = dir.GetFiles ( `` *.dll '' , SearchOption.AllDirectories ) ; private IEnumerable < IDataValidator > DataValidators { get { if ( validators.Count == 0 ) { foreach ( var asm in AppDomain.CurrentDomain.GetAssemblies ( ) ) { foreach ( var type in asm.GetTypes ( ) .Where ( x = > x.GetInterfaces ( ) .Contains ( typeof ( IDataValidator ) ) ) ) { if ( ! type.IsAbstract ) { var validator = ( IDataValidator ) Activator.CreateInstance ( type , context ) ; validators.Add ( validator ) ; } } } } return validators ; } } System.Reflection.ReflectionTypeLoadException was unhandled HResult=-2146232830 Message=Unable to load one or more of the requested types . Retrieve the LoaderExceptions property for more information . Source=mscorlib StackTrace : at System.Reflection.RuntimeModule.GetTypes ( RuntimeModule module ) at System.Reflection.RuntimeModule.GetTypes ( ) at System.Reflection.Assembly.GetTypes ( ) at TTi.Data.Pipeline.Server.Common.DataPipeline.get_DataValidators ( ) in C : \Users\anorcross\Source\Workspaces\Universal System\Data\Main\TTi.Data\TTi.Data.Pipeline.Server.Common\DataPipeline.cs : line 124 at TTi.Data.Pipeline.Server.Common.DataPipeline.CheckConfiguration ( DataConfiguration config ) in C : \Users\anorcross\Source\Workspaces\Universal System\Data\Main\TTi.Data\TTi.Data.Pipeline.Server.Common\DataPipeline.cs : line 528 at TTi.Data.Pipeline.Server.Common.DataPipeline.ProcessDataSource ( IDataSource dataSource , DataConfiguration config ) in C : \Users\anorcross\Source\Workspaces\Universal System\Data\Main\TTi.Data\TTi.Data.Pipeline.Server.Common\DataPipeline.cs : line 213 at TTi.Data.Test.Program.ImportTest ( String testFolders ) in C : \Users\anorcross\Source\Workspaces\Universal System\Data\Main\TTi.Data\TTi.Data.Test\Program.cs : line 362 at TTi.Data.Test.Program.Main ( String [ ] args ) in C : \Users\anorcross\Source\Workspaces\Universal System\Data\Main\TTi.Data\TTi.Data.Test\Program.cs : line 48 at System.AppDomain._nExecuteAssembly ( RuntimeAssembly assembly , String [ ] args ) at System.AppDomain.ExecuteAssembly ( String assemblyFile , Evidence assemblySecurity , String [ ] args ) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly ( ) at System.Threading.ThreadHelper.ThreadStart_Context ( Object state ) at System.Threading.ExecutionContext.RunInternal ( ExecutionContext executionContext , ContextCallback callback , Object state , Boolean preserveSyncCtx ) at System.Threading.ExecutionContext.Run ( ExecutionContext executionContext , ContextCallback callback , Object state , Boolean preserveSyncCtx ) at System.Threading.ExecutionContext.Run ( ExecutionContext executionContext , ContextCallback callback , Object state ) at System.Threading.ThreadHelper.ThreadStart ( ) InnerException : | Loading more dll 's into code causes crash |
C_sharp : I have a windows media player embedded in my web page view : The ShowMovie action extracts a video stream from the database and sends it to the view with this : When I use a video with a size of about 10K or so will play fine . But if I use a file that is about 137K or so the file never plays . Is it too large ? When I use F12 to see the network activity I see the file is trying to come down as text/html . Why is that ? I also see that on the GET function that it is aborting . Why is that ? I 've increased the executionTimeout value to no avail.The information from napuza was good I was able to get the correct content type and it seems the entire file was streamed to the browser but it never plays . <code> < div id= '' divCourseVideo '' style= '' width:100 % ; margin:0 auto ; '' class= '' container '' > < OBJECT style= '' display : inline-block '' ID= '' CoursePlayer '' HEIGHT= '' 400 '' WIDTH= '' 400 '' CLASSID= '' CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6 '' type= '' video/x-ms-wmv '' > < param name='URL ' value= '' @ Url.Action ( `` ShowMovie '' , `` OLT '' , new { courseId = Model.ID } ) '' / > < param name='autoStart ' value= '' true '' / > < param name='currentPosition ' value= '' false '' / > < param name='showControls ' value= '' true '' / > < /OBJECT > < /div > public void ShowMovie ( string courseId ) { CourseVideo video = Repository.GetCourseVideoStream ( courseId ) ; var bytesinfile = new byte [ video.VideoStream.Length ] ; video.VideoStream.Read ( bytesinfile , 0 , ( int ) video.VideoStream.Length ) ; ControllerContext.HttpContext.Response.BinaryWrite ( bytesinfile ) ; } | WMV streaming file size limit |
C_sharp : I 'd like to know your opinion on a matter of coding style that I 'm on the fence about . I realize there probably is n't a definitive answer , but I 'd like to see if there is a strong preference in one direction or the other.I 'm going through a solution adding using statements in quite a few places . Often I will come across something like so : where log.Connection is an OracleConnection , which implements IDisposable.The neatnik in me wants to change it to : But the lover of brevity and getting-the-job-done-slightly-faster wants to do : For some reason I feel a bit dirty doing this . Do you consider this bad or not ? If you think this is bad , why ? If it 's good , why ? EDIT : Please note that this is just one ( somewhat contrived ) example of many . Please do n't fixate on the fact that this happens to indicate a logger class with a poorly thought-out interface . This is not relevant to my question , and I 'm not at liberty to improve the classes themselves anyway . <code> { log = new log ( ) ; log.SomeProperty = something ; // several of these log.Connection = new OracleConnection ( `` ... '' ) ; log.InsertData ( ) ; // this is where log.Connection will be used ... // do other stuff with log , but connection wo n't be used again } { using ( OracleConnection connection = new OracleConnection ( `` ... '' ) ) { log = new log ( ) ; log.SomeProperty = something ; log.Connection = conn ; log.InsertData ( ) ; ... } } { log = new log ( ) ; log.SomeProperty = something ; using ( log.Connection = new OracleConnection ( `` ... '' ) ) log.InsertData ( ) ; ... } | A question of style/readability regarding the C # `` using '' statement |
C_sharp : In another question , people are getting incomplete data when reading from a HttpWebResponse via GetResponseStream ( ) .I too encountered this problem when reading data from an embedded device which should send me the configuration of 1000 inputs , all in all 32 bytes header and 64 bytes * 1000 resulting in 64032 bytes of data.Reading the response stream directly only gives me data for the first 61 and a half inputs , from there on only zeros.Version a ) Not working : To visualize the problem , I printed the 64 bytes for each input configuration seperately . It consists basically of 40 ascii chars and a few bytes which represent boolean and integer values.Version A ) Output : When I copy the ResponseStream to a new MemoryStream , I can read all 1000 inputs completely without any corrupt bytes.Version B ) Working perfectly : ( See also https : //stackoverflow.com/a/22354617/6290907 which fixed my problem in the first case ) Version B ) OutputFrom a technical point of view : Why is the HttpWebResponse losing data when accessed directly ? I do n't just want it to work , but I want to understand why version a fails and version b is successfull while both depend on the same source of data ( response.GetResponseStream ( ) ) .What is happening under the hood in this case ? Thank you for your efforts ! <code> int headerSize = 32 ; int inputSize = 64 ; byte [ ] buffer = new byte [ ( inputSize*1000 ) + headerSize ] ; HttpWebResponse response = ( HttpWebResponse ) request.GetResponse ( ) ; using ( Stream stream = response.GetResponseStream ( ) ) { if ( stream ! = null ) { stream.Seek ( 0 , SeekOrigin.Begin ) ; stream.Read ( buffer , 0 , buffer.Length ) ; } } response.Close ( ) ; return buffer ; 1/1000 | 46656E7374657220576F686E656E2020202020202020202020202020202020202020202020202020000000000F0EB0AA000081000000018000001000900100202/1000 | 42574D20576F686E656E202020202020202020202020202020202020202020202020202020202020000000000F0EB0AA00008100000001800000100091010080…61/1000 | 53656E736F72203631202020202020202020202020202020202020202020202020202020202020200000000000000000000010003300000000001000C301000062/1000 | 53656E736F722036322020202020202020202020202020202020202020202020000000000000000000000000000000000000000000000000000000000000000063/1000 | 00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000…999/1000 | 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000/1000 | 00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 int headerSize = 32 ; int inputSize = 64 ; byte [ ] buffer = new byte [ ( inputSize*1000 ) + headerSize ] ; HttpWebResponse response = ( HttpWebResponse ) request.GetResponse ( ) ; using ( Stream stream = response.GetResponseStream ( ) ) { if ( stream ! = null ) { MemoryStream memStream = new MemoryStream ( ) ; stream.CopyTo ( memStream ) ; memStream.Flush ( ) ; stream.Close ( ) ; memStream.Seek ( 0 , SeekOrigin.Begin ) ; memStream.Read ( buffer , 0 , buffer.Length ) ; memStream.Close ( ) ; } } response.Close ( ) ; return buffer ; 1/1000 | 46656E7374657220576F686E656E2020202020202020202020202020202020202020202020202020000000000F0EB0AA000081000000018000001000900100202/1000 | 42574D20576F686E656E202020202020202020202020202020202020202020202020202020202020000000000F0EB0AA00008100000001800000100091010080…61/1000 | 53656E736F72203631202020202020202020202020202020202020202020202020202020202020200000000000000000000010003300000000001000C301000062/1000 | 53656E736F72203632202020202020202020202020202020202020202020202020202020202020200000000000000000000010003300000000001000C301000063/1000 | 53656E736F72203633202020202020202020202020202020202020202020202020202020202020200000000000000000000010003300000000001000C3010000…999/1000 | 53656E736F7220393939202020202020202020202020202020202020202020202020202020202020000000000000000000001000DA030000000010006A0500001000/1000 | 53656E736F7220313030302020202020202020202020202020202020202020202020202020202020000000000000000000001000DB030000000010006B050000 | Why is HttpWebResponse losing data ? |
C_sharp : I am looking into the grammar of C # 5.0 and do n't quite understand the use of `` base '' . In the reference manual , there is a notion of `` base access '' defined as : Where base is a keyword , and it appears that this is the only case . However , I encounter C # inputs such as Can someone point me out which grammar rule this statement refers to ? As 'base ' appears to be a normal keyword , not contextual , I assume that there should be a specific grammar rule for this case , and base can not simply be an identifier . <code> base-access : base . identifier base [ expression-list ] base.WithAdditionalDiagnostics < TNode > ( node , diagnostics ) ; | C # grammar `` base '' |
C_sharp : I currently have a class and I am a bit confused with its constructor . what does the statement this ( new BarInterval [ ] { interval } ) imply ? <code> public class BarListTracker : GotTickIndicator { public BarListTracker ( BarInterval interval ) : this ( new BarInterval [ ] { interval } ) { } } | ` this ` and a class constructor |
C_sharp : I 've read so many articles about this but still I have 2 questions.Question # 1 - Regarding Dependency Inversion : It states that high-level classes should not depend on low-level classes . Both should depend on abstractions . Abstractions should not depend on details . Details should depend on abstractions.for example : The fix : put it in a ctor.If it will be in ctor - I 'll have to send it each and every time I use the class . So I will have to keep it when calling the BirthdayCalculator class . it it ok to do it like that ? I can argue that , after the fix , still - IList < Birthday > _birthdays should not by there ( the Birthday in IList ) - but it should be as IList < IBirthday > . Am I right ? Question # 2 - Regarding Liskov Substitution : derived classes must be substitutable for their base classesor more accurate : Let q ( x ) be a property provable about objects x of type T. Then q ( y ) should be true for objects y of type S where S is a subtype of T. ( already read this ) example : I have a class : and the bank wants to open a Mortgage account - so : The problem arises when there is a function which accepts mortage as Account and do deposit.so here , it violates the LSP.But I do n't understand.every overridden method will do different code when overridden so it will never be 100 % replaceable ! the definition did NOT talk about `` logic should continue as in base class ( always deposit ( add ) positive numbers ) '' example : What if both CheckingAccount class and MortgageAccount class were depositing positive numbers but MortgageAccount also log to db ? does it still breaks LSP ? What is the boundry for breaks/not-brakes LSP ? the definition should define whatis that boundry . and it is n't saying anything about it.what am i missing ? <code> public class BirthdayCalculator { private readonly List < Birthday > _birthdays ; public BirthdayCalculator ( ) { _birthdays = new List < Birthday > ( ) ; // < -- -- - here is a dependency } ... public class BirthdayCalculator { private readonly IList < Birthday > _birthdays ; public BirthdayCalculator ( IList < Birthday > birthdays ) { _birthdays = birthdays ; } public abstract class Account { public abstract void Deposit ( double amount ) ; } public class CheckingAccount : Account { public override void Deposit ( double amount ) { ... _currentBalance += amount ; } } public class MortgageAccount : Account { public override void Deposit ( double amount ) { _currentBalance -= amount ; // < -- -- -notice the minus } } public class Bank { public void ReceiveMoney ( Account account , double amount ) { double oldBalance = account.CurrentBalance ; account.Deposit ( amount ) ; //oopssss ? ? ? ? ? } } | S.O.L.I.D Essentials missing points ? |
C_sharp : I have an enumeration with flags . I want to declare a variable with n different flags . n > 1 in this case.Okay - one variant is to cast each flag into an byte and cast the result to my enum . But this is kinda messy - imho . Is there an more readable way to combine flags ? <code> public enum BiomeType { Warm = 1 , Hot = 2 , Cold = 4 , Intermediate = 8 , Dry = 16 , Moist = 32 , Wet = 64 , } BiomeType bType = ( BiomeType ) ( ( byte ) BiomeType.Hot + ( byte ) BiomeType.Dry ) | How to combine enumerations with flags ? |
C_sharp : EDIT : I 've done some research about this , but have not been able to find a solution ! I 'm reading a configuration from an XML file.The layout of the configuration is set for certain version.This version is in the first line of the XML , which is easy to extract.What I would like to know is , what is the best way to actually parse this file/get another method , based on the version ( so all 4 elements , the Major , Minor , Build and Revision ) .Right now I 've come up with this : But I do not find this elegant ( at all ) and I feel like there is a way better way to do this.Anyone who can help ? <code> switch ( version.Major ) { case 0 : switch ( version.Minor ) { case 0 : switch ( version.Build ) { case 0 : switch ( version.Revision ) { case 0 : return VersionNone ( doc ) ; } break ; } break ; } break ; } throw new NotImplementedException ( ) ; | Parse file differently upon different version |
C_sharp : I 'm a Java programmer . I have little knowledge on C # . But from the blogs I have read , Java supports only pass-by-value-of-reference whereas in C # the default is pass-by-value-of-reference but the programmer can use pass by reference if needed . I have penned down my understanding of how a swap function works . I guess it is crucial to get this concept clear as it is very fundamental to programming concepts.In C # : Step 1 : A string object with value one is created on heap and the address of its location is returned stored in variable ONE . Runtime Environment allocates a chunk of memory on the heap and returns a pointer to the start of this memory block . This variable ONE is stored on the stack which is a reference pointer to the locate the actual object in memoryStep 2 : Method changeString is called . A copy of the pointer ( or the memory address location ) is assigned to the variable word . This variable is local to the method which means when the method call ends , it is removed from stack frame and is out of scope to be garbage collected.Within the method call , the variable word is reassigned to point to a new location where TWO object sits in memory . method returnsStep 3 : Printing on the console should print ONE , since what was changed in the previous step was only a local variableStep 4 : Variable one is reassigned to point to the memory location where object ONE resides.Step 5 : method changeString is called . This time reference to the ONE is passed . what this means is the local method variable word is an alias to the variable one in the main scope . So , no copy of reference is done . Hence it is equivalent in thinking that the same variable one is passed to the method call . The method reassigns the variable to point to a different memory location which happens to hold TWO . The method returnsStep 6 : Now the variable one on the outer scope i.e. , in the main method is changed by method call and so it prints TWO.In Java , step 5 is not possible . That is you can not pass by reference.Please correct if the programming flow I described above is correct ? Articles I have read , here and here . <code> public static void Main ( ) { String ONE = `` one '' ; //1 ChangeString ( ONE ) ; //2 Console.WriteLine ( ONE ) ; //3 String ONE = `` ONE '' ; //4 ChangeString ( ref ONE ) ; //5 Console.WriteLine ( ONE ) ; //6 } private static void ChangeString ( String word ) { word = `` TWO '' ; } private static void SeedCounter ( ref String word ) { word = `` TWO '' ; } | how does a swap method work in C # at a memory level ? |
C_sharp : I 've written a little parsing program to compare the older System.IO.Stream and the newer System.IO.Pipelines in .NET Core . I 'm expecting the pipelines code to be of equivalent speed or faster . However , it 's about 40 % slower.The program is simple : it searches for a keyword in a 100Mb text file , and returns the line number of the keyword . Here is the Stream version : I would expect the above stream code to be slower than the below pipelines code , because the stream code is encoding the bytes to a string in the StreamReader . The pipelines code avoids this by operating on bytes : Here are the associated helper methods : I 'm using SequenceReader < byte > above because my understanding is that it 's more intelligent/faster than ReadOnlySequence < byte > ; it has a fast path for when it can operate on a single Span < byte > .Here are the benchmark results ( .NET Core 3.1 ) . Full code and BenchmarkDotNet results are available in this repo.GetLineNumberWithStreamAsync - 435.6 ms while allocating 366.19 MBGetLineNumberUsingPipeAsync - 619.8 ms while allocating 9.28 MBAm I doing something wrong in the pipelines code ? Update : Evk has answered the question . After applying his fix , here are the new benchmark numbers : GetLineNumberWithStreamAsync - 452.2 ms while allocating 366.19 MBGetLineNumberWithPipeAsync - 203.8 ms while allocated 9.28 MB <code> public static async Task < int > GetLineNumberUsingStreamAsync ( string file , string searchWord ) { using var fileStream = File.OpenRead ( file ) ; using var lines = new StreamReader ( fileStream , bufferSize : 4096 ) ; int lineNumber = 1 ; // ReadLineAsync returns null on stream end , exiting the loop while ( await lines.ReadLineAsync ( ) is string line ) { if ( line.Contains ( searchWord ) ) return lineNumber ; lineNumber++ ; } return -1 ; } public static async Task < int > GetLineNumberUsingPipeAsync ( string file , string searchWord ) { var searchBytes = Encoding.UTF8.GetBytes ( searchWord ) ; using var fileStream = File.OpenRead ( file ) ; var pipe = PipeReader.Create ( fileStream , new StreamPipeReaderOptions ( bufferSize : 4096 ) ) ; var lineNumber = 1 ; while ( true ) { var readResult = await pipe.ReadAsync ( ) .ConfigureAwait ( false ) ; var buffer = readResult.Buffer ; if ( TryFindBytesInBuffer ( ref buffer , searchBytes , ref lineNumber ) ) { return lineNumber ; } pipe.AdvanceTo ( buffer.End ) ; if ( readResult.IsCompleted ) break ; } await pipe.CompleteAsync ( ) ; return -1 ; } /// < summary > /// Look for ` searchBytes ` in ` buffer ` , incrementing the ` lineNumber ` every/// time we find a new line./// < /summary > /// < returns > true if we found the searchBytes , false otherwise < /returns > static bool TryFindBytesInBuffer ( ref ReadOnlySequence < byte > buffer , in ReadOnlySpan < byte > searchBytes , ref int lineNumber ) { var bufferReader = new SequenceReader < byte > ( buffer ) ; while ( TryReadLine ( ref bufferReader , out var line ) ) { if ( ContainsBytes ( ref line , searchBytes ) ) return true ; lineNumber++ ; } return false ; } static bool TryReadLine ( ref SequenceReader < byte > bufferReader , out ReadOnlySequence < byte > line ) { var foundNewLine = bufferReader.TryReadTo ( out line , ( byte ) '\n ' , advancePastDelimiter : true ) ; if ( ! foundNewLine ) { line = default ; return false ; } return true ; } static bool ContainsBytes ( ref ReadOnlySequence < byte > line , in ReadOnlySpan < byte > searchBytes ) { return new SequenceReader < byte > ( line ) .TryReadTo ( out var _ , searchBytes ) ; } | Why is this System.IO.Pipelines code much slower than Stream-based code ? |
C_sharp : I have a user controller created using the hartl tutorial that signs up new users via form with email and password inputs . This is working properly . I am attempting to send an HttpWebRequest from the Unity editor player to my server in order to sign up a new user from a password string created within Unity . I have provided the error response and the code relevant to the attempt below . WebException : The remote server returned an error : ( 422 ) Unprocessable Entity . System.Net.HttpWebRequest.EndGetResponse ( System.IAsyncResult asyncResult ) ( at > < 4b9f316768174388be8ae5baf2e6cc02 > :0 ) System.Net.HttpWebRequest.GetResponse ( ) ( at < 4b9f316768174388be8ae5baf2e6cc02 > :0 ) UnityStandardAssets.Characters.RigidbodyFirstPersonController.RigidbodyFirstPer > sonController.resetScene3 ( ) ( at > Assets/Scripts/RigidbodyFirstPersonController.cs:463 ) HttpWebRequest Code from RigidbodyFirstPer > sonController.resetScene3 ( ) : Ruby on Rails Users ControllerRoutes.rbUpdate : New code from attempt utilizing Stream . <code> public static string _url = `` https : //immense-castle-53592.herokuapp.com/signup '' ; HttpWebRequest request = ( HttpWebRequest ) HttpWebRequest.Create ( _url ) ; request.Method = `` POST '' ; request.Headers [ `` action '' ] = `` /users '' ; request.Headers [ `` class '' ] = `` new_user '' ; request.Headers [ `` id '' ] = `` new_user '' ; request.Headers [ `` utf8 '' ] = `` & # x2713 ; '' ; request.Headers [ `` authenticity_token '' ] = `` NNb6+J/j46LcrgYUC60wQ2titMuJQ5lLqyAbnbAUkdo= '' ; request.Headers [ `` user_email '' ] = `` jakebrantley44 @ gmail.com '' ; request.Headers [ `` user_password '' ] = passwordUnity ; using ( HttpWebResponse response = ( HttpWebResponse ) request.GetResponse ( ) ) { Debug.Log ( `` Publish Response : `` + ( int ) response.StatusCode + `` , `` + response.StatusDescription ) ; if ( ( int ) response.StatusCode == 200 ) { //SetEnvironmentVersion ( version ) ; } } class UsersController < ApplicationController def show @ user = User.find ( params [ : id ] ) end def new @ user = User.new end def create @ user = User.new ( user_params ) puts params [ : password ] if @ user.save log_in @ user flash [ : success ] = `` Welcome to your vault ! '' redirect_to @ user else render 'new ' end end def edit @ user = User.find ( params [ : id ] ) end private def user_params params.require ( : user ) .permit ( : email , : password ) endend Rails.application.routes.draw do get 'sessions/new ' root 'static_pages # home ' get '/help ' , to : 'static_pages # help ' get '/demo ' , to : 'static_pages # demo ' get '/about ' , to : 'static_pages # about ' get '/contact ' , to : 'static_pages # contact ' get '/signup ' , to : 'users # new ' get '/login ' , to : 'sessions # new ' post '/login ' , to : 'sessions # create ' post '/signup ' , to : 'users # create ' post '/ ' , to : 'users # create ' get '/show ' , to : 'users # create ' delete '/logout ' , to : 'sessions # destroy ' resources : usersend HttpWebRequest request = ( HttpWebRequest ) HttpWebRequest.Create ( _url ) ; // Set the ContentType property of the WebRequest . request.ContentType = `` application/x-www-form-urlencoded '' ; request.Method = `` POST '' ; // Add dictionary strings headers [ `` action '' ] = `` /users '' ; headers [ `` class '' ] = `` new_user '' ; headers [ `` id '' ] = `` new_user '' ; headers [ `` utf8 '' ] = `` & # x2713 ; '' ; headers [ `` authenticity_token '' ] = `` NNb6+J/j46LcrgYUC60wQ2titMuJQ5lLqyAbnbAUkdo= '' ; headers [ `` user_email '' ] = `` jakebrantley44 @ gmail.com '' ; headers [ `` user_password '' ] = passwordUnity ; byte [ ] headersByte = UnityWebRequest.SerializeSimpleForm ( headers ) ; // Set the ContentLength property of the WebRequest . request.ContentLength = headersByte.Length ; Debug.Log ( headersByte ) ; // Get the request stream . Stream dataStream = request.GetRequestStream ( ) ; // Write the data to the request stream . dataStream.Write ( headersByte , 0 , headersByte.Length ) ; // Close the Stream object . dataStream.Close ( ) ; // Get the response . using ( HttpWebResponse response = ( HttpWebResponse ) request.GetResponse ( ) ) { // Display the status . Console.WriteLine ( ( ( HttpWebResponse ) response ) .StatusDescription ) ; // Get the stream containing content returned by the server . dataStream = response.GetResponseStream ( ) ; // Open the stream using a StreamReader for easy access . StreamReader reader = new StreamReader ( dataStream ) ; //Read the content string responseFromServer = reader.ReadToEnd ( ) ; // Display the content . Console.WriteLine ( responseFromServer ) ; Debug.Log ( responseFromServer ) ; reader.Close ( ) ; dataStream.Close ( ) ; response.Close ( ) ; Debug.Log ( `` Publish Response : `` + ( int ) response.StatusCode + `` , `` + response.StatusDescription ) ; if ( ( int ) response.StatusCode == 200 ) { } } | How to use Ruby on Rails users controller via Unity ( C # ) to sign up a new user ? |
C_sharp : I need a function which can calculate the mathematical combination of ( n , k ) for a card game . My current attempt is to use a function based on usual Factorial method : It 's working very well but the matter is when I use some range of number ( n value max is 52 and k value max is 4 ) , it keeps me returning a wrong value . E.g : I know that it 's because I overflow the long when I make Factorial ( 52 ) but the range result I need is not as big as it seems.Is there any way to get over this issue ? <code> static long Factorial ( long n ) { return n < 2 ? 1 : n * Factorial ( n - 1 ) ; } static long Combinatory ( long n , long k ) { return Factorial ( n ) / ( Factorial ( k ) * Factorial ( n - k ) ) ; } long comb = Combinatory ( 52 , 2 ) ; // return 1 which should be actually 1326 | Combinatory issue due to Factorial overflow |
C_sharp : i want to create a windows form which takes image from file and displays in the pictureBox in c # i am having problem when i type image.FromFile after `` = '' the FromFile gets red underline as if it does not consists in the library . <code> 1 using System ; 2 using System.Collections.Generic ; 3 using System.ComponentModel ; 4 using System.Data ; 5 using System.Drawing ; 6 using System.Linq ; 7 using System.Text ; 8 using System.Windows.Forms ; 9 using System.IO ; 1011 namespace demo212 { 13 public partial class Image : Form14 { 15 public Image ( ) 16 { 17 InitializeComponent ( ) ; 18 } 19 20 21 22 private void button1_Click ( object sender , EventArgs e ) 23 { 24 OpenFileDialog ofd = new OpenFileDialog ( ) ; 25 ofd.Filter = `` image files|*.png ; *.jpg ; *.gif '' ; 26 DialogResult dr = ofd.ShowDialog ( ) ; 27 28 if ( dr == DialogResult.Cancel ) 29 return ; 30 31 pictureBox1.Image = Image.FromFile ( ofd.FileName ) ; 32 textBox1.Text = ofd.FileName ; 33 } 34 35 } 36 } | .FromFile underlined red and showing error |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.