text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
C_sharp : This is best illustrated with an example.Say I want to load several records from a database at the beginning of a web request . I want to pull in all the necessary data asynchronously . I might have something like this : Now let ’ s say I want to load this data in parallel . Suddenly this nice clear/clean async code becomes a bit messy.Is there a nicer , more succinct way to achieve this ? <code> var user = await Database.GetUser ( userId ) ; var group = await Database.GetGroup ( groupId ) ; var members = await Database.GetGroupMembers ( groupId ) ; var userTask = Database.GetUser ( userId ) ; var groupTask = Database.GetGroup ( groupId ) ; var membersTask = Database.GetGroupMembers ( groupId ) ; await Task.WhenAll ( userTask , groupTask , membersTask ) ; var user = userTask.Result ; var group = groupTask.Result ; var members = membersTask.Result ; | What is the most elegant way to load multiple variables asynchronously in parallel in c # |
C_sharp : I was trying around a bit with Try Roslyn when I entered this piece of code : And it gave me back this code : What I do n't get is why it would do the assignment of the backing field twice inside of the constructor : Is this an error of the website or does the Roslyn compiler actually do this ( would be really dumb imo ) ? What I mean is that if I doAnd have that code created : But should n't it optimize that out ? <code> using System ; using System.Linq ; using System.Collections.Generic ; using Microsoft.CSharp ; public class C { public C ( ) { x = 4 ; } public int x { get ; } = 5 ; } using System ; using System.Diagnostics ; using System.Reflection ; using System.Runtime.CompilerServices ; using System.Security ; using System.Security.Permissions ; [ assembly : AssemblyVersion ( `` 0.0.0.0 '' ) ] [ assembly : Debuggable ( DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue ) ] [ assembly : CompilationRelaxations ( 8 ) ] [ assembly : RuntimeCompatibility ( WrapNonExceptionThrows = true ) ] [ assembly : SecurityPermission ( SecurityAction.RequestMinimum , SkipVerification = true ) ] [ module : UnverifiableCode ] public class C { [ DebuggerBrowsable ( DebuggerBrowsableState.Never ) , CompilerGenerated ] private readonly int < x > k__BackingField ; public int x { [ CompilerGenerated ] get { return this. < x > k__BackingField ; } } public C ( ) { this. < x > k__BackingField = 5 ; base ( ) ; // This is not valid C # , but it represents the IL correctly . this. < x > k__BackingField = 4 ; } } this. < x > k__BackingField = 5 ; base ( ) ; // This is not valid C # , but it represents the IL correctly . this. < x > k__BackingField = 4 ; . public C ( int x ) { this.x = x ; } public int x { get ; } = 5 ; public C ( int x ) { this. < x > k__BackingField = 5 ; base ( ) ; // This is not valid C # , but it represents the IL correctly . this. < x > k__BackingField = x ; } | Why does the IL set this value twice ? |
C_sharp : I am working on a web application . I have two text boxes , one is txtEmployeeID , and one is txtEmployeeName . What I am trying to do here is when the user enter EmployeeID in the txtEmployeeID , the name of the employee will show up in the txtEmployeeName . I got this part working so far . However , if the employeeID start with bunch of 0 , let say 00000345 , the user need to enter all 00000345 in the employeeID in order to show that employeeName . I am wondering if there a way for user to just enter 345 and then that 00000345 's employeeName will display in the txtEmployeeName ? Help will be appreaciated . For ExampleIn my text box.It will display My DB Query <code> EmployeeID EmployeeName00000345 James Murray Employee ID : 345 Employee Name : James Murray @ Employee_ID varchar ( 8 ) = NULLSELECT s.Employee_ID , p.FIRST_NAME , p.LAST_NAME FROM [ dbo ] . [ Employee ] e INNER JOIN [ dbo ] . [ Person ] p ON e.PERSON_ID = p.PERSON_ID WHERE p.Employee_ID = @ Employee_ID | How to ignore integer start with 0 |
C_sharp : Author post-edit : Chosen solution ( Original question remains below this box ) SUMMARY : You SHOULD NOT name a class the same as its namespace . Therefore should a product name be used for the namespace or the main class ? Chosen solution : I decided to apply the product name to the namespace and add a suffix to the main class name ( e.g. , __Module ) .Rationale : Visual Studio defaults to using the project name for the namespace , assembly name , as well as the actual deliverable .exe or .dll -- These are the most visible items so I think it makes sense to name the namespace after my product name , then do as Jon Skeet recommends in his answer and name the main class as ___Main or __Program or __Module . No one right answer I suppose.Original question : I COMPLETELY GET IT -- DO N'T NAME A CLASS THE SAME AS ITS NAMESPACE ! This is almost a duplicate question ... except I 've spent hours reading articles ( see below ) and ca n't find or think of a solution that seems right.Say I have a product called the ACME Foobarinator . It has a couple related types ( e.g. , settings , enums ) but not enough to call for any sort of namespace hierarchy.It makes sense to create a single product namespace and throw everything into it : BAD ! ! ! Both namespace and class name are the same ! ! But , I 'd also like the main class to be Foobarinator because it 's the trademark product name and I 'd like consumers to use it by trademark name : var fb = new Foobarinator ( ) ; Option 1 : Eliminate the product namespace , promoting all types to the parent namespace . But this pollutes the parent namespace with types that are specific to the product ( and not necessarily all public types ) . As the product evolves , the pollution stands to increase ! Option 2 : Add needless suffix to the main class . But this obfuscates the product trademark name ! Option 3 : Use child classes/types for the related types . However , encapsulating everything in one class eventually violates separation of concerns as the product evolves : YOUR THOUGHTS ? Where do I compromise ? Related questions and articles : How to avoid having the same name for a class and it 's namespace , such as Technology.Technology ? Should a class have the same name as the namespace ? Namespace with same name as a class nameShould a class have the same name as the namespace ? http : //blogs.msdn.com/ericlippert/archive/2010/03/09/do-not-name-a-class-the-same-as-its-namespace-part-one.aspx <code> namespace Acme.Web.Foobarinator { public class Foobarinator { } // BAD ! Same name as namespace ! public class FoobarinatorInfo { } public enum Mode { Disabled , Enabled } } namespace Acme.Web { public class Foobarinator { } public class FoobarinatorInfo { } public enum FoobarinatorMode { Disabled , Enabled } // More pollution in future ... } namespace Acme.Web.Foobarinator { public class FoobarinatorMain { } // Not the name of the product ! public class FoobarinatorInfo { } public enum Mode { Disabled , Enabled } } namespace Acme.Web { public class Foobarinator { public class FoobarinatorInfo { } public enum Mode { Disabled , Enabled } } } | Product trademark name begs for class/namespace with same name |
C_sharp : Why is it giving me a null in s variable ? I know that casting it using int ? s = ( int ? ) i ; will work fine but why ca n't I use an as operator ? <code> long ? i = 10000 ; int ? s = i as int ? ; | Why ` as ` is giving null for nullable value types ? |
C_sharp : This question is a slightly modified version of Convert List < T > to Dictionary with strategyI have List < DTO > where DTO class looks like this , I create objects and add it to List.Now my requirement is I need to create a List from the dtoCollection where Name field should be unique across the entire List.For example , if you convert the above dtoCollection to the required List from , the resultant list should be like : List < DTO > count should be 1 ; The object inside the list should be a single DTO with Name as `` test '' and Count as 5Where Count is obtained from summing up the Count fields in all DTO 's whose Name fields are same <code> private class DTO { public string Name { get ; set ; } public int Count { get ; set ; } } var dto1 = new DTO { Name = `` test '' , Count = 2 } ; var dto2 = new DTO { Name = `` test '' , Count = 3 } ; var dtoCollection = new List < DTO > { dto1 , dto2 } ; | Group a List based on uniqueness |
C_sharp : Hi I have a listbox Whenever a user selects an item a request is sent to the web Now I want to cancel the previous operation when the user selected the item and then start the new operation.I used the following codes to do this , I wanted to know if these codes work well . Or should I try another way ? and i run func this way <code> private CancellationTokenSource ts = new CancellationTokenSource ( ) ; private async void Subf2mCore ( CancellationToken ct ) { HtmlDocument doc = await web.LoadFromWebAsync ( url ) ; ... foreach ( var node in doc ) { if ( ! ct.IsCancellationRequested ) { ... . } } } ts ? .Cancel ( ) ; ts = new CancellationTokenSource ( ) ; Subf2mCore ( ts.Token ) ; | Cancel Task in async void |
C_sharp : Using Visual Studio 2013 , I 'm trying to reproduce the gotcha mentioned in Eric Lippert 's blog post `` Closing over the loop variable considered harmful '' .In the project properties , I selected `` C # 3.0 '' as the language version ( Build > Advanced… ) . Further , I selected `` .NET Framework 3.5 '' as the target framework , as though I think this should n't be necessary as this solely concerns the language.Running his code : Expected output : Actual output : As answered by Eric Lippert himself in `` Is there a reason for C # 's reuse of the variable in a foreach ? `` : The for loop will not be changed , and the change will not be `` back ported '' to previous versions of C # . You should therefore continue to be careful when using this idiom.What am I doing wrong ? <code> using System ; using System.Collections.Generic ; namespace Project1 { class Class1 { public static void Main ( string [ ] args ) { var values = new List < int > ( ) { 100 , 110 , 120 } ; var funcs = new List < Func < int > > ( ) ; foreach ( var v in values ) { funcs.Add ( ( ) = > v ) ; } foreach ( var f in funcs ) Console.WriteLine ( f ( ) ) ; } } } 120120120 100110120 | Reproducing the `` close over the variable of a foreach '' gotcha |
C_sharp : Imagine that you have a list called List < Foo > .Foo is an abstract class , so this can be FooA , FooB , FooC or FooD . And I 'd like to have an extension for List < T > where you can order this elements by type but sequently.For example , if I have 9 elements in it.Order by type sequently will be.I 'm trying that the function can be ordered at the order you specify , at this case , IE , it was : I was trying to create this extension , but I do n't get anything . Can you help a little bit ? I 'm guessing that I can accomplish it with LINQ . <code> FooA , FooA , FooB , FooD , FooC , FooC , FooA , FooB , FooA FooA , FooB , FooC , FooD , FooA , FooB , FooC , FooA , FooA new [ ] { typeof ( FooA ) , typeof ( FooB ) , typeof ( FooC ) , typeof ( FooD ) } | How to order a list by type ? |
C_sharp : This has me pretty stumped . Maybe I 'm too tired right now.inputArea is a nullable Rectangle , which in my particular case is null.The first two statements yields a cropArea initialized to 0 . The second , however , yields the correct cropArea based on the image width and height . Have I misunderstood anything with the conditional operator ? It seems it does not return rectangle when inputArea = null ? Is there any quirks when working with value types ? EDIT : Alright , I should have tried this first : restarted VS . It seems the debugger lied to me , or something . Anyway , works now . Thanks . <code> Rectangle rectangle = new Rectangle ( 0 , 0 , image.Width , image.Height ) ; Rectangle cropArea = inputArea == null ? rectangle : inputArea.Value ; if ( inputArea == null ) cropArea = rectangle ; | Weird behaviour with conditional operator in .Net |
C_sharp : I have the following code : I would like my listSrc result to contain two Info items whose Name and Num properties are : However , the code I show above results in four items : <code> public class Info { public string Name ; public string Num ; } string s1 = `` a , b '' ; string s2 = `` 1,2 '' ; IEnumerable < Info > InfoSrc = from name in s1.Split ( ' , ' ) from num in s2.Split ( ' , ' ) select new Info ( ) { Name = name , Num = num } ; List < Info > listSrc = InfoSrc.ToList ( ) ; a , 1b , 2 a , 1a , 2b , 1b , 2 | Split multiple strings into a list of objects in C # |
C_sharp : Is there a way to reliably get a unique e-mail address from one put in from a user ? The problem is services such as GMail allow you to put a period in the address and it 's stripped out whereas with other services this is not the case.GMail : All of these are the sameOther service : These are unique.Other than having special logic specifically for GMail is there a better way ? <code> chad.moran @ gmail.comc..hadmoran @ gmail.comc.h.a.d.m.o.r.a.n @ gmail.com chad.moran @ -- -.comc..hadmoran @ -- -.com | How to de-duplicate e-mail addresses |
C_sharp : How can this code : run 3x faster than this code : The first code snippet does exactly the same fast divide operation ( thats the multiply then shift right ) but also a subtraction and multiplication but but the JIT compiler appears to be producing slower code.I have the disassembly code for each available.The slower code pushes the rbx register and subtracts 10h from rsp at the start and then adds it back and pops rbx at the end whereas the faster codes doesn't.The slower code also uses the r11 register for most things where the faster code uses rdx.Any ideas ? <code> var check = 0 ; for ( var numerator = 0 ; numerator < = maxNumerator ; numerator++ ) { check += numerator > = 0 ? numerator - ( int ) ( ( numerator * qdi.Multiplier ) > > qdi.Shift ) * qdi.Number : numerator - ( int ) - ( ( -numerator * qdi.Multiplier ) > > qdi.Shift ) * qdi.Number ; } return check ; var check = 0 ; for ( var numerator = 0 ; numerator < = maxNumerator ; numerator++ ) { check += numerator > = 0 ? ( int ) ( ( numerator * qdi.Multiplier ) > > qdi.Shift ) : ( int ) - ( ( -numerator * qdi.Multiplier ) > > qdi.Shift ) ; } return check ; | How can the first of these two code snippets run 3x faster than the second when its doing more work ? |
C_sharp : Using interpolated strings to send sql server queries , why with a datacontext on LINQ to SQL you need to add single quotes ? db.ExecuteCommand ( $ '' delete table where date = ' { date : yyyy-MM-dd } ' '' ) ; while with EF Core you need to remove them ? and why in EF Core , if you 're using String.Format instead of interpolation , you need to put back the single quotes : <code> db.Database.ExecuteSqlCommand ( $ '' delete table where date = { date : yyyy-MM-dd } '' ) ; String.Format ( `` delete table where date= ' { 0 } ' '' , date.ToString ( `` yyyy-MM-dd '' ) ) ; | Ef Core vs Linq on interpolated string |
C_sharp : So insteed of writing : I thought of writing : It kind of feels wrong , especially this part `` obj.Collection = obj.Collection ... '' What do you guys think ? Regards , <code> if ( obj.Collection == null ) obj.Collection = new Collection ( ) ; obj.Collection.Add ( something ) ; obj.Collection = obj.Collection ? ? new Collection ; obj.Collection.Add ( something ) ; | What 's wrong with the ? ? operator used like this : |
C_sharp : This code seems to not call the Mixed constructor and prints y = 0However , simply modifying the Main function to look like this results in the constructor being called.This prints : Why does simply adding this reference to a non-static field result in the constructor being called correctly ? Should n't creating the object always result in a constructor being called , regardless of how that object is used later in the program ? Oddly enough , making the Mixed object non-static like this also results in the constructor being called : However , this does n't seem to make sense to me either . Declaring the Mixed object as static should only imply that there is only one copy of the object in memory , regardless of how many times Program is instantiated . Is this some sort of compiler optimization that for static fields the compiler waits for a reference to a non-static field of that type before actually instantiating it ? <code> public class Mixed { public int x ; public static int y ; public Mixed ( ) { x = 1 ; y = 1 ; } } public class Program { static Mixed mixed = new Mixed ( ) ; static void Main ( string [ ] args ) { Console.WriteLine ( `` y = `` + Mixed.y ) ; Console.ReadLine ( ) ; } } static void Main ( string [ ] args ) { Console.WriteLine ( `` x = `` + mixed.x ) ; Console.WriteLine ( `` y = `` + Mixed.y ) ; Console.ReadLine ( ) ; } x = 1y = 1 public class Program { static void Main ( string [ ] args ) { Mixed mixed = new Mixed ( ) ; Console.WriteLine ( `` y = `` + Mixed.y ) ; Console.ReadLine ( ) ; } } | Why is n't this C # instance constructor being called , unless there is a reference to a non-static member ? |
C_sharp : I am iterating through a collection in a foreach loop and was wondering.When this gets executed by the .NET runtimeDoes the myDict.Values get invoked for every loop or is it called only once ? Thanks , <code> foreach ( object obj in myDict.Values ) { // ... do something } | Collections use in foreach loop |
C_sharp : This is best illustrated with an example : I want to tell , for an arbitrary object , if I can cast it to Cat . Sadly I can not seem to use the is/as operator.I 'm hoping to avoid a try/catch ( InvalidCastException ) as I may be doing this a lot and this would be quite expensive.Is there a way to do this cheaply and easily ? edit : Thanks for the answers guys - votes for all , wish I could give you all the Tick , but it 's going to Marc for the most general solution ( bonus vote for punching it out on an ipod ) . However Jordao 's solution managed to hone in on what I need and not what I asked for so it is probably what I 'm going with . <code> class Cat { } class Dog { public static implicit operator Cat ( Dog d ) { return new Cat ( ) ; } } void Main ( ) { var d = new Dog ( ) ; if ( d is Cat ) throw new Exception ( `` d is Cat '' ) ; var c1 = ( Cat ) d ; // yes //var c2 = d as Cat ; // Wo n't compile : Can not convert type 'Dog ' to 'Cat ' via a reference conversion , boxing conversion , unboxing conversion , wrapping conversion , or null type conversion } | Is there a `` cheap and easy '' way to tell if an object implements an explicit/implicit cast operator to a particular type ? |
C_sharp : Here is the codeI can´t get the limit counter to increment for each timeI can get it to count to 1 between each outputline , but that´s itAny idea why ? I want it to be able to count every `` overshoot '' <code> class Actuator { private int limit_count = 0 ; public int Inc_Limit_counter ( int temp , int co2_conc , int rel_humid ) { if ( temp > 70 || co2_conc > 450 || rel_humid > 77 ) limit_count++ ; //Console.WriteLine ( `` test { 0 } '' , limit_count ) ; return limit_count ; } public int Get_limit_count ( ) { return limit_count ; } } class Program { static int read_random_values ( ) { Random r = new Random ( ) ; int temp , co2_conc , rel_humid , i ; Console.WriteLine ( `` Temperature in celcius : '' ) ; for ( i = 0 ; i < = 100 ; i++ ) { temp = r.Next ( -50,50 ) ; co2_conc = r.Next ( 300,600 ) ; rel_humid = r.Next ( 0,100 ) ; Console.WriteLine ( `` The temperature is : { 0 } , Co2 concentration is : { 1 } and Relative Humidity is : { 2 } '' , temp , co2_conc , rel_humid ) ; Actuator Counter1 = new Actuator ( ) ; Counter1.Inc_Limit_counter ( temp , co2_conc , rel_humid ) ; } return 0 ; } static void Main ( ) { read_random_values ( ) ; Actuator object1 = new Actuator ( ) ; object1.Get_limit_count ( ) ; } } | Displaying values from a private int in c # |
C_sharp : UPDATE : The following code only makes sense in C # 4.0 ( Visual Studio 2010 ) It seems like I am having some misunderstanding of covariance/contravariance thing . Can anybody tell me why the following code does n't compile ? while this one compiles : ( ! ! ! ) <code> public class TestOne < TBase > { public IEnumerable < TBase > Method < TDerived > ( IEnumerable < TDerived > values ) where TDerived : TBase { return values ; } } public interface IBase { } public interface IDerived : IBase { } public class TestTwo { public IEnumerable < IBase > Method ( IEnumerable < IDerived > values ) { return values ; } } | Covariance/contravariance : how to make the following code compile |
C_sharp : In specific , if I say : How does the compiler go about generating a concrete enumerable class out of this ? <code> public static IEnumerable < String > Data ( ) { String connectionString = `` ... '' ; using ( SqlConnection connection = new SqlConnection ( connectionString ) ) { connection.Open ( ) ; IDataReader reader = new SqlCommand ( `` '' , connection ) .ExecuteReader ( ) ; while ( reader.Read ( ) ) yield return String.Format ( `` Have a beer { 0 } { 1 } ! `` , reader [ `` First_Name '' ] , reader [ `` Last_Name '' ] ) ; connection.Close ( ) ; } } | How does the compiler use 'yield return ' to build a class |
C_sharp : I am making a horse programme . I have the horse face and wish to apply a bit mask . Only the horses eyes should be visible when it is wearing the bit mask . First I must convert the horses face to digital . For this I have a set of bits which include 0 , 0 , 0 , and 1 for the face of the horse.I am using C # and have broken the problem into parts : Convert the horse 's head to digitalBuild a bit mask for it to wearPut the bit mask on the horse Convert the digital masked horse backinto graphicsAt step 4 I expect only to see the horses eyes but I only see `` 0 '' which IS NOT EVEN A HORSE FACE.Here is all of my code , please do n't question my ASCII art it is not relevant to the question , besides it is a prototype the real program will have superior graphics . I suspect something is wrong with the conversion , I have tried all kinds of things like converting to a byte array and formatting the string with spaces but with no luck . I am wondering if this problem might be NP-hard . <code> //the head of the horsestring head = `` # # '' + `` # # # # # # # # '' + `` # O O # '' + `` # # '' + `` # # '' + `` # = = # '' + `` # ==== # `` + `` # # # # `` ; //digitize the horse into bits of binarystring binaryHead = head.Replace ( ' # ' , ' 0 ' ) .Replace ( '= ' , ' 0 ' ) .Replace ( ' ' , ' 0 ' ) .Replace ( ' O ' , ' 1 ' ) ; long face = Convert.ToInt64 ( binaryHead , 2 ) ; //make a bit mask with holes for the eyesstring mask = `` 11111111 '' + `` 11111111 '' + `` 10111101 '' + `` 11111111 '' + `` 11111111 '' + `` 11111111 '' + `` 11111111 '' + `` 11111111 '' ; //apply the bit mask using C # long maskBits = Convert.ToInt64 ( mask , 2 ) ; string eyesOnly = Convert.ToString ( face & maskBits , 2 ) ; //eyesOnly is `` 0 '' ... .WHAT ? ? ? It should be more than that . WHERE IS THE HORSE ? ? //It should look like this : // `` 00000000 '' +// `` 00000000 '' +// `` 01000010 '' +// `` 00000000 '' +// `` 00000000 '' +// `` 00000000 '' +// `` 00000000 '' +// `` 00000000 '' ; | Can not apply bit mask |
C_sharp : I 've written a recursive function which yields IEnumerable < int > So If I write It should yield But it does n't work as expected . ( it displays 0 ) .In normal recursive function ( which return int - without Ienumerable ) it works fine.Question : How can I fix the code so it yields the expected value ? nb . No there 's no reason for using recursive Ienumerables . It 's just came to my mind after playing with recursive yields . <code> IEnumerable < int > Go ( int b ) { if ( b==0 ) yield return 0 ; else foreach ( var element in Go ( b-1 ) ) { yield return element ; } } foreach ( var element in Go ( 3 ) ) { Console.WriteLine ( element ) ; } 0123 | Recursive IEnumerable does n't work as expected ? |
C_sharp : I am trying to upgrade my project from Microsoft.WindowsAzure.Storage v9 ( deprecated ) to latest sdk Azure.Storage.Blobs v12.My issue ( post-upgrade ) is accessing the ContentHash property.Pre-upgrade steps : upload file to blobget MD5 hash of uploaded file provided by CloudBlob.Properties.ContentMD5 from Microsoft.WindowsAzure.Storage.Blobcompare the calculated MD5 hash with the one retrieved from azurePost-upgrade attempts to access the MD5 hash that Azure is calculating on its side:1.BlobClient.GetProperties ( ) calling this method2.BlobClient.UploadAsync ( ) looking at the BlobContentInfo responseboth return ContentHash is null . ( see my later Question to see why ) One huge difference I 've noticed is that with older sdk I could tell to the storage client to use MD5 computing like this : So I was expecting to find something similar to StoreBlobContentMD5 on the latest sdk but I couldn't.Can anyone help me find a solution for this problem ? Edit 1 : I did a test and in azure storage I do not have a MD5 hashUpload code : There is not much difference between old upload code and new one apart from using new classes from new sdk.The main difference remains the one I already stated , I can not find an equivalent setting in new sdk for StoreBlobContentMD5 .I think this is the problem . I need to set the storage client to compute MD5 hash , as I did with old sdk.Edit 2 : For download I can do something like this : By using this definition of DownloadAsync I can force MD5 hash to be calculated and it can be found in download.Value.ContentHash <code> CloudBlobClient cloudBlobClient = _cloudStorageAccount.CreateCloudBlobClient ( ) ; cloudBlobClient.DefaultRequestOptions.StoreBlobContentMD5 = true ; var container = _blobServiceClient.GetBlobContainerClient ( containerName ) ; var blob = container.GetBlobClient ( blobPath ) ; BlobHttpHeaders blobHttpHeaders = null ; if ( ! string.IsNullOrWhiteSpace ( fileContentType ) ) { blobHttpHeaders = new BlobHttpHeaders ( ) { ContentType = fileContentType , } ; } StorageTransferOptions storageTransferOption = new StorageTransferOptions ( ) { MaximumConcurrency = 2 , } ; var blobResponse = await blob.UploadAsync ( stream , blobHttpHeaders , null , null , null , null , storageTransferOption , default ) ; return blob.GetProperties ( ) ; var properties = blob.GetProperties ( ) ; var download = await blob.DownloadAsync ( range : new HttpRange ( 0 , properties.Value.ContentLength ) , rangeGetContentHash : true ) ; | ContentHash is null in Azure.Storage.Blobs v12.x.x |
C_sharp : When trying to compile the following code in LINQPad : I get the following error : The type arguments for method 'System.Linq.Enumerable.Select ( System.Collections.Generic.IEnumerable , System.Func ) ' can not be inferred from the usage . Try specifying the type arguments explicitly.If I use a lambda like d = > GetProviderName ( d ) instead of a method group , it works fine ... I 'm quite surprised , because I was sure the compiler would be able to infer the type from the method group . There is no other GetProviderName method in scope , and the input and output types are clearly defined , so it should be implicitly convertible to a Func < DriveInfo , string > ... should n't it ? <code> void Main ( ) { DriveInfo.GetDrives ( ) .Select ( GetProviderName ) .Dump ( ) ; } static string GetProviderName ( DriveInfo drive ) { // some irrelevant WMI code ... } | Why generic type inference does n't work in that case ? |
C_sharp : In my viewmodel , I have a list of items I fetch from the database and then send to the view . I would like to know if it 's possible to avoid having to refill the options property whenever I hit a Post action and need to return the model ( for validation errors and what not ) ? In webforms , this would n't be necessary.Edit : I was not clear . My problem is with the SelectList options I use for my DropDownLists . Everything gets posted , but if I have to return to the view ( model is invalid ) , I have to reload the options from the database ! I want to know if this can be avoided.My viewmodel : My view : My controller ( do notice the comment on HttpPost ) : Thanks in advance.Edit : FYI , my solution was to use the Session variable . <code> public class TestModel { public TestModel ( ) { Departments = new List < SelectListItem > ( ) ; } public string Name { get ; set ; } public int Department { get ; set ; } public IEnumerable < SelectListItem > Departments { get ; set ; } } @ model MvcApplication1.Models.TestModel @ using ( Html.BeginForm ( ) ) { @ Html.TextBoxFor ( m = > m.Name ) @ Html.DropDownListFor ( m = > m.Department , Model.Departments ) < input type=submit value=Submit / > } public ActionResult Index ( ) { TestModel model = new TestModel { Name = `` Rafael '' , Department = 1 , Departments = new List < SelectListItem > { new SelectListItem { Text = `` Sales '' , Value = `` 1 '' } , new SelectListItem { Text = `` Marketing '' , Value = `` 2 '' , Selected = true } , new SelectListItem { Text = `` Development '' , Value = `` 3 '' } } } ; // Departments gets filled from a database . return View ( model ) ; } [ HttpPost ] public ActionResult Index ( TestModel model ) { if ( ! ModelState.IsValid ) { //Do I have to fill model.Departments again ! ? ! ? ! ? return View ( model ) ; } else { ... } } | Reuse model data in a post action |
C_sharp : I have created a bezier curve by adding the following script to an empty game object in the inspector . This draws to complete curve at once when I run the code . How can I animate it over a given period of time , say 2 or 3 seconds ? <code> public class BCurve : MonoBehaviour { LineRenderer lineRenderer ; public Vector3 point0 , point1 , point2 ; int numPoints = 50 ; Vector3 [ ] positions = new Vector3 [ 50 ] ; // Use this for initializationvoid Start ( ) { lineRenderer = gameObject.AddComponent < LineRenderer > ( ) ; lineRenderer.material = new Material ( Shader.Find ( `` Sprites/Default '' ) ) ; lineRenderer.startColor = lineRenderer.endColor = Color.white ; lineRenderer.startWidth = lineRenderer.endWidth = 0.1f ; lineRenderer.positionCount = numPoints ; DrawQuadraticCurve ( ) ; } void DrawQuadraticCurve ( ) { for ( int i = 1 ; i < numPoints + 1 ; i++ ) { float t = i / ( float ) numPoints ; positions [ i - 1 ] = CalculateLinearBeziearPoint ( t , point0 , point1 , point2 ) ; } lineRenderer.SetPositions ( positions ) ; } Vector3 CalculateLinearBeziearPoint ( float t , Vector3 p0 , Vector3 p1 , Vector3 p2 ) { float u = 1 - t ; float tt = t * t ; float uu = u * u ; Vector3 p = uu * p0 + 2 * u * t * p1 + tt * p2 ; return p ; } } | How to animate a bezier curve over a given duration |
C_sharp : This is my first question on Stack Overflow . Apologies in advance if I do n't do things quite right while I 'm learning how things work here.Here is my code : It produces this XML : I do n't understand why I am not getting < Items testAttribute= '' foo '' > Please can anyone tell me what I need to add to my code so that the Serializer will write this attribute out ? Thanks , <code> public void TestSerialize ( ) { ShoppingBag _shoppingBag = new ShoppingBag ( ) ; Fruits _fruits = new Fruits ( ) ; _fruits.testAttribute = `` foo '' ; Fruit [ ] fruit = new Fruit [ 2 ] ; fruit [ 0 ] = new Fruit ( `` pineapple '' ) ; fruit [ 1 ] = new Fruit ( `` kiwi '' ) ; _fruits.AddRange ( fruit ) ; _shoppingBag.Items = _fruits ; Serialize < ShoppingBag > ( _shoppingBag , @ '' C : \temp\shopping.xml '' ) ; } public static void Serialize < T > ( T objectToSerialize , string filePath ) where T : class { XmlSerializer serializer = new XmlSerializer ( typeof ( T ) ) ; using ( StreamWriter writer = new StreamWriter ( filePath ) ) { serializer.Serialize ( writer , objectToSerialize ) ; } } [ Serializable ] public class ShoppingBag { private Fruits _items ; public Fruits Items { get { return _items ; } set { _items = value ; } } } public class Fruits : List < Fruit > { public string testAttribute { get ; set ; } } [ Serializable ] public class Fruit { public Fruit ( ) { } public Fruit ( string value ) { Name = value ; } [ XmlAttribute ( `` name '' ) ] public string Name { get ; set ; } } < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < ShoppingBag xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xmlns : xsd= '' http : //www.w3.org/2001/XMLSchema '' > < Items > < Fruit name= '' pineapple '' / > < Fruit name= '' kiwi '' / > < /Items > < /ShoppingBag > | C # XML Serializer wo n't store an attribute |
C_sharp : I 'm having a hard time getting the LINQ-syntax.. How can I do this command in a better way ? As you can see , there 's a table user , a table pintouser and a table pin . Pintouser references user and pin . Is it possible to write something short like `` user.pintouser.pin '' ? I think I have the navigation properties all set up but I 'm not sure how to use them properly or if I could make them better by modifying them.Thanks for reading <code> var user = ( from u in context.users where u.email.Equals ( email ) select u ) .Single ( ) ; var pinToUser = ( from ptu in context.pintousers where ptu.user_id.Equals ( user.id ) select ptu ) .Single ( ) ; var pin = ( from p in context.pins where p.idpin.Equals ( pinToUser.pin_idpin ) select p ) .Single ( ) ; return pin ; | Making a LINQ query better |
C_sharp : I have this code after decompileI do n't know what mean operator/symbol < > before some operations . Does somebody know ? <code> SampleClass sampleClass ; SampleClass < > g__initLocal0 ; int y ; sampleClass = null ; Label_0018 : try { < > g__initLocal0 = new SampleClass ( ) ; < > g__initLocal0.X = 5 ; < > g__initLocal0.Y = 10 ; sampleClass = < > g__initLocal0 ; goto Label_003A ; } catch ( Exception ) { Label_0035 : goto Label_003A ; } Label_003A : y = sampleClass.Y ; | What does the symbol < > mean in MSIL ? |
C_sharp : Basically I have a few functions that look like this : Under the assumption I can use the same resource instead of a different one [ instance ] in every function is it ok practice in regard to cleanup and such to do this ? : <code> class MyClass { void foo ( ) { using ( SomeHelper helper = CreateHelper ( ) ) { // Do some stuff with the helper } } void bar ( ) { using ( SomeHelper helper = CreateHelper ( ) ) { // Do some stuff with the helper } } } class MyClass { SomeHelper helper = CreateHelper ( ) ; // ... foo and bar that now just use the class helper ... . ~MyClass ( ) { helper.Dispose ( ) ; } } | Using statement in every function - > convert to class field with proper cleanup ? |
C_sharp : I have a class hierarchy like thisI wanted to create an action Action lamda that had a generic type paramater of type CalendarEventBase that I could assign to the following different methods : I created the following illegal assignment : The compiler complains that it was expecting a method with void ( CalendarEventBase ) as a signature . I was surprised by this as I thought it would accept a more derived type.To get round this , I created the following delegate that allows me to complete my task : My question is , could I have completed the task without having to create an additional delegate ? I thought I could just create an Action instance.Any help or pointers , greatly appreciated . <code> public abstract class CalendarEventBase { } public class TrainingEvent : CalendarEventBase { } public class AuditEvent : CalendarEventBase { } public void EmailCancelation ( TrainingEvent trainingEvent ) public void EmailCancelation ( AuditEvent auditEvent ) Action < CalendarEventBase > emailCancelation = _trainingService.EmailTrainingCancellation ; public delegate void EmailCancelation < in T > ( T calendarEvent ) where T : CalendarEventBase ; | Contravariance in Action lambda - C # |
C_sharp : Normally if I would have had this : I would have gotten a CA1062 : Validate arguments of public methods from code analysis . It would have been fixed by modifying the code as such : But now I want to use another means of doing this validation : since the method validates the argument the code analysis rule is satisfied but you still get a CA1062 warning . Is there a way to suppress the Code Analysis rule for cases like these without manually suppressing them each time or turning off that specific Code Analysis rule ? <code> public string Foo ( string text ) { return text.Substring ( 3 ) ; } public string Foo ( string text ) { if ( text == null ) throw new ArgumentNullException ( `` text '' ) ; else if ( string.IsNullEmptyOrWhiteSpace ( text ) throw new ArgumentException ( `` May not be empty or white space '' , `` text '' ) else if ( text.Length < 3 ) throw new ArgumentException ( `` Must be at least 3 characters long '' , `` text '' ) ; return text.Substring ( 3 ) ; } public string Foo ( string text ) { Validator.WithArgument ( text , `` text '' ) .NotNullEmptyOrWhitespace ( ) .OfMinLength ( 3 ) ; return text.Substring ( 3 ) ; } | How to let Code Analysis pick up that an argument was validated in called method |
C_sharp : Goal : Generic enumerated type to be the same type when returned.Note : This works when the types are entered but I do n't understand why they ca n't be inferred.List < T > then return List < T > IOrderedEnumerable < T > then return IOrderedEnumerable < T > ETCCurrent method ( works only if all types are entered ) Example OnlyMaking it workWhat I 'm missing is why C # ca n't infer the types although the where filter does make the types accurate . I understand why you either supply all or none generic types to methods so please do not point me to those answers.Edit : If I ca n't infer the types ; then how can I make this more elegant ? <code> public static TEnumerable WithEach < TEnumerable , T > ( this TEnumerable items , Action < T > action ) where TEnumerable : IEnumerable < T > { foreach ( var item in items ) action.Invoke ( item ) ; return items ; } var list = new List < int > ( ) ; //TODO : Mock random valueslist.WithEach ( x = > Console.WriteLine ( x ) ) //Here WithEach ideally returns List < int > following orignal type List < int > .OrderBy ( x = > x ) .WithEach ( x = > Console.WriteLine ( x ) ) ; //Here WithEach ideally returns IOrderedEnumerable < int > following OrderBy var list = new List < int > ( ) ; //TODO : Mock random valueslist.WithEach < List < int > , int > ( x = > Console.WriteLine ( x ) ) .OrderBy ( x = > x ) .WithEach < IOrderedEnumerable < int > , int > ( x = > Console.WriteLine ( x ) ) ; | How can I return < TEnumerable , T > : where TEnumerable : IEnumerable < T > |
C_sharp : I 'm trying to downcast a controller instance inside an action filter , and I 'm having issue doing so.I have a DefaultController class : IBaseEntity is : I have an instance of a controller , inheriting the DefaultController : Workflow is inheriting BaseEntity which implements IBaseEntity.Now , inside my action filter , code wise , it 's impossible to know on which controller the request is running on so I 'm trying to downcast it to DefaultControllerI 've tried using defaultControllerGenericType but I ca n't pass it anywhere , or at least I 'm lacking the correct syntax.Is there any way to do this ? <code> public abstract partial class DefaultController < T > : Controller where T : IBaseEntity { } public interface IBaseEntity { int Id { get ; set ; } DateTime CreatedOn { get ; set ; } DateTime ModifiedOn { get ; set ; } int CreatedBy { get ; set ; } int ModifiedBy { get ; set ; } int OwnerId { get ; set ; } } public class WorkflowController : DefaultController < Workflow > { } public class AddHeaders : ActionFilterAttribute { public override void OnActionExecuted ( ActionExecutedContext filterContext ) { var defaultControllerGenericType = controller.GetType ( ) .BaseType.GenericTypeArguments.FirstOrDefault ( ) ; //this retrieve with which type DefaultController was initiated with ... var controller = filterContext.Controller as DefaultController < BaseEntity > ; //this returns null ... var controller2 = filterContext.Controller as DefaultController < IBaseEntity > ; //this does so as well . } } | How to do this tricky down-casting with generic constraints ? |
C_sharp : I 've noticed something very odd when working with addition of nullable floats . Take the following code : result is 6.099999 whereas result2 is 6.1 . I 'm lucky to have stumbled on this at all because if I change the values for a , b , and c the behavior typically appears correct . This may also happen with other arithmetic operators or other nullable value types , but this is case I 've been able to reproduce . What I do n't understand is why the implicit cast to float from float ? did n't work correctly in the first case . I could perhaps understand if it tried to get an int value given that the other side of the conditional is 0 , but that does n't appear to be what 's happening . Given that result only appears incorrect for certain combinations of floating values , I 'm assuming this is some kind of rounding problem with multiple conversions ( possibly due to boxing/unboxing or something ) .Any ideas ? <code> float ? a = 2.1f ; float ? b = 3.8f ; float ? c = 0.2f ; float ? result = ( a == null ? 0 : a ) + ( b == null ? 0 : b ) + ( c == null ? 0 : c ) ; float ? result2 = ( a == null ? 0 : a.Value ) + ( b == null ? 0 : b.Value ) + ( c == null ? 0 : c.Value ) ; | Curious Behavior When Doing Addition on Nullable Floats |
C_sharp : Want to learn how an instance of a class is created in the background . When this statement is evaluated . What will happen in the backgroud ? My following statements are correct or not ( for 32-bit OS machine ) ? A memory space will be created and referenced as myClass ; within above memory space , 4 bytes is used for the value of int i ; within above memory space , 4 bytes is used for the reference of string str ; the actual value of the str is stored in other location ( where ? ) within above memory space , 8 bytes is used for the value of MyStruct mystruct ( because MyStruct is 8 bytes ) ; within above memory space , 4 bytes is used for the reference of the B b object ; memory for b object will be allocated in somewhere else when it is instantiated ; within above memory space , 4 bytes is used for the reference of the ArrayList myList ; actual memory space for ArrayList myList is allocated in other place and referenced in here as myList ; another 4 or 8 bytes from above memory space is used for object metadata ; ... ; <code> public class MyClass { int i = 0 ; string str = `` here '' ; MyStruct mystruct ; B b ; ArrayList myList = new ArrayList ( 10 ) ; public MyClass ( ) { } ... . } public struct MyStruct { public int i ; public float f ; } public class B { ... } MyClass myClass = new MyClass ( ) ; | How does C # create an instance of a class ? |
C_sharp : Suppose I have the following array ( my sequences are all sorted in ascending order , and contain positive integers ) I want to write a linq query to select the continuous numbers in a series treated as a group . So , in above example I would get { [ 1 , 2 , 3 ] , [ 7 , 8 , 9 ] , [ 15 , 16 , 17 ] } .I could write a foreach ( ) sequence , run through each element and see where the sequence is taking a hop and yield a group there . But is there any LINQ-only way of doing it ? I might be able to move my foreach ( ) code into a new extension method so my code still looks LINQy , but I am wondering if there is anything available in System.Linq already for that.EDIT : I had created my own extension ( as follows ) , but Me.Name came up with something very smart in his Answer . <code> var mySequence = new [ ] { 1 , 2 , 3 , 7 , 8 , 9 , 15 , 16 , 17 } ; internal class Sequence { public int Start { get ; set ; } public int End { get ; set ; } } internal static class EnumerableMixins { public static IEnumerable < Sequence > GroupFragments ( this IEnumerable < int > sequence ) { if ( sequence.Any ( ) ) { var lastNumber = sequence.First ( ) ; var firstNumber = lastNumber ; foreach ( var number in sequence.Skip ( 1 ) ) { if ( Math.Abs ( number - lastNumber ) > 1 ) { yield return new Sequence ( ) { Start = firstNumber , End = lastNumber } ; firstNumber = lastNumber = number ; } else { lastNumber = number ; } } yield return new Sequence ( ) { Start = firstNumber , End = lastNumber } ; } } } | LINQ Query to identify fragments in a series |
C_sharp : I created an Class which is only able to handle primitive ( or ICloneable ) TypesI want to know if it 's possible to say something like : or do I really need to create a constructor for each primitive type like : What I am trying to achieve is to create an object with 3 public properties Value , Original and IsDirty.The Value will be an deep Clone of Original so the Original needs to be primitve or ICloneable <code> public myobject ( primitiv original ) { ... } public myobject ( int original ) { ... } public myobject ( bool original ) { ... } ... | How to tell a constructor it should only use primitive types |
C_sharp : If I have a string like thisHow can I parse it such that the result would be three string `` words '' which have the following content : Edit 2 : note that the quotation marks are to be retainedAt first , I attempted by using string.Split ( ' ' ) , but I noticed that it would make the third string broken to few other strings.I try to limit the Split result by using its count argument as 3 to solve this . And is it ok for this case , but when the given string isThen the Split fails because the last two words will be combined.I also created something like ReadInBetweenSameDepth to get the string in between the quotation markHere is my ReadInBetweenSameDepth methodBut though this function is working , I found it pretty hard to combine the result with the string.Split to make the correct parsing as I want.Edit 2 : In my poor solution , I need to re-add the quotation marks later onIs there any better way to do this ? If we use Regex , how do we do this ? Edit : I honestly am unaware that this problem could be solved the same way as the CSV formatted text . Neither did I know that this problem is not necessarily solved by Regex ( thus I labelled it as such ) . My sincere apology to those who see this as duplicate post . Edit 2 : After working more on my project , I realized that there was something wrong with my question ( that is , I did not include quotation mark ) - My apology to the previously best answerer , Mr. Tim Schmelter . And then after looking at the dupe-link , I noticed that it does n't provide the answer for this either . <code> create myclass `` 56 , 'for the better or worse ' , 54.781 '' [ 0 ] create [ 1 ] myclass [ 2 ] `` 56 , 'for the better or worse ' , 54.781 '' create myclass false `` 56 , 'for the better or worse ' , 54.781 '' //orcreate myclass `` 56 , 'for the better or worse ' , 54.781 '' false //Examples : // [ 1 ] ( 2 + 1 ) * ( 5 + 6 ) will return 2 + 1 // [ 2 ] ( 2 * ( 5 + 6 ) + 1 ) will return 2 * ( 5 + 6 ) + 1public static string ReadInBetweenSameDepth ( string str , char delimiterStart , char delimiterEnd ) { if ( delimiterStart == delimiterEnd || string.IsNullOrWhiteSpace ( str ) || str.Length < = 2 ) return null ; int delimiterStartFound = 0 ; int delimiterEndFound = 0 ; int posStart = -1 ; for ( int i = 0 ; i < str.Length ; ++i ) { if ( str [ i ] == delimiterStart ) { if ( i > = str.Length - 2 ) //delimiter start is found in any of the last two characters return null ; //it means , there is n't anything in between the two if ( delimiterStartFound == 0 ) //first time posStart = i + 1 ; //assign the starting position only the first time ... delimiterStartFound++ ; //increase the number of delimiter start count to get the same depth } if ( str [ i ] == delimiterEnd ) { delimiterEndFound++ ; if ( delimiterStartFound == delimiterEndFound & & i - posStart > 0 ) return str.Substring ( posStart , i - posStart ) ; //only successful if both delimiters are found in the same depth } } return null ; } | Parse string with whitespace and quotation mark ( with quotation mark retained ) |
C_sharp : I have dimensional list : I would do binary search by the first column ( words ) , something like this : but it works only for a one-dimensional list . How would I extend it to work for two-dimensional lists in my case ? I do n't want to use Dictionary class . <code> List < List < string > > index_en_bg = new List < List < string > > ( ) ; index_en_bg.Add ( new List < string > ( ) { word1 , translation1 } ) ; index_en_bg.Add ( new List < string > ( ) { word2 , translation2 } ) ; index_en_bg.Add ( new List < string > ( ) { word3 , translation3 } ) ; int row = index_en_bg.BinarySearch ( searchingstr ) ; | BinarySearch in two dimensional list |
C_sharp : My Question is simpleVB.dll ( VB5.0 I guess ) includes these methodsin C # ... . ( .NET 4.5 ) The first one works great , but the second one spilt this error . A call to PInvoke function 'ffr_data_transceive_ex ' has unbalanced the stack . This is likely because the managed PInvoke signature does not match the unmanaged target signature . Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.FYIThis is a working code from VB ... ( NOT INNER DLL SOURCES ) I do n't even understand what Dim rData As String * 40 is about ... will it become 0 when rData is 0 ? and become 40 when rData has 1 ? ... What 's wrong with my DllImport methods in C # ? ? ? <code> Private Declare Function ffr_device_find Lib `` .\ffr_32.dll '' ( ) As BooleanPrivate Declare Function ffr_data_transceive_ex Lib `` .\ffr_32.dll '' ( ByVal sp_sdata As String , ByVal sp_rdata As String ) As Boolean [ DllImport ( `` FFR_32.dll '' , CallingConvention = CallingConvention.Cdecl ) ] extern public static Boolean ffr_device_find ( ) ; [ DllImport ( `` FFR_32.dll '' , CallingConvention = CallingConvention.Cdecl ) ] extern public static void ffr_data_transceive_ex ( [ Out ] string sp_sdata , [ Out ] string sp_rdata ) ; // FYI , I tried [ Out ] , out , and ref but to no avail . Dim st As StringDim rData As String * 40st = `` 4401 '' & `` 20202020202020202020202020202020 '' Text1.Text = stCal_BCCCall ffr_data_transceive_ex ( Text1.Text , rData ) Text2.Text = rData | VB5 dll , how can I invoke the function from C # ( .NET 4.5 ) |
C_sharp : Here 's what I am trying to write : The signature of the Bar ( ) method is : So I get a compile error because the T in Foo 's signature does n't have the same constraint . Unfortunately I ca n't write : because Foo is implementing a method defined in an external interface . Question is : Can I somehow transpose the T within the method Foo before calling Bar . ( Note , I can be sure that T always will be a class - I just need to get past the compiler ) .The only way I have found is using reflection but I wonder if there is a simpler trick I 'm missing . <code> public void Foo < T > ( T parameter ) { otherObject.Bar < T > ( parameter ) ; } public void Bar < T > ( T parameter ) where T : class public void Foo < T > ( T parameter ) where T : class { otherObject.Bar < T > ( parameter ) ; } | How to cast a generic parameter ? |
C_sharp : I have a windows TCP service , which has many devices connecting to it , and a client can have one or more devices.Requirement : Separate Folder per client with separate log file for each device.so something like this : Now I have not used a 3rd Party library like log4net or NLog , I have a class which handles this.And then I can use it like this : The problem with the above class is that , because the service is multi-threaded , some threads try to access the same log file at the same time causing an Exception to Throw.Which sometimes causes my service to crash.How do I make my Logger class to work in multi-threaded services ? EDITChanges to the Logger Class <code> /MyService/25-04-2016/ Client 1/ Device1.txt Device2.txt Device3.txt Client 2/ Device1.txt Device2.txt Device3.txt public class xPTLogger : IDisposable { private static object fileLocker = new object ( ) ; private readonly string _logFileName ; private readonly string _logFilesLocation ; private readonly int _clientId ; public xPTLogger ( ) : this ( `` General '' ) { } public xPTLogger ( string logFileName ) { _clientId = -1 ; _logFileName = logFileName ; _logFilesLocation = SharedConstants.LogFilesLocation ; // D : /LogFiles/ } public xPTLogger ( string logFileName , int companyId ) { _clientId = companyId ; _logFileName = logFileName ; _logFilesLocation = SharedConstants.LogFilesLocation ; } public void LogMessage ( MessageType messageType , string message ) { LogMessage ( messageType , message , _logFileName ) ; } public void LogExceptionMessage ( string message , Exception innerException , string stackTrace ) { var exceptionMessage = innerException ! = null ? string.Format ( `` Exception : [ { 0 } ] , Inner : [ { 1 } ] , Stack Trace : [ { 2 } ] '' , message , innerException.Message , stackTrace ) : string.Format ( `` Exception : [ { 0 } ] , Stack Trace : [ { 1 } ] '' , message , stackTrace ) ; LogMessage ( MessageType.Error , exceptionMessage , `` Exceptions '' ) ; } public void LogMessage ( MessageType messageType , string message , string logFileName ) { var dateTime = DateTime.UtcNow.ToString ( `` dd-MMM-yyyy '' ) ; var logFilesLocation = string.Format ( `` { 0 } { 1 } \\ '' , _logFilesLocation , dateTime ) ; if ( _clientId > -1 ) { logFilesLocation = string.Format ( `` { 0 } { 1 } \\ { 2 } \\ '' , _logFilesLocation , dateTime , _clientId ) ; } var fullLogFile = string.IsNullOrEmpty ( logFileName ) ? `` GeneralLog.txt '' : string.Format ( `` { 0 } .txt '' , logFileName ) ; var msg = string.Format ( `` { 0 } | { 1 } | { 2 } \r\n '' , DateTime.UtcNow.ToString ( `` dd-MMM-yyyy HH : mm : ss '' ) , messageType , message ) ; fullLogFile = GenerateLogFilePath ( logFilesLocation , fullLogFile ) ; LogToFile ( fullLogFile , msg ) ; } private string GenerateLogFilePath ( string objectLogDirectory , string objectLogFileName ) { if ( string.IsNullOrEmpty ( objectLogDirectory ) ) throw new ArgumentNullException ( string.Format ( `` { 0 } location can not be null or empty '' , `` objectLogDirectory '' ) ) ; if ( string.IsNullOrEmpty ( objectLogFileName ) ) throw new ArgumentNullException ( string.Format ( `` { 0 } can not be null or empty '' , `` objectLogFileName '' ) ) ; if ( ! Directory.Exists ( objectLogDirectory ) ) Directory.CreateDirectory ( objectLogDirectory ) ; string logFilePath = string.Format ( `` { 0 } \\ { 1 } '' , objectLogDirectory , objectLogFileName ) ; return logFilePath ; } private void LogToFile ( string logFilePath , string message ) { if ( ! File.Exists ( logFilePath ) ) { File.WriteAllText ( logFilePath , message ) ; } else { lock ( fileLocker ) { File.AppendAllText ( logFilePath , message ) ; } } } public void Dispose ( ) { fileLocker = new object ( ) ; } } var _logger = new xPTLogger ( `` DeviceId '' , 12 ) ; _logger.LogMessage ( MessageType.Info , string.Format ( `` Information Message = [ { 0 } ] '' , 1 ) ) ; 25-Apr-2016 13:07:00 | Error | Exception : The process can not access the file 'D : \LogFiles\25-Apr-2016\0\LogFile.txt ' because it is being used by another process . public class xPTLogger : IDisposable { private object fileLocker = new object ( ) ; private readonly string _logFileName ; private readonly string _logFilesLocation ; private readonly int _companyId ; public xPTLogger ( ) : this ( `` General '' ) { } public xPTLogger ( string logFileName ) { _companyId = -1 ; _logFileName = logFileName ; _logFilesLocation = SharedConstants.LogFilesLocation ; // `` D : \\MyLogs '' ; } public xPTLogger ( string logFileName , int companyId ) { _companyId = companyId ; _logFileName = logFileName ; _logFilesLocation = SharedConstants.LogFilesLocation ; } public void LogMessage ( MessageType messageType , string message ) { LogMessage ( messageType , message , _logFileName ) ; } public void LogExceptionMessage ( string message , Exception innerException , string stackTrace ) { var exceptionMessage = innerException ! = null ? string.Format ( `` Exception : [ { 0 } ] , Inner : [ { 1 } ] , Stack Trace : [ { 2 } ] '' , message , innerException.Message , stackTrace ) : string.Format ( `` Exception : [ { 0 } ] , Stack Trace : [ { 1 } ] '' , message , stackTrace ) ; LogMessage ( MessageType.Error , exceptionMessage , `` Exceptions '' ) ; } public void LogMessage ( MessageType messageType , string message , string logFileName ) { if ( messageType == MessageType.Debug ) { if ( ! SharedConstants.EnableDebugLog ) return ; } var dateTime = DateTime.UtcNow.ToString ( `` dd-MMM-yyyy '' ) ; var logFilesLocation = string.Format ( `` { 0 } { 1 } \\ '' , _logFilesLocation , dateTime ) ; if ( _companyId > -1 ) { logFilesLocation = string.Format ( `` { 0 } { 1 } \\ { 2 } \\ '' , _logFilesLocation , dateTime , _companyId ) ; } var fullLogFile = string.IsNullOrEmpty ( logFileName ) ? `` GeneralLog.txt '' : string.Format ( `` { 0 } .txt '' , logFileName ) ; var msg = string.Format ( `` { 0 } | { 1 } | { 2 } \r\n '' , DateTime.UtcNow.ToString ( `` dd-MMM-yyyy HH : mm : ss '' ) , messageType , message ) ; fullLogFile = GenerateLogFilePath ( logFilesLocation , fullLogFile ) ; LogToFile ( fullLogFile , msg ) ; } private string GenerateLogFilePath ( string objectLogDirectory , string objectLogFileName ) { if ( string.IsNullOrEmpty ( objectLogDirectory ) ) throw new ArgumentNullException ( string.Format ( `` { 0 } location can not be null or empty '' , `` objectLogDirectory '' ) ) ; if ( string.IsNullOrEmpty ( objectLogFileName ) ) throw new ArgumentNullException ( string.Format ( `` { 0 } can not be null or empty '' , `` objectLogFileName '' ) ) ; if ( ! Directory.Exists ( objectLogDirectory ) ) Directory.CreateDirectory ( objectLogDirectory ) ; string logFilePath = string.Format ( `` { 0 } \\ { 1 } '' , objectLogDirectory , objectLogFileName ) ; return logFilePath ; } private void LogToFile ( string logFilePath , string message ) { lock ( fileLocker ) { try { if ( ! File.Exists ( logFilePath ) ) { File.WriteAllText ( logFilePath , message ) ; } else { File.AppendAllText ( logFilePath , message ) ; } } catch ( Exception ex ) { var exceptionMessage = ex.InnerException ! = null ? string.Format ( `` Exception : [ { 0 } ] , Inner : [ { 1 } ] , Stack Trace : [ { 2 } ] '' , ex.Message , ex.InnerException.Message , ex.StackTrace ) : string.Format ( `` Exception : [ { 0 } ] , Stack Trace : [ { 1 } ] '' , ex.Message , ex.StackTrace ) ; var logFilesLocation = string.Format ( `` { 0 } { 1 } \\ '' , _logFilesLocation , DateTime.UtcNow.ToString ( `` dd-MMM-yyyy '' ) ) ; var logFile = GenerateLogFilePath ( logFilesLocation , `` FileAccessExceptions.txt '' ) ; try { if ( ! File.Exists ( logFile ) ) { File.WriteAllText ( logFile , exceptionMessage ) ; } else { File.AppendAllText ( logFile , exceptionMessage ) ; } } catch ( Exception ) { } } } } public void Dispose ( ) { //fileLocker = new object ( ) ; //_logFileName = null ; //_logFilesLocation = null ; //_companyId = null ; } } | Separate Logfile and directory for each client and date |
C_sharp : In C # , volatile keyword ensures that reads and writes have acquire and release semantics , respectively . However , does it say anything about introduced reads or writes ? For instance : <code> volatile Thing something ; volatile int aNumber ; void Method ( ) { // Are these lines ... var local = something ; if ( local ! = null ) local.DoThings ( ) ; // ... guaranteed not to be transformed into these by compiler , jitter or processor ? if ( something ! = null ) something.DoThings ( ) ; // < -- Second read ! // Are these lines ... if ( aNumber == 0 ) aNumber = 1 ; // ... guaranteed not to be transformed into these by compiler , jitter or processor ? var temp = aNumber ; if ( temp == 0 ) temp = 1 ; aNumber = temp ; // < -- An out-of-thin-air write ! } | Does volatile prevent introduced reads or writes ? |
C_sharp : I 'm refreshing my memory on how reference and value types work in .NET . I understand that the entry on the stack for a reference type contains a pointer to a memory location on the heap . What I ca n't seem to find details about is what else the stack entry contains . So , given the following : After the first line of code an entry on the stack containing a null pointer will exist . Does that entry also contain the identifying name `` customer '' ? Does it contain type information ? Have I fundamentally misunderstood something ? <code> Customer customer ; customer = new Customer ( ) ; | What does the stack entry for a reference type contain ? |
C_sharp : Given an Expression < Func < TEntity , bool > > along the lines ofI am trying to extract a list property conditions by type , i.e.So far , I have created an ExpressionVisitor and identified the VisitBinary method as the one I want to plug into in order to obtain my information.I am still at a loss abouthow to determine whether the BinaryExpression I am looking at represents a terminal statement ( in the sense that there are no more nested expressions that I need to look at ) how to determine the Entity type that the BinaryExpression is concerned withwhether I need to override any of the other ExpressionVisitor methods to cover for cases that I have not considered yet . <code> entity = > entity.SubEntity.Any ( subEntity = > ( ( subEntity.SomeProperty == False ) AndAlso subEntity.SubSubEntity.FooProperty.StartsWith ( value ( SomeClass+ < > c__DisplayClass0 ) .ComparisonProperty ) AndAlso subEntity.SubSubEntity.BarProperty == `` Bar '' AndAlso subEntity.SubSubEntity.SubSubSubEntity.Any ( subSubSubEntity = > ( x.SubSubSubSubEntity.BazProperty == `` whatever '' ) ) ) ) TEntity : [ /* no conditions for immediate members of TEntity */ ] TSubEntity : [ { SomeProperty == False } ] TSubSubEntity : [ { FooProperty.StartsWith ( /* ... */ ) } , { BarProperty == `` Bar '' } ] , TSubSubSubEntity : [ /* no conditions for immediate members of TSubSubSubEntity */ ] , TSubSubSubSubEntity : [ { BazProperty == `` whatever '' } ] | Extract all conditions from Expression by Type |
C_sharp : UPDATE : I 've found the answer , which I will post in a couple of days if nobody else does.I am creating a numeric struct , so I am overloading the arithmetical operators . Here is an example for a struct that represents a 4-bit unsigned integer : The overloaded addition operator allows this code : Here , the calculation overflows , so the variable z has the value 5 . I would also like to be able to do this , however : This sample should throw an OverflowException . How can I achieve that ? I have already established that the checked context does not extend to called methods , so , for example , this does not throw , regardless of whether it is called in a checked or unchecked context : Is there a way of declaring two overloads of the addition operator , one checked and the other unchecked ? Alternatively , is there a way to determine at run time the context of the caller ( which seems highly unlikely , but I thought I 'd ask nonetheless ) , something like this : <code> public struct UInt4 { private readonly byte _value ; private const byte MinValue = 0 ; private const byte MaxValue = 15 ; public UInt4 ( int value ) { if ( value < MinValue || value > MaxValue ) throw new ArgumentOutOfRangeException ( `` value '' ) ; _value = ( byte ) value ; } public static UInt4 operator + ( UInt4 a , UInt4 b ) { return new UInt4 ( ( a._value + b._value ) & MaxValue ) ; } } var x = new UInt4 ( 10 ) ; var y = new UInt4 ( 11 ) ; var z = x + y ; var x = new UInt4 ( 10 ) ; var y = new UInt4 ( 11 ) ; var z = checked ( x + y ) ; public static UInt4 operator + ( UInt4 a , UInt4 b ) { int i = int.MaxValue ; //this should throw in a checked context , but when //the operator is used in a checked context , this statement //is nonetheless unchecked . byte b = ( byte ) i ; return new UInt4 ( ( a._value + b._value ) & MaxValue ) ; } public static UInt4 operator + ( UInt4 a , UInt4 b ) { byte result = ( byte ) ( a._value + b._value ) ; if ( result > MaxValue ) if ( ContextIsChecked ( ) ) throw new OverflowException ( ) ; else result & = MaxValue ; return new UInt4 ( result ) ; } private static bool ContextIsChecked ( ) { throw new NotImplementedException ( `` Please help . `` ) ; } | Overloading the + operator so it is sensitive to being called in a checked or unchecked context |
C_sharp : I am very new to programming and I have a question , I am trying to use Regex method to extract hours , minutes and seconds from a string and putting them into an array , but so far I can do it with only one number : How do manage to read from a string 06 : 11 : 33 , and transform these hours , minutes and seconds into an array of ints ? So the resulting array would be like this : Thank you for your time in advance ! <code> int initialDay D = 0 ; string startDay = Console.ReadLine ( ) ; //input : `` It started 5 days ago '' var resultString = Regex.Match ( startDay , @ '' \d+ '' ) .Value ; initialDay = Int32.Parse ( resultString ) ; // initialDay here equals 5. int [ ] array = new int [ ] { n1 , n2 , n3 } ; // the n1 would be 6 , n2 would be 11 and n3 would be 33 | Regex extract from string xx : xx : xx format |
C_sharp : I have developed a small-ish C # console application ( TextMatcher.exe ) on my local development machine and now need to deploy it to the live environment . It references another class library which I developed which has generic functions , which I intend to use and improve in future console applications.Ultimately this specific application will be executed from within an SSIS package , but for now I 'm just trying to run it from cmd.I kid you not that this is the actual output from the program : The computer literally says `` No '' and gives no further information . I have not included , anywhere in the program , to output the word `` No '' , on any failure or otherwise.Of course , it runs fine locally . I made sure I included the dll of the utility class library too . I have read other questions ( here , here ) about how to deploy console apps correctly , and have followed the advice.NB : This is also proving to be quite hard to Google because of the use of the word `` No '' being fundamental to the problem ... EDIT - It seems to be working now ... I simply copied over the files again from my local machine to the remote machine ... I am trying to get it to break again so that I can figure out what on Earth happened , and until I do , I will not accept an answer so that people could maybe shed some more light onto it . Either way it is quite baffling . <code> E : /TextMatcher > TextMatcher.exeNoE : /TextMatcher > | C # application says `` No '' when executed |
C_sharp : I need to split List < IInterface > to get lists of concrete implementations of IInterface.How can I do it in optimal way ? <code> public interface IPet { } public class Dog : IPet { } public class Cat : IPet { } public class Parrot : IPet { } public void Act ( ) { var lst = new List < IPet > ( ) { new Dog ( ) , new Cat ( ) , new Parrot ( ) } ; // I need to get three lists that hold each implementation // of IPet : List < Dog > , List < Cat > , List < Parrot > } | C # split List of interface by implementations |
C_sharp : I have a predicate Expression < Func < T1 , bool > > I need to use it as a predicate Expression < Func < T2 , bool > > using the T1 property of T2 I was trying to think about several approches , probably using Expression.Invoke but couln ; t get my head around it.For reference : AndThanks a lot in advance . <code> class T2 { public T1 T1 ; } Expression < Func < T1 , bool > > ConvertPredicates ( Expression < Func < T2 , bool > > predicate ) { //what to do here ... } | Linq - Creating Expression < T1 > from Expression < T2 > |
C_sharp : I read of a useful trick about how you can avoid using the wrong domain data in your code by creating a data type for each domain type you 're using . By doing this the compiler will prevent you from accidentally mixing your types.For example , defining these : allows me to not mix up meters and seconds because they 're separate data types . This is great and I can see how useful it can be . I 'm aware you 'd still need to define operator overloads to handle any kind of arithmetic with these types , but I 'm leaving that out for simplicity.The problem I 'm having with this approach is that in order to use these types I need to use the full constructor every time , like this : Is there any way in C # I can use the same mode of construction that a System.Int32 uses , like this : I tried creating an implicit conversion but it seems this would need to be part of the Int32 type , not my custom types . I ca n't add an Extension Method to Int32 because it would need to be static , so is there any way to do this ? <code> public struct Meter { public int Value ; public Meter ( int value ) { this.Value = value ; } } public struct Second { public int Value ; public Second ( int value ) { this.Value = value ; } } Meter distance = new Meter ( 5 ) ; Meter distance = 5 ; | Is there any way to implicitly construct a type in C # ? |
C_sharp : consider the following code : //This prints 53954 . Why ? ? and //This prints 40000 . how ? ? any help appreciable ... <code> ushort a = 60000 ; a = ( ushort ) ( a * a / a ) ; Console.WriteLine ( `` A = `` + a ) ; ushort a = 40000 ; a = ( ushort ) ( a * a / a ) ; Console.WriteLine ( `` a = `` + a.ToString ( ) ) ; | confusion with result of Ushort |
C_sharp : I have static method like this : and I use it as following : How write method that return the following results ? s1 : `` ID '' s2 : `` Age '' s3 : `` Name '' * return each property ` s name after = > as string <code> public static string MyMethod ( Func < Student , object > func ) { return ? ? ? ; } var s1 = MyMethod ( student = > student.ID ) ; // Return `` ID '' ? ? ? var s2 = MyMethod ( student = > student.Age ) ; // Return `` Age '' ? ? ? var s3 = MyMethod ( student = > student.Name ) ; // Return `` Name '' ? ? ? | How Func < DomainObject , object > return Object name as string |
C_sharp : In C # resizing an array ( increasing its size in this case ) initializes the new segment with default values – is this reliable ? I do see the default values ( 0 for byte arrays ) , but is it possible to safely take that as the standard behavior for all base types ? In my application saving every second is a big deal , hence thought I could avoid unnecessary loop to initialize the newly added segment if it is already available by default . Microsoft .NET document doesn ’ t explicitly state this fact : https : //docs.microsoft.com/en-us/dotnet/api/system.array.resize ? view=netframework-4.8 although the examples kind of hint to that behavior . <code> Array.Resize ( ref bytes , bytes.Length + extra ) ; | In C # resizing an array ( increasing its size in this case ) initializes the new segment with default values – is this reliable ? |
C_sharp : I have been looking into speeding up my application as it is performance critical ... i.e . every millisecond I can get out of it is better . To do this I have a method that calls some other methods and each of these other methods is wrapped with a Stopwatch timer and Console.WriteLine calls . I.e . : The problem is whenever I comment out the Stopwatch and Console.WriteLine lines the code runs about 20ms ( not 50 ) slower which is a lot for what I need.Does anyone know why this is ? EDIT : The SomeMainMethod method and others in the class are also wrapped in a Stopwatch and Console.WriteLine calls similar to above.The SomeMainMethod and the methods it calls is part of a class that is part of a Class Library that is called from a console testbed , all of which is single threaded.For more information : The app is running in x86 .NET 4.6.1 Release mode with optimisations enabled . I am also running this in visual studio 2013 not outside of it . <code> private void SomeMainMethod ( ) { System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch ( ) ; sw.Start ( ) ; SomeMethod ( ) ; sw.Stop ( ) ; Console.WriteLine ( `` Time for SomeMethod = { 0 } ms '' , sw.ElapsedMilliseconds ) ; sw.Reset ( ) ; sw.Start ( ) ; SomeOtherMethod ( ) ; sw.Stop ( ) ; Console.WriteLine ( `` Time for SomeOtherMethod= { 0 } ms '' , sw.ElapsedMilliseconds ) ; // ... } | Console.WriteLine speeds up my code ? |
C_sharp : In C # , you can do something like this : What is this syntax called ? <code> SomeClass someClass = new SomeClass ( ) { SomeProperty = someValue } ; | What is the name of this C # syntax ? |
C_sharp : In the below example I have created a class named 'Custom ' that implements IComparable : Implementations of CompareTo ( Object ) are generally `` forgiving '' in that they will cast 'value ' to a more specific type . In this case , a cast to the type 'Custom ' will be performed so a comparison can be made . Imagine I also overload the == operator : The problem I 've run into is in this case : The problem is that when == is invoked , because the rhs is of type 'Object ' , it falls back to the default test for reference equality - the overload is not called.What is the expectation here ? I can add another overload for the == operator : But examples like this are noticeably absent from MSDN or other online examples . This makes me think that the test for reference equality is the expected behavior <code> public int CompareTo ( Object value ) { // comparison logic here } public static bool operator== ( Custom lhs , Custom rhs ) { // equivalence test here } Custom c = GetCustomObject ( ) ; Object o = GetOtherObject ( ) ; if ( c == o ) { // will not be true unless c and o are the same object } public static bool operator== ( Custom lhs , Object rhs ) | How to handle operator == overload when the right hand side is of type Object |
C_sharp : I came across this and am curious as to why is it not possible to use the is operator to discern between bool and Nullable < bool > ? Example ; Calling Main ( ) gives ; I 'd expect ; Why do both bool and Nullable < bool > match each other ? What have I tried ; I 've consulted the docs for Nullable , is , switch and pattern matching.I think this might be related to unboxing of the value when it 's passed into the method ? I think it might be unique to Nullable because I do n't run into the same problems for other generic types . For example ; Gives ; I 'm not looking to solve a problem . Just interested as to why it works this way.Answers so far suggest it 's implicit and explicit conversions that cause this behaviour but I have n't been able to replicate with the following example ; Gives ; The docs for is say : It only considers reference conversions , boxing conversions , and unboxing conversions ; it does not consider user-defined conversions or conversions defined by a type 's implicit and explicit operators . The following example generates warnings because the result of the conversion is known at compile-time . Note that the is expression for conversions from int to long and double return false , since these conversions are handled by the implicit operator.Are reference conversions , boxing conversions , and unboxing conversions something the framework decides ? <code> void Main ( ) { bool theBool = false ; Nullable < bool > theNullableBoolThatsFalse = false ; Nullable < bool > theNullableBoolThatsNull = null ; void WhatIsIt ( object value ) { if ( value is bool ) Console.WriteLine ( `` It 's a bool ! `` ) ; if ( value is Nullable < bool > ) Console.WriteLine ( `` It 's a Nullable < bool > ! `` ) ; if ( value is null ) Console.WriteLine ( `` It 's a null ! `` ) ; } Console.WriteLine ( `` Considering theBool : '' ) ; WhatIsIt ( theBool ) ; Console.WriteLine ( `` Considering theNullableBoolThatsFalse : '' ) ; WhatIsIt ( theNullableBoolThatsFalse ) ; Console.WriteLine ( `` Considering theNullableBoolThatsNull : '' ) ; WhatIsIt ( theNullableBoolThatsNull ) ; } Considering theBool : It 's a bool ! It 's a Nullable < bool > ! Considering theNullableBoolThatsFalse : It 's a bool ! It 's a Nullable < bool > ! Considering theNullableBoolThatsNull : It 's a null ! Considering theBool : It 's a bool ! Considering theNullableBoolThatsFalse : It 's a Nullable < bool > ! Considering theNullableBoolThatsNull : It 's a null ! void Main ( ) { bool theBool = false ; List < bool > theListOfBool= new List < bool > ( ) ; void WhatIsIt ( object value ) { if ( value is bool ) Console.WriteLine ( `` It 's a bool ! `` ) ; if ( value is List < bool > ) Console.WriteLine ( `` It 's a List < bool > ! `` ) ; } Console.WriteLine ( `` Considering theBool : '' ) ; WhatIsIt ( theBool ) ; Console.WriteLine ( `` Considering theListOfBool : '' ) ; WhatIsIt ( theListOfBool ) ; } Considering theBool : It 's a bool ! Considering theListOfBool : It 's a List < bool > class A { public static implicit operator A ( B value ) = > new A ( ) ; public static explicit operator B ( A value ) = > new B ( ) ; } class B { public static implicit operator A ( B value ) = > new A ( ) ; public static explicit operator B ( A value ) = > new B ( ) ; } static void Main ( string [ ] args ) { var a = new A ( ) ; var b = new B ( ) ; void WhatIsIt ( object value ) { if ( value is A ) Console.WriteLine ( `` It 's a A ! `` ) ; if ( value is B ) Console.WriteLine ( `` It 's a B ! `` ) ; } Console.WriteLine ( `` Considering a ; '' ) ; WhatIsIt ( a ) ; Console.WriteLine ( `` Considering b ; '' ) ; WhatIsIt ( b ) ; } Considering a ; It 's a A ! Considering b ; It 's a B ! | Why is it not possible to use the is operator to discern between bool and Nullable < bool > ? |
C_sharp : I have a problem with generic . When I try to use less operators in generic , their call is not happening . But it works with the method Equals.That is a some test class : And class Checker : Small testing : How I can use less operators in class Test from generic ? <code> public class Test { public int i ; static public Boolean operator == ( Test obj1 , Test obj2 ) { Console.WriteLine ( `` operator == '' ) ; return obj1.i == obj2.i ; } static public Boolean operator ! = ( Test obj1 , Test obj2 ) { Console.WriteLine ( `` operator ! = '' ) ; return obj1.i ! = obj2.i ; } public override bool Equals ( object obj ) { Console.WriteLine ( `` operator equals '' ) ; return this == ( Test ) obj ; } public override int GetHashCode ( ) { Console.WriteLine ( `` HashCode '' ) ; return 5 ; } } public class Checker { public Boolean TestGeneric < T > ( T Left , T Right ) where T : class { return Left == Right ; //not work override operators return Left.Equals ( Right ) ; //work fine } } Test left = new Test ( ) { i = 4 } ; Test right = new Test ( ) { i = 4 } ; var checker = new Checker ( ) ; Console.WriteLine ( checker.TestGeneric < Test > ( left , right ) ) ; Console.ReadKey ( ) ; | C # generics class operators not working |
C_sharp : I have people and places data as : Person entity hasIList < DateRangePlaces > each havingIList < Place > of possible places Schedule day pattern as ie . 10 days available 4 unavailableWithin a particular DateRangePlaces date range one has to obey to Schedule pattern whether person can go to a particular place or not.Place entity hasIList < DateRangeTiming > each defining opening/closing times within each date rangeOverlapping date ranges work as LIFO . So for each day that has already been defined previously new timing definition takes preference.The problemNow I need to do something like this ( in pseudo code ) : This means that number of steps to execute my task is approx . : ∑ ( places ) ( ∑ ( days ) × ∑ ( people ) ) This to my understanding is O ( x × yx × z ) and likely approximates to this algorithm complexity : O ( n3 ) I 'm not an expert in theory so you can freely correct my assumptions . What is true is that this kind of complexity is definitely not acceptable especially given the fact that I will be operating over long date ranges with many places and people.From the formula approximation we can see that people set would be iterated lots of times . Hence I would like to optimize at least this part . To ease things a bit I changedtowhich would give me a faster result whether a person can go to some place on particular date , because I would only check whether Place.Id is present in the dictionary versus IList.Where ( ) LINQ clause that would have to scan the whole list each and every time.QuestionCan you suggest any additional optimizations I could implement into my algorithm to make it faster or even make it less complex in terms of the big O notation ? Which memory structure types would you use where and why ( lists , dictionaries , stacks , queues ... ) to improve performance ? Addendum : The whole problem is even more complexThere 're also additional complexities that I did n't mention since I wanted to simplify my question to make it more clear . So . There 's also : So places require particular permissions and people have a limited time permission grants that expire.Additional to that , there 's alsowhich tells only particular times that person can go somewhere during particular date range . AndWhich defines place prioritization for a particular date range.And during this process of getting applicable people I also have to calculate certain factor per every person per every place that 's related to the : number of places that a person can visit on particular dayperson 's place priority factor on that particular dayAll these are the reasons why I decided to rather manipulate this data in memory than using a very complex stored procedure that would also be doing multiple table scans to get factors per person and place and day.I think such stored procedure would be way to complex to handle and maintain . So I rather get all the data first ( put it appropriate memory structures to aid performance ) and then mangle with it in memory . <code> for each Place { for each Day between minimum and maximum date in IList < DateRangeTiming > { get a set of People applicable for Place and on Day } } Person.IList < DateRangePlaces > .IList < Place > Person.IList < DateRangePlaces > .IDictionary < int , Place > Place.IList < Permission > Person.IList < DateRangePermission > Person.IList < DateRangeTimingRestriction > Person.IList < DateRangePlacePriorities > | Advanced : How to optimize my complex O ( n² ) algorithm |
C_sharp : I frequently find myself wanting to do something along these lines : Of course the compiler will now complain that this code is not valid , since ClientSize is a property , and not a variable.We can fix this by setting the ClientSize in its entirety : Or , in general : But this is all looks unnecessary and obfuscated . Why ca n't the compiler do this for me ? And of course , I 'm asking about the general case , possibly involving even deeper levels of properties , not just the mundane example aboveBasically , I 'm asking why there is no syntactic sugar to translate the line form.ClientSize.Width = 500 into the above code . Is this simply a feature which has n't yet been implemented , is it to avoid stacking of side effects from different getters and setters , to prevent confusion when one of the setters is n't defined , or is there a completely different reason why something like this does n't exist ? <code> Form form = new Form ( ) ; form.ClientSize.Width = 500 ; form.ClientSize = new Size ( 500 , ClientSize.Height ) ; Size s = form.ClientSize ; s.Width = 500 ; form.ClientSize = s ; //only necessary if s is a value-type . ( Right ? ) | Why can we not set properties of properties ? |
C_sharp : I think I 'm going mad , someone please reassure me.People keep on adding code like the above in to our code base , surely this is wrong and horrid and I am doing the world a favour by deleting it and replacing all ( or both in this case ... ) references to it with the internal code.Is there any real justification for this kind of thing ? Could I be missing the bigger picture ? We are quite YAGNI-centric in our team and this seems to fly in the face of that . I could understand if this was the beginnings of something more , however this code has lay dormant for many many months until I tripped over it today . The more I search the more I find . <code> public class MyFile { public static byte [ ] ReadBinaryFile ( string fileName ) { return File.ReadAllBytes ( fileName ) ; } public static void WriteBinaryFile ( string fileName , byte [ ] fileContents ) { File.WriteAllBytes ( fileName , fileContents ) ; } } | Methods which wrap a single method |
C_sharp : I 'm an absolute beginner when it comes to C # . Trying to learn via examples . So I 've found myself a nice little calculator tutorial . Everything goes fine up to last moment , the code is working , but it does n't take multi-digit input like 33 . There 's a bool statement there for turning arithmetic operations on/off and tutorial instructor figured , that we should put bool = false before the number input/button press ( in button_Click ) .His code looks like this : It compiles nicely . But when I try to input a multidigit number and follow it with a mathematical operator , it throws an exception for value = double.Parse ( tb.Text ) ; that states : When converting string to DateTime , parse the string to take the date before putting each variable into the DateTime object.I 'm so confused right now . There 's no DateTime even involved ! And I 'm 100 % positive , everything is like in the tutorial . What 's going on ? : /Any help will be appreciated greatly ! EDITScreenshot of actual error : <code> public partial class MainWindow : Window { double value = 0 ; string operation = `` '' ; bool operation_pressed = false ; public MainWindow ( ) { InitializeComponent ( ) ; } private void button_Click ( object sender , RoutedEventArgs e ) { if ( ( tb.Text == `` 0 '' ) || ( operation_pressed == true ) ) tb.Clear ( ) ; operation_pressed = false ; Button b = ( Button ) sender ; tb.Text += `` \n '' + b.Content.ToString ( ) ; } private void operator_Click ( object sender , RoutedEventArgs e ) { Button b = ( Button ) sender ; operation = b.Content.ToString ( ) ; value = double.Parse ( tb.Text ) ; operation_pressed = true ; equation.Content = value + `` `` + operation ; } private void result_Click ( object sender , RoutedEventArgs e ) { equation.Content = `` '' ; switch ( operation ) { case `` + '' : tb.Text = `` \n '' + ( value + double.Parse ( tb.Text ) ) .ToString ( ) ; break ; case `` - '' : tb.Text = `` \n '' + ( value - double.Parse ( tb.Text ) ) .ToString ( ) ; break ; case `` * '' : tb.Text = `` \n '' + ( value * double.Parse ( tb.Text ) ) .ToString ( ) ; break ; case `` / '' : tb.Text = `` \n '' + ( value / double.Parse ( tb.Text ) ) .ToString ( ) ; break ; default : break ; } } private void CE_Click ( object sender , RoutedEventArgs e ) { tb.Text = `` \n 0 '' ; } private void C_Click ( object sender , RoutedEventArgs e ) { tb.Clear ( ) ; equation.Content = `` '' ; value = 0 ; } } | C # bool statement throws strange exception for seemingly unconnected double.parse ( string ) |
C_sharp : I would like to have four buttons like this : On an iPhone or a small mobile I would like to have these fill 90 % of the screen width . But on a bigger screen I would like the buttons to only fill 50 % of the screen width . Can anyone suggest to me how I can do this ? <code> < Grid x : Name= '' buttonGrid '' Grid.Row= '' 3 '' Grid.Column= '' 0 '' HorizontalOptions= '' FillAndExpand '' VerticalOptions= '' Center '' Padding= '' 20 , 0 '' > < Button x : Name= '' zeroButton '' Text= '' 0 '' HeightRequest= '' 60 '' BackgroundColor= '' # 2D7BF7 '' HorizontalOptions= '' FillAndExpand '' VerticalOptions= '' StartAndExpand '' / > < Button x : Name= '' oneButton '' Text= '' 1 '' HeightRequest= '' 60 '' BackgroundColor= '' # 2D7BF7 '' HorizontalOptions= '' FillAndExpand '' VerticalOptions= '' StartAndExpand '' / > < Button x : Name= '' twoButton '' Text= '' 2 '' HeightRequest= '' 60 '' BackgroundColor= '' # 2D7BF7 '' HorizontalOptions= '' FillAndExpand '' VerticalOptions= '' StartAndExpand '' / > < Button x : Name= '' fiveButton '' Text= '' 5 '' HeightRequest= '' 60 '' BackgroundColor= '' # 2D7BF7 '' HorizontalOptions= '' FillAndExpand '' VerticalOptions= '' StartAndExpand '' / > < /Grid > | How can I achieve four spaced buttons on an iPhone that fill the screen and on bigger than an iPhone that fill half the screen ? |
C_sharp : How to match the sentence that start with `` أقول `` by this code ? This is an arbic word . `` أقول `` What is the regular expression exactly ? <code> Regex.Matches ( Content , `` أقول `` ) ; | How to match the sentence that start with `` أقول `` by this code ? |
C_sharp : I have a DataTemplate Column with 2 DatePickers that are bound to 2 properties . When the data in these control is changed only last control gets updatedIn this case if I update both Start and Due Only Due gets updated . Also the binding works fine because if I put a breakPoint on Start in my Model class it gets hit but the value passed is the original value of StartEDIT 1After some debugging I found out that If I only have one control inside my DataTemplate it works Fine . Also When I change the Date The break point is hit straightaway . But if I have more than one control the break point is not hit until I focus out of column and then only the last binding works.EDIT 2After some mroe debugging I noticed that it will work fine if I only use CellTemplate and discard cell EditTemplateEDIT 3I was able to refresh binding on both the control using the selectedDatechange event and then refreshing the binding on the sender . I am still not sure why the 2 way binding working wo n't work . Can anyone explain why this is happening ? EDIT 4Model and Properties <code> < sdk : DataGridTemplateColumn Width= '' 300 '' CanUserReorder= '' False '' > < sdk : DataGridTemplateColumn.CellTemplate > < DataTemplate > < Grid MouseRightButtonDown= '' ActionsGrid_MouseRightButtonDown '' Width= '' 300 '' Height= '' 40 '' MouseLeftButtonDown= '' ActionsGrid_MouseLeftButtonDown '' > < StackPanel Orientation= '' Horizontal '' > < TextBlock VerticalAlignment= '' Stretch '' Width= '' 100 '' Text= '' { Binding Start , Converter= { StaticResource DateConverter } } '' Padding= '' 2 '' HorizontalAlignment= '' Center '' / > < TextBlock VerticalAlignment= '' Stretch '' Width= '' 100 '' Text= '' { Binding Due , Converter= { StaticResource DateConverter } } '' Padding= '' 2 '' HorizontalAlignment= '' Center '' / > < /StackPanel > < /Grid > < /DataTemplate > < /sdk : DataGridTemplateColumn.CellTemplate > < sdk : DataGridTemplateColumn.CellEditingTemplate > < DataTemplate > < StackPanel Orientation= '' Horizontal '' > < sdk : DatePicker VerticalAlignment= '' Top '' Width= '' 100 '' SelectedDate= '' { Binding Start , Mode=TwoWay , } '' Padding= '' 2 '' / > < sdk : DatePicker VerticalAlignment= '' Top '' Width= '' 100 '' SelectedDate= '' { Binding Due , Mode=TwoWay , ValidatesOnDataErrors=True } '' Padding= '' 2 '' / > < /StackPanel > < /DataTemplate > < /sdk : DataGridTemplateColumn.CellEditingTemplate > < /sdk : DataGridTemplateColumn > < sdk : DataGridTemplateColumn Width= '' 300 '' CanUserReorder= '' False '' > < sdk : DataGridTemplateColumn.CellTemplate > < DataTemplate > < StackPanel Orientation= '' Horizontal '' > < sdk : DatePicker VerticalAlignment= '' Top '' Width= '' 100 '' SelectedDate= '' { Binding Start , Mode=TwoWay , } '' Padding= '' 2 '' / > < sdk : DatePicker VerticalAlignment= '' Top '' Width= '' 100 '' SelectedDate= '' { Binding Due , Mode=TwoWay , ValidatesOnDataErrors=True } '' Padding= '' 2 '' / > < /StackPanel > < /DataTemplate > < /sdk : DataGridTemplateColumn.CellEditingTemplate > < /sdk : DataGridTemplateColumn > private void DatePicker_SelectedDateChanged ( object sender , SelectionChangedEventArgs e ) { ( sender as DatePicker ) .GetBindingExpression ( DatePicker.SelectedDateProperty ) .UpdateSource ( ) ; } public DateTime ? Start { get { return _Start ; } set { _Start = value ; Dirty = true ; if ( _Start.HasValue & & _Due.HasValue & & _Start.Value > _Due.Value ) _dataErrors [ `` Start '' ] = `` Start date can not be greater than the Due date '' ; else if ( _dataErrors.ContainsKey ( `` Start '' ) ) _dataErrors.Remove ( `` Start '' ) ; NotifyPropertyChanged ( ) ; NotifyPropertyChanged ( `` CalcStatus '' ) ; } } public DateTime ? Due { get { return _Due ; } set { _Due = value ; Dirty = true ; if ( _Start.HasValue & & _Due.HasValue & & _Start.Value > _Due.Value ) _dataErrors [ `` Start '' ] = `` Start date can not be greater than the Due date '' ; else if ( _dataErrors.ContainsKey ( `` Start '' ) ) _dataErrors.Remove ( `` Start '' ) ; NotifyPropertyChanged ( `` Due '' ) ; NotifyPropertyChanged ( `` CalcStatus '' ) ; } } | Only last control in Data Template column getting updated |
C_sharp : I have 2 scenarios.This fails : error CS0102 : The type ' F < X > ' already contains a definition for ' X ' This works : The only logical explanation is that in the second snippet the type parameter X is out of scope , which is not true ... Why should a type parameter affect my definitions in a type ? IMO , for consistency , either both should work or neither should work.Any other ideas ? PS : I call it 'lexical ' , but it is probably not the correct term.Update : As per Henk 's answer , here is a non-generic version displaying the same behavior , but perhaps easier to grok.Fails : Works : From what I can see , the C # compiler creates a lexical scope at type definition boundries.It also implies that types and member names live in the same 'location ' ( or namespace in terms of LISP ) . <code> class F < X > { public X X { get ; set ; } } class F < X > { class G { public X X { get ; set ; } } } class F { class X { } public X X { get ; set ; } } class X { } class F { public X X { get ; set ; } } | 'Lexical ' scoping of type parameters in C # |
C_sharp : I want to see the real time use of Volatile keyword in c # . but am unable to project the best example . the below sample code works without Volatile keyword how can it possible ? In the above code i am getting a value as 5. how it works without using volatile keyword ? <code> class Program { private static int a = 0 , b = 0 ; static void Main ( string [ ] args ) { Thread t1 = new Thread ( Method1 ) ; Thread t2 = new Thread ( Method2 ) ; t1.Start ( ) ; t2.Start ( ) ; Console.ReadLine ( ) ; } static void Method1 ( ) { a = 5 ; b = 1 ; } static void Method2 ( ) { if ( b == 1 ) Console.WriteLine ( a ) ; } } | What is the volatile keyword purpose in c # ? |
C_sharp : BackgroundI have a website that displays data unique to a client . The site required views to be created ever time a new client is added . Each client is unique and has a different identifying information unique to them . For example an ID number and a prefix.Everytime a new client is added a new set of views is manually created using a standard view set , which is just changed each time to reflect the clients unique information . This is usually done using a Find and Replace in SQL Server Management Studio ( SSMS ) What I have so far ? I have created a Winform app that captures the unique information and puts them into variables . These variables are then put into the the standard script that is used to create the views.ProblemMy script contains SMSS statements are not native SQL statements , this causes my program to error and break in its submission to the database.The statement in question is the GOkey word used to run batches by SMSS.What I have tried so far ? I have encapsulated the whole script using String Literal and have inserted a new line before and after the GO statements as suggested in another question . but it did n't seem to work.What I am trying now ? Using REGEX to split the script up at every 'GO ' occurrence . This is n't working either . QuestionIs there a better solution to this problem or a fix for my solution ? CodeError Message { `` Incorrect syntax near 'ANSI_NULLS'.\r\nIncorrect syntax near 'QUOTED_IDENTIFIER'.\r\nIncorrect syntax near ' ) '.\r\nIncorrect syntax near 'ANSI_NULLS'.\r\nIncorrect syntax near 'QUOTED_IDENTIFIER'.\r\nIncorrect syntax near ' ) '.\r\n'CREATE VIEW ' must be the first statement in a query batch.\r\nIncorrect syntax near ' ) '.\r\nIncorrect syntax near ' ) '.\r\nIncorrect syntax near ' ) '.\r\nIncorrect syntax near 'ANSI_NULLS'.\r\nIncorrect syntax near 'ANSI_NULLS'.\r\nIncorrect syntax near the keyword 'AS'.\r\nIncorrect syntax near the keyword 'AS'.\r\nIncorrect syntax near the keyword 'AS'.\r\nIncorrect syntax near the keyword 'AS'.\r\nIncorrect syntax near the keyword 'AS'.\r\nIncorrect syntax near the keyword 'AS'.\r\nIncorrect syntax near 'ANSI_NULLS'.\r\nIncorrect syntax near ' ) '.\r\nIncorrect syntax near 'ANSI_NULLS'.\r\nIncorrect syntax near 'ANSI_NULLS'.\r\nIncorrect syntax near 'ANSI_NULLS'.\r\nIncorrect syntax near the keyword 'AS'.\r\nIncorrect syntax near the keyword 'AS'.\r\nIncorrect syntax near 'ANSI_NULLS'.\r\nIncorrect syntax near ' ) '.\r\nIncorrect syntax near 'ANSI_NULLS'.\r\nIncorrect syntax near ' ) '.\r\nIncorrect syntax near 'ANSI_NULLS'.\r\nIncorrect syntax near 'ANSI_NULLS'.\r\nIncorrect syntax near 'ANSI_NULLS'.\r\nIncorrect syntax near ' ) '.\r\nIncorrect syntax near 'ANSI_NULLS'.\r\nIncorrect syntax near the keyword 'AS'.\r\nIncorrect syntax near the keyword 'AS'.\r\nIncorrect syntax near 'ANSI_NULLS'.\r\nIncorrect syntax near 'ANSI_NULLS'.\r\nIncorrect syntax near 'ANSI_NULLS'.\r\nIncorrect syntax near 'ANSI_NULLS'.\r\nIncorrect syntax near ' ) '.\r\nIncorrect syntax near 'ANSI_NULLS'.\r\nIncorrect syntax near 'ANSI_NULLS'.\r\nIncorrect syntax near the keyword 'AS'.\r\nIncorrect syntax near the keyword 'LIKE'.\r\nIncorrect syntax near 'ANSI_NULLS ' . `` } My Script /****** Object : View [ dbo ] . [ TIDEreportEmails ] Script Date : 23/02/2015 12:43:36 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE VIEW [ dbo ] . [ TIDEreportEmails ] AS SELECT EmailID , EmailContent , EmailSubject , EmailTo , EmailFrom , UserID , ObjectValueID , EmailSent , EmailCreated , EmailRead , EmailFromName , EmailType , EmailFailed , CASE WHEN emailread IS NULL THEN 'Not Read ' ELSE 'Read ' END AS EmailStatus FROM DEReportingClient2DB.dbo.Emails AS Emails_1 WHERE ( UserID IN ( SELECT UserID FROM DEReportingClient2DB.dbo.Users WHERE ( ClientID = 195 ) ) ) GO /****** Object : View [ dbo ] . [ TIDEunreadEmails ] Script Date : 23/02/2015 12:43:36 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE VIEW [ dbo ] . [ TIDEunreadEmails ] AS SELECT COUNT ( * ) AS UnreadEmails , UserID FROM dbo.TIDEreportEmails WHERE ( EmailRead IS NULL ) GROUP BY UserID <code> string connectionString = fmDbSelect ( ) ; using ( SqlConnection connection = new SqlConnection ( connectionString ) ) { using ( SqlCommand command = new SqlCommand ( ) ) { command.Connection = connection ; connection.Open ( ) ; var scripts = Regex.Split ( sql , @ '' ^\w+GO $ '' , RegexOptions.Multiline ) ; foreach ( var splitScript in scripts ) { command.CommandText = splitScript ; command.ExecuteNonQuery ( ) ; } } } | How to Dynamically Create Views ? |
C_sharp : I 'm using structure map with the AspNet Core 1.0 RTM . It appears they have removed using the FromServices attribute on properties . This breaks the code below because I am now unable to inject the ClaimsPrincipal . I 'm not sure how to get the DI system to pickup this property . Do I need to create a custom InputFormatter or something else . That seems like a lot of work to get this working again.Startup.csModel.csTestController.cs <code> public class Startup { public IServiceProvider ConfigureServices ( IServiceCollection services ) { var container = new Container ( ) ; container.Configure ( i = > { i.For < IHttpContextAccessor > ( ) .Use ( new HttpContextAccessor ( ) ) ; i.For < ClaimsPrincipal > ( ) .Use ( x = > x.GetInstance < IHttpContextAccessor > ( ) .HttpContext.User ) ; } ) ; container.Populate ( services ) ; return container.GetInstance < IServiceProvider > ( ) ; } } public class Model { // [ FromServices ] < -- worked in RC1 public ClaimsPrincipal Principal { get ; set ; } public string Value = > Principal.Identity.Name ; } public class TestController : Controller { public IActionResult Test ( Model model ) { return Ok ( ) ; } } | Asp.Net Core RC1 - > RTM DI changes - Removed FromServices |
C_sharp : I 'm currently working on an application that combines many streams of data through equations . What I 'd like to be able to do is something like : Where result updates whenever any of the streams update . At the moment the only way I can express this in Rx is as : Which is n't nearly as clear.My current idea is as follows : The problem is that CombineLatest returns an IObservable < double > instead of an ArithmeticStream.Two possible questions : How can I transparently convert an IObservable < double > into an ArithmeticStream ? Is there an alternative route that will get me the result I want ? <code> var result = ( stream1 + stream2 ) / stream3 + stream4 * 2 ; var result = stream1.CombineLatest ( stream2 , ( x , y ) = > x+y ) .CombineLatest ( stream3 , ( x , y ) = > x / y ) .CombineLatest ( stream4 , ( x , y ) = > x + y*2 ) ; Public class ArithmeticStream : IObservable < double > { public static ArithmeticStream operator + ( ArithmeticStream xx , ArithmeticStream yy ) { return Observable.CombineLatest ( xx , yy , ( x , y ) = > x + y ) ; } ... } | Stream Arithmetic with Reactive Extensions |
C_sharp : I have a List of type string in a .NET 3.5 project . The list has thousands of strings in it , but for the sake of brevity we 're going to say that it just has 5 strings in it.Assume that the list is sorted ( as you can tell above ) . What I need is a LINQ query that will remove all strings that are not duplicates . So the result would leave me with a list that only contains the two `` Coconut '' strings . Is this possible to do with a LINQ query ? If it is not then I 'll have to resort to some complex for loops , which I can do , but I did n't want to unless I had to . <code> List < string > lstStr = new List < string > ( ) { `` Apple '' , `` Banana '' , `` Coconut '' , `` Coconut '' , `` Orange '' } ; | Query a list for only duplicates |
C_sharp : I have subscribed various event in OnNavigatedTo like I have n't unsubscribed this event . Does it cause any memory issue when this page is not needed ? ? <code> protected override void OnNavigatedTo ( NavigationEventArgs e ) { Loaded += Screen_Loaded ; } | Do I need to unsubscribe from an event in a c # metro application ? |
C_sharp : I am trying to pull multiple elements out of an XML documents and their children but I can not find a useful example anywhere ... MSDN is very vague . This is c # in .NetI am creating this XML dynamically already and transferring it to a string . I have been trying to use XmlNode with a NodeList to go through each file in a foreach section but It is not working properly.Here is some sample XML : I need to pull each of the full paths < result > <code> < searchdoc > < results > < result no = `` 1 '' > < url > a.com < /url > < lastmodified > 1/1/1 < /lastmodified > < description > desc1 < /description > < title > title1 < /title > < /result > < result no = `` 2 '' > < url > b.com < /url > < lastmodified > 2/2/2/ < /lastmodified > < description > desc2 < /description > < title > title2 < /title > < /result > < /results > < /searchdoc > | Can I get a specific example of XML in c # |
C_sharp : EDIT : The bounty 's expired , but if the community would like to award it to someone , then I choose Raful Chizkiyahu.I have a memory leak in one of my C # Winforms programs , and I 'd like to graph its memory usage over time to get a better understanding of what might be causing the leak . Problem is , none of the usual memory diagnostic commands match up with what the Task Manager is claiming as its consumed memory for that process . I assumed this was perhaps due to the app using unsafe/unmanaged code not being included in the total.So to try and drill deeper , I created a new Winforms app , very simple , with just a timer to report the memory usage in realtime . I use 5 labels , each with various functions ( mostly found from here ) : Environment.WorkingSet , GC.GetTotalMemory ( false ) , GC.GetTotalMemory ( true ) , Process.GetCurrentProcess ( ) .PrivateMemorySize64 and Process.GetCurrentProcess ( ) .WorkingSet64.Surprisingly ( or maybe not so , sigh ) , I still ca n't get any of these five numbers to match up with the Windows 10 Task Manager . Here 's a screenshot : So what I 'm basically looking for is that 5.1MB number . How do I sneakily extract that hidden number from the .NET framework ? Here 's the code I have in the Timer tick function : As might be evident , I tried with and without the Refresh ( ) command to no avail.EDIT : The bounty 's expired , but if the community would like to award it to someone , then I choose Raful Chizkiyahu . <code> private void timer1_Tick ( object sender , EventArgs e ) { //Refresh ( ) ; label1.Text = `` Environment.WorkingSet : `` + Environment.WorkingSet ; label2.Text = `` GC.GetTotalMemory ( false ) : `` + GC.GetTotalMemory ( false ) ; label3.Text = `` GC.GetTotalMemory ( true ) : `` + GC.GetTotalMemory ( true ) ; Process proc = Process.GetCurrentProcess ( ) ; label4.Text = `` proc.PrivateMemorySize64 : `` + proc.PrivateMemorySize64 ; label5.Text = `` proc.WorkingSet64 : `` + proc.WorkingSet64 ; proc.Dispose ( ) ; } | Contradictory reporting of total Process memory usage in C # Winforms app |
C_sharp : I 'd like to know how should I do to test simple C # expressions 1 ) in Visual Studio and 2 ) not in debug , in design mode Say , I want to verify what will return this codeOr I obtained in the immediate window the following message : <code> ? DateTime.ParseExact ( `` 2016 '' , `` yyyy '' ) int i ; int.TryParse ( `` x55 '' , out i ) ; ? i ? DateTime.ParseExact ( `` 2016 '' , `` yyyy '' ) The expression can not be evaluated while in design mode . | Test simple c # code expressions in Visual Studio |
C_sharp : If I execute the code below , OutOfMemoryException occurs at either the lineor the linewhen the inner for statement executed about 1000 times.However , I do n't know why OutOfMemoryException occurs . I think I have written enough using to dispose Bitmap objects . Where does the memory leak occurs ? EDIT : OK. Maybe it 's because Parallel.ForEach spawns tasks before other tasks ended , so that more and more tasks are started but Bitmaps were not GCed since the tasks were not ended . Well , if this is the case , how to fix it to avoid OutofMemoryException ? I am not sure if this is the case yet though ... <code> using ( Bitmap bitmap1 = new Bitmap ( FrameToFilePath ( interval.Start - 1 ) ) ) using ( Bitmap bitmap2 = new Bitmap ( FrameToFilePath ( interval.End + 1 ) ) ) class Program { static void Main ( string [ ] args ) { // Some code to initialize List < Interval > intervals Parallel.ForEach ( intervals , interval = > { using ( Bitmap bitmap1 = new Bitmap ( FrameToFilePath ( interval.Start - 1 ) ) ) using ( Bitmap bitmap2 = new Bitmap ( FrameToFilePath ( interval.End + 1 ) ) ) { for ( int i = interval.Start ; i < = interval.End ; i++ ) { ColorMatrix colorMatrix = new ColorMatrix ( ) ; // Identity matrix colorMatrix.Matrix33 = ( i - interval.Start + 1F ) / ( interval.Span + 1F ) ; // Alpha using ( ImageAttributes imageAttributes = new ImageAttributes ( ) ) using ( Bitmap intermediate = new Bitmap ( bitmap1.Width , bitmap1.Height , PixelFormat.Format32bppArgb ) ) using ( Graphics graphics = Graphics.FromImage ( intermediate ) ) { imageAttributes.SetColorMatrix ( colorMatrix , ColorMatrixFlag.Default , ColorAdjustType.Bitmap ) ; graphics.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver ; graphics.DrawImage ( bitmap1 , 0 , 0 ) ; graphics.DrawImage ( bitmap2 , new Rectangle ( 0 , 0 , intermediate.Width , intermediate.Height ) , 0 , 0 , bitmap2.Width , bitmap2.Height , GraphicsUnit.Pixel , imageAttributes ) ; intermediate.Save ( FrameToFilePath ( i ) , ImageFormat.Png ) ; } } } } ) ; } static string FrameToFilePath ( int frame ) { return string.Format ( @ '' C : \ ( some path ) \frames\frame- { 0:00000 } .png '' , frame ) ; } } class Interval { public int Start { get ; set ; } public int End { get ; set ; } public int Span { get { return End - Start + 1 ; } } } | C # Bitmap - Can not find how to remove OutOfMemoryException |
C_sharp : I am writing some unit test for an ApiController . I continue to get multiple System.MissingMethodException exceptions for methods in the System.Web.Http namespace . Message : System.MissingMethodException : Method not found : 'System.Net.Http.HttpRequestMessage System.Web.Http.ApiController.get_Request ( ) ' . Message : System.MissingMethodException : Method not found : 'System.Threading.Tasks.Task ` 1 System.Web.Http.IHttpActionResult.ExecuteAsync ( System.Threading.CancellationToken ) '.The test project compiles just fine , has the correct using statements , package references , and bindings . However , as soon as it tries to run , one of the above exceptions are thrown ( whichever is first encountered , depending on how the code is structured ) . It may also be worth noting that when System.Web.Http methods are not used , the test project runs just fine.I was hoping this question had my answer , but I can not find any discrepancies . I have uninstalled/reinstalled multiple times . Verified both projects use the same version ( 5.2.7.0 ) . Verified that version is being used via viewing the Modules during debug . And verified that the reference path for both projects point to the correct nuget packages folder : ( ... \Main\src\packages\Microsoft.AspNet.WebApi.Core.5.2.7\lib\net45\System.Web.Http.dll ) Below is the package and binding info , if anything else is needed please let me know . I 've already wasted a couple days on this , any help would be greatly appreciated.Main Project - packages.configMain Project - web.config bindingsTest Project - packages.configTest Project - app.config bindingsEdit - adding project refs and modules screen shotMain Project - csproj referencesTest Project - csproj referencesScreenshot of Modules window during debug , showing loaded assembly <code> < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < packages > < package id= '' AutoMapper '' version= '' 8.1.0 '' targetFramework= '' net461 '' / > < package id= '' EntityFramework '' version= '' 6.1.3 '' targetFramework= '' net461 '' / > < package id= '' log4net '' version= '' 2.0.8 '' targetFramework= '' net461 '' / > < package id= '' Microsoft.AspNet.OData '' version= '' 7.1.0 '' targetFramework= '' net461 '' / > < package id= '' Microsoft.AspNet.WebApi '' version= '' 5.2.7 '' targetFramework= '' net461 '' / > < package id= '' Microsoft.AspNet.WebApi.Client '' version= '' 5.2.7 '' targetFramework= '' net461 '' / > < package id= '' Microsoft.AspNet.WebApi.Core '' version= '' 5.2.7 '' targetFramework= '' net461 '' / > < package id= '' Microsoft.AspNet.WebApi.WebHost '' version= '' 5.2.7 '' targetFramework= '' net461 '' / > < package id= '' Microsoft.Extensions.DependencyInjection '' version= '' 1.0.0 '' targetFramework= '' net461 '' / > < package id= '' Microsoft.Extensions.DependencyInjection.Abstractions '' version= '' 1.0.0 '' targetFramework= '' net461 '' / > < package id= '' Microsoft.OData.Core '' version= '' 7.5.0 '' targetFramework= '' net461 '' / > < package id= '' Microsoft.OData.Edm '' version= '' 7.5.0 '' targetFramework= '' net461 '' / > < package id= '' Microsoft.Spatial '' version= '' 7.5.0 '' targetFramework= '' net461 '' / > < package id= '' Newtonsoft.Json '' version= '' 11.0.2 '' targetFramework= '' net461 '' / > < package id= '' NLog '' version= '' 4.2.3 '' targetFramework= '' net461 '' / > < package id= '' System.Collections '' version= '' 4.0.11 '' targetFramework= '' net461 '' / > < package id= '' System.Collections.Concurrent '' version= '' 4.0.12 '' targetFramework= '' net461 '' / > < package id= '' System.ComponentModel '' version= '' 4.0.1 '' targetFramework= '' net461 '' / > < package id= '' System.Diagnostics.Debug '' version= '' 4.0.11 '' targetFramework= '' net461 '' / > < package id= '' System.Globalization '' version= '' 4.0.11 '' targetFramework= '' net461 '' / > < package id= '' System.Linq '' version= '' 4.1.0 '' targetFramework= '' net461 '' / > < package id= '' System.Linq.Expressions '' version= '' 4.1.0 '' targetFramework= '' net461 '' / > < package id= '' System.Reflection '' version= '' 4.1.0 '' targetFramework= '' net461 '' / > < package id= '' System.Resources.ResourceManager '' version= '' 4.0.1 '' targetFramework= '' net461 '' / > < package id= '' System.Runtime.CompilerServices.Unsafe '' version= '' 4.5.2 '' targetFramework= '' net461 '' / > < package id= '' System.Runtime.Extensions '' version= '' 4.1.0 '' targetFramework= '' net461 '' / > < package id= '' System.Threading '' version= '' 4.0.11 '' targetFramework= '' net461 '' / > < package id= '' System.Threading.Tasks '' version= '' 4.0.11 '' targetFramework= '' net461 '' / > < package id= '' Unity '' version= '' 5.10.1 '' targetFramework= '' net461 '' / > < /packages > < runtime > < assemblyBinding xmlns= '' urn : schemas-microsoft-com : asm.v1 '' > < dependentAssembly > < assemblyIdentity name= '' Newtonsoft.Json '' publicKeyToken= '' 30ad4fe6b2a6aeed '' / > < bindingRedirect oldVersion= '' 0.0.0.0-11.0.0.0 '' newVersion= '' 11.0.0.0 '' / > < /dependentAssembly > < dependentAssembly > < assemblyIdentity name= '' System.Net.Http.Formatting '' publicKeyToken= '' 31bf3856ad364e35 '' culture= '' neutral '' / > < bindingRedirect oldVersion= '' 0.0.0.0-5.2.7.0 '' newVersion= '' 5.2.7.0 '' / > < /dependentAssembly > < dependentAssembly > < assemblyIdentity name= '' System.Web.Http '' publicKeyToken= '' 31bf3856ad364e35 '' culture= '' neutral '' / > < bindingRedirect oldVersion= '' 0.0.0.0-5.2.7.0 '' newVersion= '' 5.2.7.0 '' / > < /dependentAssembly > < /assemblyBinding > < /runtime > < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < packages > < package id= '' AutoMapper '' version= '' 8.1.0 '' targetFramework= '' net461 '' / > < package id= '' Castle.Core '' version= '' 4.3.1 '' targetFramework= '' net461 '' / > < package id= '' EntityFramework '' version= '' 6.1.3 '' targetFramework= '' net461 '' / > < package id= '' log4net '' version= '' 2.0.8 '' targetFramework= '' net461 '' / > < package id= '' Microsoft.AspNet.OData '' version= '' 7.1.0 '' targetFramework= '' net461 '' / > < package id= '' Microsoft.AspNet.WebApi.Client '' version= '' 5.2.7 '' targetFramework= '' net461 '' / > < package id= '' Microsoft.AspNet.WebApi.Core '' version= '' 5.2.7 '' targetFramework= '' net461 '' / > < package id= '' Microsoft.Extensions.DependencyInjection '' version= '' 1.0.0 '' targetFramework= '' net461 '' / > < package id= '' Microsoft.Extensions.DependencyInjection.Abstractions '' version= '' 1.0.0 '' targetFramework= '' net461 '' / > < package id= '' Microsoft.OData.Core '' version= '' 7.5.0 '' targetFramework= '' net461 '' / > < package id= '' Microsoft.OData.Edm '' version= '' 7.5.0 '' targetFramework= '' net461 '' / > < package id= '' Microsoft.Spatial '' version= '' 7.5.0 '' targetFramework= '' net461 '' / > < package id= '' Moq '' version= '' 4.10.1 '' targetFramework= '' net461 '' / > < package id= '' netDumbster '' version= '' 2.0.0.4 '' targetFramework= '' net461 '' / > < package id= '' Newtonsoft.Json '' version= '' 11.0.2 '' targetFramework= '' net461 '' / > < package id= '' NUnit '' version= '' 2.6.4 '' targetFramework= '' net461 '' / > < package id= '' NUnitTestAdapter '' version= '' 1.2 '' targetFramework= '' net461 '' / > < package id= '' System.Collections '' version= '' 4.0.11 '' targetFramework= '' net461 '' / > < package id= '' System.Collections.Concurrent '' version= '' 4.0.12 '' targetFramework= '' net461 '' / > < package id= '' System.ComponentModel '' version= '' 4.0.1 '' targetFramework= '' net461 '' / > < package id= '' System.Diagnostics.Debug '' version= '' 4.0.11 '' targetFramework= '' net461 '' / > < package id= '' System.Globalization '' version= '' 4.0.11 '' targetFramework= '' net461 '' / > < package id= '' System.Linq '' version= '' 4.1.0 '' targetFramework= '' net461 '' / > < package id= '' System.Linq.Expressions '' version= '' 4.1.0 '' targetFramework= '' net461 '' / > < package id= '' System.Reflection '' version= '' 4.1.0 '' targetFramework= '' net461 '' / > < package id= '' System.Resources.ResourceManager '' version= '' 4.0.1 '' targetFramework= '' net461 '' / > < package id= '' System.Runtime.CompilerServices.Unsafe '' version= '' 4.5.2 '' targetFramework= '' net461 '' / > < package id= '' System.Runtime.Extensions '' version= '' 4.1.0 '' targetFramework= '' net461 '' / > < package id= '' System.Threading '' version= '' 4.0.11 '' targetFramework= '' net461 '' / > < package id= '' System.Threading.Tasks '' version= '' 4.0.11 '' targetFramework= '' net461 '' / > < package id= '' System.Threading.Tasks.Extensions '' version= '' 4.5.1 '' targetFramework= '' net461 '' / > < /packages > < runtime > < assemblyBinding xmlns= '' urn : schemas-microsoft-com : asm.v1 '' > < dependentAssembly > < assemblyIdentity name= '' Newtonsoft.Json '' publicKeyToken= '' 30ad4fe6b2a6aeed '' culture= '' neutral '' / > < bindingRedirect oldVersion= '' 0.0.0.0-11.0.0.0 '' newVersion= '' 11.0.0.0 '' / > < /dependentAssembly > < dependentAssembly > < assemblyIdentity name= '' System.Web.Http '' publicKeyToken= '' 31bf3856ad364e35 '' culture= '' neutral '' / > < bindingRedirect oldVersion= '' 0.0.0.0-5.2.7.0 '' newVersion= '' 5.2.7.0 '' / > < /dependentAssembly > < dependentAssembly > < assemblyIdentity name= '' System.Net.Http.Formatting '' publicKeyToken= '' 31bf3856ad364e35 '' culture= '' neutral '' / > < bindingRedirect oldVersion= '' 0.0.0.0-5.2.7.0 '' newVersion= '' 5.2.7.0 '' / > < /dependentAssembly > < dependentAssembly > < assemblyIdentity name= '' System.Runtime.CompilerServices.Unsafe '' publicKeyToken= '' b03f5f7f11d50a3a '' culture= '' neutral '' / > < bindingRedirect oldVersion= '' 0.0.0.0-4.0.4.1 '' newVersion= '' 4.0.4.1 '' / > < /dependentAssembly > < /assemblyBinding > < /runtime > < ItemGroup > < Reference Include= '' AutoMapper , Version=8.1.0.0 , Culture=neutral , PublicKeyToken=be96cd2c38ef1005 , processorArchitecture=MSIL '' > < HintPath > ..\packages\AutoMapper.8.1.0\lib\net461\AutoMapper.dll < /HintPath > < /Reference > < Reference Include= '' log4net , Version=2.0.8.0 , Culture=neutral , PublicKeyToken=669e0ddf0bb1aa2a , processorArchitecture=MSIL '' > < HintPath > ..\packages\log4net.2.0.8\lib\net45-full\log4net.dll < /HintPath > < /Reference > < Reference Include= '' EntityFramework , Version=6.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 , processorArchitecture=MSIL '' > < HintPath > ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll < /HintPath > < /Reference > < Reference Include= '' EntityFramework.SqlServer , Version=6.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 , processorArchitecture=MSIL '' > < HintPath > ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.SqlServer.dll < /HintPath > < /Reference > < Reference Include= '' Microsoft.AspNet.OData , Version=7.1.0.21120 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 , processorArchitecture=MSIL '' > < HintPath > ..\packages\Microsoft.AspNet.OData.7.1.0\lib\net45\Microsoft.AspNet.OData.dll < /HintPath > < /Reference > < Reference Include= '' Microsoft.CSharp '' / > < Reference Include= '' Microsoft.Extensions.DependencyInjection , Version=1.0.0.0 , Culture=neutral , PublicKeyToken=adb9793829ddae60 , processorArchitecture=MSIL '' > < HintPath > ..\packages\Microsoft.Extensions.DependencyInjection.1.0.0\lib\netstandard1.1\Microsoft.Extensions.DependencyInjection.dll < /HintPath > < /Reference > < Reference Include= '' Microsoft.Extensions.DependencyInjection.Abstractions , Version=1.0.0.0 , Culture=neutral , PublicKeyToken=adb9793829ddae60 , processorArchitecture=MSIL '' > < HintPath > ..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.1.0.0\lib\netstandard1.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll < /HintPath > < /Reference > < Reference Include= '' Microsoft.OData.Core , Version=7.5.0.20627 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 , processorArchitecture=MSIL '' > < HintPath > ..\packages\Microsoft.OData.Core.7.5.0\lib\portable-net45+win8+wpa81\Microsoft.OData.Core.dll < /HintPath > < /Reference > < Reference Include= '' Microsoft.OData.Edm , Version=7.5.0.20627 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 , processorArchitecture=MSIL '' > < HintPath > ..\packages\Microsoft.OData.Edm.7.5.0\lib\portable-net45+win8+wpa81\Microsoft.OData.Edm.dll < /HintPath > < /Reference > < Reference Include= '' Microsoft.Spatial , Version=7.5.0.20627 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 , processorArchitecture=MSIL '' > < HintPath > ..\packages\Microsoft.Spatial.7.5.0\lib\portable-net45+win8+wpa81\Microsoft.Spatial.dll < /HintPath > < /Reference > < Reference Include= '' Newtonsoft.Json , Version=11.0.0.0 , Culture=neutral , PublicKeyToken=30ad4fe6b2a6aeed , processorArchitecture=MSIL '' > < HintPath > ..\packages\WellsFargo.Azure.ChannelSecure.3.0.0.12\lib\Newtonsoft.Json.dll < /HintPath > < /Reference > < Reference Include= '' NLog , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=5120e14c03d0593c , processorArchitecture=MSIL '' > < HintPath > ..\packages\WellsFargo.Azure.ChannelSecure.3.0.0.12\lib\NLog.dll < /HintPath > < /Reference > < Reference Include= '' SSORestIISModule , Version=3.0.0.9 , Culture=neutral , PublicKeyToken=f8c74029db907226 , processorArchitecture=MSIL '' > < HintPath > ..\packages\WellsFargo.Azure.ChannelSecure.3.0.0.12\lib\SSORestIISModule.dll < /HintPath > < /Reference > < Reference Include= '' System.Data.DataSetExtensions '' / > < Reference Include= '' System.IO.Compression '' / > < Reference Include= '' System.Net '' / > < Reference Include= '' System.Net.Http '' / > < Reference Include= '' System.Net.Http.Formatting , Version=5.2.7.0 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 , processorArchitecture=MSIL '' > < HintPath > ..\packages\Microsoft.AspNet.WebApi.Client.5.2.7\lib\net45\System.Net.Http.Formatting.dll < /HintPath > < /Reference > < Reference Include= '' System.Runtime.CompilerServices.Unsafe , Version=4.0.4.1 , Culture=neutral , PublicKeyToken=b03f5f7f11d50a3a , processorArchitecture=MSIL '' > < HintPath > ..\packages\System.Runtime.CompilerServices.Unsafe.4.5.2\lib\netstandard2.0\System.Runtime.CompilerServices.Unsafe.dll < /HintPath > < /Reference > < Reference Include= '' System.Runtime.Serialization '' / > < Reference Include= '' System.ServiceModel '' / > < Reference Include= '' System.Transactions '' / > < Reference Include= '' System.Web.DynamicData '' / > < Reference Include= '' System.Web.Entity '' / > < Reference Include= '' System.Web.ApplicationServices '' / > < Reference Include= '' System.ComponentModel.DataAnnotations '' / > < Reference Include= '' System '' / > < Reference Include= '' System.Data '' / > < Reference Include= '' System.Drawing '' / > < Reference Include= '' System.Web '' / > < Reference Include= '' System.Web.Extensions '' / > < Reference Include= '' System.Web.Http , Version=5.2.7.0 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 , processorArchitecture=MSIL '' > < HintPath > ..\packages\Microsoft.AspNet.WebApi.Core.5.2.7\lib\net45\System.Web.Http.dll < /HintPath > < /Reference > < Reference Include= '' System.Web.Http.WebHost , Version=5.2.7.0 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 , processorArchitecture=MSIL '' > < HintPath > ..\packages\Microsoft.AspNet.WebApi.WebHost.5.2.7\lib\net45\System.Web.Http.WebHost.dll < /HintPath > < /Reference > < Reference Include= '' System.Xml '' / > < Reference Include= '' System.Configuration '' / > < Reference Include= '' System.Web.Services '' / > < Reference Include= '' System.EnterpriseServices '' / > < Reference Include= '' System.Xml.Linq '' / > < Reference Include= '' Unity.Abstractions , Version=4.1.2.0 , Culture=neutral , PublicKeyToken=489b6accfaf20ef0 , processorArchitecture=MSIL '' > < HintPath > ..\packages\Unity.5.10.1\lib\net46\Unity.Abstractions.dll < /HintPath > < /Reference > < Reference Include= '' Unity.Container , Version=5.10.1.0 , Culture=neutral , PublicKeyToken=489b6accfaf20ef0 , processorArchitecture=MSIL '' > < HintPath > ..\packages\Unity.5.10.1\lib\net46\Unity.Container.dll < /HintPath > < /Reference > < /ItemGroup > < ItemGroup > < Reference Include= '' AutoMapper , Version=8.1.0.0 , Culture=neutral , PublicKeyToken=be96cd2c38ef1005 , processorArchitecture=MSIL '' > < HintPath > ..\packages\AutoMapper.8.1.0\lib\net461\AutoMapper.dll < /HintPath > < /Reference > < Reference Include= '' Castle.Core , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=407dd0808d44fbdc , processorArchitecture=MSIL '' > < HintPath > ..\packages\Castle.Core.4.3.1\lib\net45\Castle.Core.dll < /HintPath > < /Reference > < Reference Include= '' EntityFramework , Version=6.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 , processorArchitecture=MSIL '' > < HintPath > ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll < /HintPath > < /Reference > < Reference Include= '' EntityFramework.SqlServer , Version=6.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 , processorArchitecture=MSIL '' > < HintPath > ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.SqlServer.dll < /HintPath > < /Reference > < Reference Include= '' log4net , Version=2.0.8.0 , Culture=neutral , PublicKeyToken=669e0ddf0bb1aa2a , processorArchitecture=MSIL '' > < HintPath > ..\packages\log4net.2.0.8\lib\net45-full\log4net.dll < /HintPath > < /Reference > < Reference Include= '' Microsoft.AspNet.OData , Version=7.1.0.21120 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 , processorArchitecture=MSIL '' > < HintPath > ..\packages\Microsoft.AspNet.OData.7.1.0\lib\net45\Microsoft.AspNet.OData.dll < /HintPath > < /Reference > < Reference Include= '' Microsoft.Extensions.DependencyInjection , Version=1.0.0.0 , Culture=neutral , PublicKeyToken=adb9793829ddae60 , processorArchitecture=MSIL '' > < HintPath > ..\packages\Microsoft.Extensions.DependencyInjection.1.0.0\lib\netstandard1.1\Microsoft.Extensions.DependencyInjection.dll < /HintPath > < /Reference > < Reference Include= '' Microsoft.Extensions.DependencyInjection.Abstractions , Version=1.0.0.0 , Culture=neutral , PublicKeyToken=adb9793829ddae60 , processorArchitecture=MSIL '' > < HintPath > ..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.1.0.0\lib\netstandard1.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll < /HintPath > < /Reference > < Reference Include= '' Microsoft.OData.Core , Version=7.5.0.20627 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 , processorArchitecture=MSIL '' > < HintPath > ..\packages\Microsoft.OData.Core.7.5.0\lib\portable-net45+win8+wpa81\Microsoft.OData.Core.dll < /HintPath > < /Reference > < Reference Include= '' Microsoft.OData.Edm , Version=7.5.0.20627 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 , processorArchitecture=MSIL '' > < HintPath > ..\packages\Microsoft.OData.Edm.7.5.0\lib\portable-net45+win8+wpa81\Microsoft.OData.Edm.dll < /HintPath > < /Reference > < Reference Include= '' Microsoft.Spatial , Version=7.5.0.20627 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 , processorArchitecture=MSIL '' > < HintPath > ..\packages\Microsoft.Spatial.7.5.0\lib\portable-net45+win8+wpa81\Microsoft.Spatial.dll < /HintPath > < /Reference > < Reference Include= '' Moq , Version=4.10.0.0 , Culture=neutral , PublicKeyToken=69f491c39445e920 , processorArchitecture=MSIL '' > < HintPath > ..\packages\Moq.4.10.1\lib\net45\Moq.dll < /HintPath > < /Reference > < Reference Include= '' netDumbster , Version=2.0.0.4 , Culture=neutral , PublicKeyToken=4a1d8c974aa1bd1c , processorArchitecture=MSIL '' > < HintPath > ..\packages\netDumbster.2.0.0.4\lib\net461\netDumbster.dll < /HintPath > < /Reference > < Reference Include= '' Newtonsoft.Json , Version=11.0.0.0 , Culture=neutral , PublicKeyToken=30ad4fe6b2a6aeed , processorArchitecture=MSIL '' > < HintPath > ..\packages\Newtonsoft.Json.11.0.2\lib\net45\Newtonsoft.Json.dll < /HintPath > < /Reference > < Reference Include= '' nunit.core , Version=2.6.3.13283 , Culture=neutral , PublicKeyToken=96d09a1eb7f44a77 , processorArchitecture=MSIL '' > < HintPath > ..\packages\NUnitTestAdapter.1.2\lib\nunit.core.dll < /HintPath > < Private > False < /Private > < /Reference > < Reference Include= '' nunit.core.interfaces , Version=2.6.3.13283 , Culture=neutral , PublicKeyToken=96d09a1eb7f44a77 , processorArchitecture=MSIL '' > < HintPath > ..\packages\NUnitTestAdapter.1.2\lib\nunit.core.interfaces.dll < /HintPath > < Private > False < /Private > < /Reference > < Reference Include= '' nunit.framework , Version=2.6.4.14350 , Culture=neutral , PublicKeyToken=96d09a1eb7f44a77 , processorArchitecture=MSIL '' > < HintPath > ..\packages\NUnit.2.6.4\lib\nunit.framework.dll < /HintPath > < /Reference > < Reference Include= '' nunit.util , Version=2.6.3.13283 , Culture=neutral , PublicKeyToken=96d09a1eb7f44a77 , processorArchitecture=MSIL '' > < HintPath > ..\packages\NUnitTestAdapter.1.2\lib\nunit.util.dll < /HintPath > < Private > False < /Private > < /Reference > < Reference Include= '' NUnit.VisualStudio.TestAdapter , Version=1.2.0.0 , Culture=neutral , PublicKeyToken=4cb40d35494691ac , processorArchitecture=MSIL '' > < HintPath > ..\packages\NUnitTestAdapter.1.2\lib\NUnit.VisualStudio.TestAdapter.dll < /HintPath > < Private > False < /Private > < /Reference > < Reference Include= '' System '' / > < Reference Include= '' System.ComponentModel.DataAnnotations '' / > < Reference Include= '' System.Configuration '' / > < Reference Include= '' System.Core '' / > < Reference Include= '' System.Net.Http.Formatting , Version=5.2.7.0 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 , processorArchitecture=MSIL '' > < HintPath > ..\packages\Microsoft.AspNet.WebApi.Client.5.2.7\lib\net45\System.Net.Http.Formatting.dll < /HintPath > < /Reference > < Reference Include= '' System.Runtime.CompilerServices.Unsafe , Version=4.0.4.1 , Culture=neutral , PublicKeyToken=b03f5f7f11d50a3a , processorArchitecture=MSIL '' > < HintPath > ..\packages\System.Runtime.CompilerServices.Unsafe.4.5.2\lib\netstandard2.0\System.Runtime.CompilerServices.Unsafe.dll < /HintPath > < /Reference > < Reference Include= '' System.Threading.Tasks.Extensions , Version=4.2.0.0 , Culture=neutral , PublicKeyToken=cc7b13ffcd2ddd51 , processorArchitecture=MSIL '' > < HintPath > ..\packages\System.Threading.Tasks.Extensions.4.5.1\lib\netstandard2.0\System.Threading.Tasks.Extensions.dll < /HintPath > < /Reference > < Reference Include= '' System.Web.Http , Version=5.2.7.0 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 , processorArchitecture=MSIL '' > < HintPath > ..\packages\Microsoft.AspNet.WebApi.Core.5.2.7\lib\net45\System.Web.Http.dll < /HintPath > < /Reference > < Reference Include= '' System.Xml.Linq '' / > < Reference Include= '' System.Data.DataSetExtensions '' / > < Reference Include= '' Microsoft.CSharp '' / > < Reference Include= '' System.Data '' / > < Reference Include= '' System.Net.Http '' / > < Reference Include= '' System.Xml '' / > < /ItemGroup > | System.Web.Http methods missing in Nunit test project |
C_sharp : I encountered a weird problem : given such string { `` text '' : '' s '' , '' cursorPosition '' :189 , '' dataSource '' : '' json_northwind '' , which is not a correct json , it still gets succesfully parsed.this is the class : Here is test that surprisingly succeeds : does the library have some loosened parsing rules or maybe this is a bug ? I am library version 9.0.1 <code> public class CompletionDataRequest { public CompletionDataRequest ( string text , int cursorPosition , string dataSource , string project ) { Text = text ; CursorPosition = cursorPosition ; DataSource = dataSource ; Project = project ; } public string Text { get ; } public int CursorPosition { get ; } public string DataSource { get ; } public string Project { get ; } } var s = @ '' { `` '' text '' '' : '' '' s '' '' , '' '' cursorPosition '' '' :189 , '' '' dataSource '' '' : '' '' json_northwind '' '' , '' ; var request = JsonConvert.DeserializeObject < CompletionDataRequest > ( s ) ; request.Text.Should ( ) .Be ( `` s '' ) ; request.CursorPosition.Should ( ) .Be ( 189 ) ; request.DataSource.Should ( ) .Be ( `` json_northwind '' ) ; request.Project.Should ( ) .BeNull ( ) ; | Newtonsoft.Json parses incorrect json |
C_sharp : In a project I 'm currently working on , I am starting an external process . However , the external process is the EXE of a complex program which loads current-user information from a user folder . The desktop shortcut for the program resolves the matter by setting the `` Target : '' parameter to X : \exepath\prgm.exe and setting the `` Start In '' parameter to the user 's path , X : \exepath\users\username.I currently launch the process like this : However , when the process is started , the program it launches ends up looking for all resources in the WorkingDirectory instead of pulling user content from that folder and all other content from the directory the EXE resides in . This suggests that Working Directory and the system shortcut `` Start In : '' parameter behave differently.Is there any way to mimic that behavior with a C # Process ? Alternatively , is it possible to create a shortcut in C # , which I could then start with my Process invocation ? Please let me know if more info would be helpful.EDIT - After some more trial and error , I decided to use WSH to create a shortcut and run it . WSH uses the name WorkingDirectory for the value of the `` Start In : '' parameter . It behaves identically under the hood as the execution of the process in my code above . I am still getting the error . <code> Process p = new Process ( ) ; p.StartInfo = new ProcessStartInfo ( `` X : \exepath\prgm.exe '' ) ; p.StartInfo.WorkingDirectory = `` X : \exepath\users\username '' ; p.Start ( ) ; while ( ! p.HasExited ) { } | More than one important path for .NET Process |
C_sharp : I have the following line of code : Which results in an IOException being thrown . Additional information : The process can not access the file ' C : \Users\Username\AppData\Local\Temp\dgl5fb1i.err ' because it is being used by another process.However , this is a part of a large program that consumes more than 8GB of RAM . On a system with 16GB of RAM , this exception is not thrown . The code that is dynamically compiled compiles well and runs . The program runs without any errors on a system with sufficient RAM . The program is compiled for x64 . Note that I am not getting OutOfMemoryException or any indication that the program is out of memory . In the Task Manager the memory usage almost reaches the top before the IOException is thrown.What could be causing this behavior and can anyone suggest a solution ? EDITI modified the application to use substantially less memory . The error persists even though the application has enough available memory . The issue still occurs only on one machine.This could be related to the following post : Prevent CompileAssemblyFromSource from generate temp files with duplicate file name . <code> CSharpCodeProvider c = new CSharpCodeProvider ( ) ; CompilerParameters cp = new CompilerParameters ( ) ; cp.ReferencedAssemblies.Add ( `` system.dll '' ) ; cp.CompilerOptions = `` /t : library '' ; cp.GenerateInMemory = true ; CompilerResults cr = c.CompileAssemblyFromSource ( cp , sb.ToString ( ) ) ; | IOException when dynamically compiling code |
C_sharp : What happens exactly during string initialization ? Is it going to make a call to any of these constructors ? <code> string s = `` Hello World ! `` ; public String ( char* value ) ; public String ( char [ ] value ) ; | What happens during string initialization ? |
C_sharp : C # has a conditional operator and IF statements and I suspected that the conditional operator would be just syntactic sugar . So at compile time it would have a the same as an IF operation . However they do not ( see below ) , they do have different IL . Trying to wrap my head around it and the assumption I have is that this is a performance optimisation that the conditional operator gets because it 's limited scope.Would like to know if my assumption is correct or not and maybe if there is more to this ? Also in the IF 's IL there is some checks ( L_000c , L_000d , L_000f ) around int values which I ca n't figure out the meaning . This is what has lead me to think this is a more robust solution , at the cost of performance because of IF greater scope.Code for IFCode for conditional operator ( I realise differences , but no matter how I change it - assign to variable etc ... it makes very little difference ) IL for IFIL for Conditional <code> var result = `` '' ; if ( Environment.Is64BitOperatingSystem ) { result = `` Yes '' ; } else { result = `` No '' ; } Console.WriteLine ( result ) ; Console.WriteLine ( `` Is the OS x64 ? { 0 } '' , Environment.Is64BitOperatingSystem ? `` Yes '' : `` No '' ) ; L_0001 : ldstr `` '' L_0006 : stloc.0 L_0007 : call bool [ mscorlib ] System.Environment : :get_Is64BitOperatingSystem ( ) L_000c : ldc.i4.0 L_000d : ceq L_000f : stloc.2 L_0010 : ldloc.2 L_0011 : brtrue.s L_001dL_0013 : nop L_0014 : ldstr `` Yes '' L_0019 : stloc.0 L_001a : nop L_001b : br.s L_0025L_001d : nop L_001e : ldstr `` No '' L_0023 : stloc.0 L_0024 : nop L_0025 : ldloc.0 L_0026 : call void [ mscorlib ] System.Console : :WriteLine ( string ) L_002c : ldstr `` Is the OS x64 ? { 0 } '' L_0031 : call bool [ mscorlib ] System.Environment : :get_Is64BitOperatingSystem ( ) L_0036 : brtrue.s L_003fL_0038 : ldstr `` No '' L_003d : br.s L_0044L_003f : ldstr `` Yes '' L_0044 : call void [ mscorlib ] System.Console : :WriteLine ( string , object ) | Why such a difference in IL between IF and the conditional operator ? |
C_sharp : The two methods above seems to behave equally , both when passing null reference or boxed T value . However , the generated MSIL code is a bit different : vsAs you may see , the o is T ? expression actually performs type check for Nullable < T > type , despite the fact that nullable types are specially handled by CLR so that C # represents boxed T ? value as null reference ( if T ? has no value ) or boxed T value . It seems impossible to get box of Nullable < T > type in pure C # or maybe even in C++/CLI ( since runtime handles box opcode to support this `` T ? = > T box / null '' boxing ) .Am I missing something or o is T ? is practically equivalent to o is T in C # ? <code> class C < T > where T : struct { bool M1 ( object o ) = > o is T ; bool M2 ( object o ) = > o is T ? ; } .method private hidebysig instance bool M1 ( object o ) cil managed { .maxstack 8 IL_0000 : ldarg.1 IL_0001 : isinst ! T IL_0006 : ldnull IL_0007 : cgt.un IL_0009 : ret } .method private hidebysig instance bool M2 ( object o ) cil managed { .maxstack 8 IL_0000 : ldarg.1 IL_0001 : isinst valuetype [ mscorlib ] System.Nullable ` 1 < ! T > IL_0006 : ldnull IL_0007 : cgt.un IL_0009 : ret } | Is there a difference between ` x is int ? ` and ` x is int ` in C # ? |
C_sharp : I found a piece of code of the following form : In other parts of the code , I want to get the same lightweight CustomerContact object , only not from the Invoice , but from the Customer itself . So the obvious thing to do would be to have : and then change the Expression taking Invoice as input to refer to this method , i.e . something like this : What 's the correct syntax for this ? <code> public static Expression < Func < Invoice , CustomerContact > > GetCustomerContact ( ) { return i = > new CustomerContact { FirstName = i.Customer.FirstName , LastName = i.Customer.LastName , Email = i.Customer.Email , TelMobile = i.Customer.TelMobile , } ; } public static Expression < Func < Customer , CustomerContact > > GetCustomerContact ( ) { return c = > new CustomerContact { FirstName = c.FirstName , LastName = c.LastName , Email = c.Email , TelMobile = c.TelMobile , } ; } public static Expression < Func < Invoice , CustomerContact > > GetCustomerContact ( ) { return i = > GetCustomerContact ( i.Customer ) ; // does n't compile } | Syntax to refer a method returning an Expression to another method ? |
C_sharp : Is it possible to use the return value of a function instead of a specific value as optional parameter in a function ? For example instead of : I want something like <code> public void ExampleMethod ( int a , int b , int c=10 ) { } private int ChangeC ( int a , int b ) { return a+b ; } public void ExampleMethod ( int a , int b , int c=ChangeC ( a , b ) ) { } | Use a function to define an optional parameter |
C_sharp : I have this code that creates a request and reads the data but it is always emptyWhen i try to access the link from browser i get this json : what am I missing ? <code> static string uri = `` http : //yiimp.ccminer.org/api/wallet ? address=DshDF3zmCX9PUhafTAzxyQidwgdfLYJkBrd '' ; static void Main ( string [ ] args ) { HttpWebRequest request = ( HttpWebRequest ) WebRequest.Create ( uri ) ; request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip ; HttpWebResponse response = ( HttpWebResponse ) request.GetResponse ( ) ; // Get the stream associated with the response . Stream receiveStream = response.GetResponseStream ( ) ; // Pipes the stream to a higher level stream reader with the required encoding format . StreamReader readStream = new StreamReader ( receiveStream , Encoding.UTF8 ) ; Console.WriteLine ( `` Response stream received . `` ) ; Console.WriteLine ( readStream.ReadToEnd ( ) ) ; response.Close ( ) ; readStream.Close ( ) ; } { `` currency '' : `` DCR '' , `` unsold '' : 0.030825917365192 , `` balance '' : 0.02007306 , `` unpaid '' : 0.05089898 , `` paid24h '' : 0.05796425 , `` total '' : 0.10886323 } | Reading data from url returns empty value |
C_sharp : Hi i am new in c # and i want to ask how to write this code more pretyAll it do just copy all properties except id . Can i write it shortly ? Thanx and sorry for my bad english <code> public void Update ( Product pr ) { Product prod = GeProductById ( pr.ProductID ) ; prod.Name = pr.Name ; prod.Count = pr.Count ; prod.InputPrice = pr.InputPrice ; prod.InputDate = pr.InputDate ; prod.OutPrice = pr.OutPrice ; prod.InputPriceByCurrency = pr.InputPriceByCurrency ; prod.InputPriceCurrency = pr.InputPriceCurrency ; prod.ComeOwner = pr.ComeOwner ; prod.GroupID = pr.GroupID ; prod.Discount = pr.Discount ; _context.SubmitChanges ( ) ; } | How to write it pretty ? |
C_sharp : I wrote this piece of code : and the reflector gives me : Obviously , this is not what the original code says . The line ( this._queue = new Queue < int > ( 10 ) ) ; will alway return a new Queue < int > ( 10 ) instead of _queue when it is not null.Is this a bug in the .NET Reflector or am I missing something ? The program seems to behave correctly ... EDIT - > See my answer <code> private Queue < int > EnsureQueue ( ) { return _queue ? ? ( _queue = new Queue < int > ( 10 ) ) ; } private Queue < int > EnsureQueue ( ) { if ( this._queue == null ) { } return ( this._queue = new Queue < int > ( 10 ) ) ; } | Is the .NET Reflector unable to reflect over the null-coalescing operator correctly ? |
C_sharp : In `` Getting Started with Asynchronous Programming in .NET '' by Filip Ekberg , in the `` Asynchronous Programming Deep Dive/Working with Attached and Detached Tasks '' chapter , he says that by using the service value inside the async anonymous method , it introduces a closure and unnecessary allocation : Next , he says it 's better to pass services as a parameter to the action delegate of the StartNew method which avoids unnecessary allocations by avoiding a closure : My question is : What is the allocation the author says it 's being saved by passing the services as parameter ? To make it easier to investigate , I took a much simpler example and put it in the sharplab.io : Not passing the parameter : which compiles to : There are two allocations , one for the generated class and one for the Func < int > delegate.Passing the parameter : which compiles to : Here , there are still two allocations , one for the generated class ( note there 's a static field in the class which creates an instance of the class ) and another allocation for the Func < int > delegate.As far as I can see , in both cases the compiler generates a class and there are two allocations.The only difference I can see is that in the first case , the generated class has a member : This does increase the allocation size , because the generated class occupies more memory than in the 2nd case . Did I understand it correctly , is this what the author refers to ? <code> using System ; public class C { public void M ( ) { var i = 1 ; Func < int > f = ( ) = > i + 1 ; f ( ) ; } } public class C { [ CompilerGenerated ] private sealed class < > c__DisplayClass0_0 { public int i ; internal int < M > b__0 ( ) { return i + 1 ; } } public void M ( ) { < > c__DisplayClass0_0 < > c__DisplayClass0_ = new < > c__DisplayClass0_0 ( ) ; < > c__DisplayClass0_.i = 1 ; new Func < int > ( < > c__DisplayClass0_. < M > b__0 ) ( ) ; } } using System ; public class C { public void M ( ) { var i = 1 ; Func < int , int > f = ( x ) = > x + 1 ; f ( i ) ; } } public class C { [ Serializable ] [ CompilerGenerated ] private sealed class < > c { public static readonly < > c < > 9 = new < > c ( ) ; public static Func < int , int > < > 9__0_0 ; internal int < M > b__0_0 ( int x ) { return x + 1 ; } } public void M ( ) { int arg = 1 ; ( < > c. < > 9__0_0 ? ? ( < > c. < > 9__0_0 = new Func < int , int > ( < > c. < > 9. < M > b__0_0 ) ) ) ( arg ) ; } } [ CompilerGenerated ] private sealed class < > c__DisplayClass0_0 { public int i ; | What is the allocation being saved here ? |
C_sharp : By calling Push ( ) and Pop ( ) an instance of Stack < T > in a single line I get a different behavior than performing the imho same code in two lines.The following code snippet reproduces the behavior : The Element class is really basic : With this code I get the following result ( .NET 3.5 , Win 7 , fully patched ) : Calling Expected ( ) ( version withtwo lines ) leaves one element on thestack with Value set to `` two '' .When calling Unexpected ( ) ( Versionwith one line ) I get one element onthe stack with the Value set to '' one '' .The only reason for the difference I could imagine was the operator precedence . As the assignment operator ( = ) has the lowest precedence I see no reason why the two method should behave differently.I also had a look at the IL generated : I 'm not an IL crack , but for me this code still looks good ans should leave one element on the stack with value set to `` two '' . Can anyone explain me the reason why the method Unexpected ( ) does something different than Expected ( ) ? Thanks a lot ! Lukas <code> static void Main ( string [ ] args ) { Stack < Element > stack = new Stack < Element > ( ) ; Element e1 = new Element { Value = `` one '' } ; Element e2 = new Element { Value = `` two '' } ; stack.Push ( e1 ) ; stack.Push ( e2 ) ; Expected ( stack ) ; // element on satck has value `` two '' //Unexpected ( stack ) ; // element on stack has value `` one '' Console.WriteLine ( stack.Peek ( ) .Value ) ; Console.ReadLine ( ) ; } public static void Unexpected ( Stack < Element > stack ) { stack.Peek ( ) .Value = stack.Pop ( ) .Value ; } public static void Expected ( Stack < Element > stack ) { Element e = stack.Pop ( ) ; stack.Peek ( ) .Value = e.Value ; } public class Element { public string Value { get ; set ; } } .method public hidebysig static void Unexpected ( class [ System ] System.Collections.Generic.Stack ` 1 < class OperationOrder.Element > stack ) cil managed { .maxstack 8 L_0000 : ldarg.0 L_0001 : callvirt instance ! 0 [ System ] System.Collections.Generic.Stack ` 1 < class OperationOrder.Element > : :Peek ( ) L_0006 : ldarg.0 L_0007 : callvirt instance ! 0 [ System ] System.Collections.Generic.Stack ` 1 < class OperationOrder.Element > : :Pop ( ) L_000c : callvirt instance string OperationOrder.Element : :get_Value ( ) L_0011 : callvirt instance void OperationOrder.Element : :set_Value ( string ) L_0016 : ret } | Unexpected operation order in Stack < T > related one liner |
C_sharp : I have the following C # code trying to benchmark under release mode : I am on a 64-bit machine and VS 2015 installed . When I run the code under 32-bit , it runs each iteration around 0.6 seconds , printed to the console . When I run it under 64-bit then the duration for each iteration simply jumps to 4 seconds ! I tried the sample code in my colleagues computer which only has VS 2013 installed . There both 32-bit and 64-bit versions run around 0.6 seconds.In addition to that , if we just remove the try catch block , it also runs in 0.6 seconds with VS 2015 in 64-bit . This looks like a serious RyuJIT regression when there is a try catch block . Am I correct ? <code> using System ; using System.Collections.Generic ; using System.Diagnostics ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; namespace ConsoleApplication54 { class Program { static void Main ( string [ ] args ) { int counter = 0 ; var sw = new Stopwatch ( ) ; unchecked { int sum = 0 ; while ( true ) { try { if ( counter > 20 ) throw new Exception ( `` exception '' ) ; } catch { } sw.Restart ( ) ; for ( int i = 0 ; i < int.MaxValue ; i++ ) { sum += i ; } counter++ ; Console.WriteLine ( sw.Elapsed ) ; } } } } } | Slow execution under 64 bits . Possible RyuJIT bug ? |
C_sharp : Following this very interesting issue which was originated from this question -I want to take 1 steps back please ( removed the dynamic environment ) : Looking at this code : ( a variant of this one ) The result is : This is understood : The x = 1 is from the method itself ( using Console.Writeline ) in bool operator for 1 is from the implicit operator from X to Bool ( so - Console.WriteLine treats the whole expression as Console.Writeline ( bool ) ) The last `` True '' is from the `` return true '' in the operator bool ( X x ) OK - So let 's change to Now - the result is : 2 questions : Why does this in false operator for 1 executes ? I do n't see any reason for false to be present here.I could understand why the right part in X.M ( 1 , out a ) & & X.M ( 2 , out b ) wo n't executes ONLY if the left part is false - but again I do n't see how the left part can be false . It does return true ( according to my first code ) NBI 've read many times the answers from the post : Jon said : The second & & is a normal & & between two bool expressions - because Nop returns bool , and there 's no & ( X , bool ) operator ... but there is a conversion from X to bool . So it 's more like : bool first = X.M ( 1 , out a ) & & X.M ( 2 , out b ) ; if ( first & & Nop ( a , b ) ) Now first is true even though only the first operand of & & has been evaluated ... so b really has n't been assigned.Still I do n't understand : `` first is true ( ? ? ? ? ) even though only the first operand of & & has been evaluated '' <code> void Main ( ) { int a ; int b = 100 ; Console.WriteLine ( X.M ( 1 , out a ) ) ; } public class X { public int H=0 ; public static X M ( int x , out int y ) { Console.WriteLine ( `` x = `` +x ) ; y = x ; return new X ( x ) ; } public X ( ) { } public X ( int h ) { H=h ; } public static bool operator false ( X x ) { Console.WriteLine ( `` in false operator for `` + x.H ) ; return true ; } public static bool operator true ( X x ) { Console.WriteLine ( `` in true operator for `` + x.H ) ; return true ; } public static X operator & ( X a , X b ) { Console.WriteLine ( `` in & operator for `` + a.H+ '' , '' +b.H ) ; return new X ( ) ; } public static implicit operator bool ( X x ) { Console.WriteLine ( `` in bool operator for `` + x.H ) ; return true ; } } x = 1in bool operator for 1True Console.WriteLine ( X.M ( 1 , out a ) ) ; Console.WriteLine ( X.M ( 1 , out a ) & & X.M ( 2 , out b ) ) ; x = 1in false operator for 1in bool operator for 1True | & & operator overloading and assignments in C # - Clarification ? |
C_sharp : First my question , and then some details : Q : Do I need to stub the value of a property when making sure its value is used in a subsequent assignment ? Details : I 'm using Rhino Mocks 3.5 's AAA syntax in MSpec classes . I 've trimmed the code below to keep it ( hopefully ) easy to grok . *Not Stubbing _fooResultMock 's Property Value : **Stubbing _fooResultMock 's Property Value : *The important thing to my test is that the value found in _fooResultMock 's Name property gets assigned to _fooTargetMock 's property.So , does the first code block adequately test that , or is second code block ( which stubs the value of _fooResultMock 's Name property ) necessary ? Is the second block undesirable for any reason ? <code> [ Subject ( `` Foo '' ) ] public class when_foo { Establish context = ( ) = > { _fooDependencyMock.Stub ( x = > x.GetResult ( ) ) .Return ( _fooResultMock ) ; _foo = new Foo ( _fooDependencyMock ) ; } ; Because action = ( ) = > { _foo.Whatever ( ) ; } ; It should_set_the_name_field = ( ) = > { _fooTargetMock.AssertWasCalled ( x = > x.Name = _fooResultMock.Name ) ; } ; } [ Subject ( `` Foo '' ) ] public class when_foo { Establish context = ( ) = > { _fooDependencyMock.Stub ( x = > x.GetResult ( ) ) .Return ( _fooResultMock ) ; _fooResultMock.Stub ( x = > x.Name ) .Return ( _theName ) ; // _theName ! _foo = new Foo ( _fooDependencyMock ) ; } ; Because action = ( ) = > { _foo.Whatever ( ) ; } ; It should_set_the_name_field = ( ) = > { _fooTargetMock.AssertWasCalled ( x = > x.Name = _theName ) ; // _theName ! } ; } | Rhino Mocks : stubbing value used in assertion ? |
C_sharp : Let 's say I have the following input : and expect the following output : The logic is a square which needs to be turned by 90 degrees to the right - but without linebreak.The width should be dynamic and always Is there a easy approach to solve this ? <code> string input = `` 123456789 '' ; string output = `` 741852963 '' ; // squares//INPUT OUTPUT// 123 ══╗ 741// 456 V 852// 789 963 int width = ( int ) Math.Sqrt ( input.Length ) ; | Sort a string by Linq |
C_sharp : On occasion we get some robots that like to post bad information to our website ( they are attempting some kind of reflection attack ) but luck for us the attempts are stopped via the default input validation that one gets with MVC.This is nice and all , but now we want to see what the robots are actually sending and we would like to log that information . Sadly , when one gets and HttpRequestValidationException , the offending input is truncated to the point of being useless ala ; A potentially dangerous ... . ( field = < a href= ... .. ) I am trying to use an action filter to detect these exceptions , and then create a log of all of the offending input so we can see what they are trying to send.This strikes me as odd and annoying because it seems that I now have no way of finding out what my attackers are really up to . Is n't there some way that I can get the information out of the form data without getting exceptions ? <code> public void OnException ( ExceptionContext filterContext ) { HttpRequestValidationException hex = filterContext.Exception as HttpRequestValidationException ; if ( hex == null ) { return ; } // Get the data . This will explode throwing the same exception ( ` HttpRequestValidationException ) . Is n't there a way that we can get our hands on the information ? string data = filterContext.HttpContext.Request.Form [ `` field '' ] ; ... . | MVC see input that caused exception |
C_sharp : Below is a console app that demonstrates the issue : Output is `` False True True '' .I 've used SOS.dll to try to find what holds the delegates from being GCed and here is what I get for the Action : Can someone explain what is going on ? <code> class Program { static void Main ( ) { InitRefs ( ) ; GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ; Console.WriteLine ( _refObj.IsAlive ) ; Console.WriteLine ( _refAction.IsAlive ) ; Console.WriteLine ( _refEvent.IsAlive ) ; Console.ReadKey ( ) ; } private static void InitRefs ( ) { _refObj = new WeakReference ( new object ( ) ) ; _refAction = new WeakReference ( ( Action ) ( ( ) = > { } ) ) ; _refEvent = new WeakReference ( new EventHandler ( ( sender , eventArgs ) = > { } ) ) ; } private static WeakReference _refObj ; private static WeakReference _refAction ; private static WeakReference _refEvent ; } ! gcroot 02472584HandleTable : 006613ec ( pinned handle ) - > 03473390 System.Object [ ] - > 02472584 System.Action | Delegates do not get garbage collected |
C_sharp : I am trying to change the Background of some errorneous data containing cells in a WPF DataGrid by using this code : However , upon doing this , the above change of background-color change is occuring to cells in the same column , periodically after every 14 ( aprox . ) rows as I scroll down the DataGrid . It is only intended to modify the Background of a single row . Can someone please provide a fix to this problem ? Thanks in advance . <code> DataGridRow gridRow = dgInventory.ItemContainerGenerator.ContainerFromIndex ( 0 ) as DataGridRow ; DataGridCell cell = dgInventory.Columns [ 1 ] .GetCellContent ( gridRow ) .Parent as DataGridCell ; cell.Background = Brushes.Gray ; gridRow.IsSelected = true ; gridRow.Focus ( ) ; | Changing a cell in a row of a DataGrid ( WPF ) is changing cells in rows below |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.