text
stringlengths
46
37.3k
title
stringlengths
12
162
C_sharp : I have a .Net library supplied by a third party . I did reflection on one of their classes and found a member method . The signature was ... So , I wanted to call this method through reflection and got the exception `` ByRef return value not supported in reflection invocation . `` Here is what I 've tried ... I have tried supplying parameters as in calling functions with ref parameters , but that made no difference.I would like to work around this exception in C # . <code> Byte & FooBar ( ) var strm = new TheirClass ( ) ; var t = strm.GetType ( ) ; var ms = t.GetMembers ( BindingFlags.Static|BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public ) ; foreach ( var m in ms ) { Debug.WriteLine ( String.Format ( `` Name : { 0 } : { 1 } '' , m.Name , m.ToString ( ) ) ) ; // ... // Name : FooBar : Byte & FooBar ( ) // ... } var meth = t.GetMethod ( `` FooBar '' ) ; object returnValue = meth.Invoke ( strm , new object [ ] { } ) ; //throw exception
How do I work around the error `` ByRef return value not supported in reflection invocation '' in C # ?
C_sharp : I 'm trying to write a simple program that would connect to remote machines and query the indexing status.Here 's the code that does it on my machine . This works OK.However , when I call GetCatalog on `` mycomputername.SystemIndex '' instead of `` SystemIndex '' , I get An unhandled exception of type 'System.Runtime.InteropServices.COMException ' occurred in IndexStatus.exe Additional information : Exception from HRESULT : 0x80042103Visual Studio 2015 is running with admin permissions on Windows 8.1 . The target computers will be Windows 7 systems mostly and the program will mostly be run from a Windows 10 system . I 'm using Microsoft.Search.Interop.dll from Microsoft Windows Search 3.X SDK downloaded from here . I turned the firewall off in case that had anything to do with it , but apparently not.I 've checked that I get the same exception if I call the function on complete nonsense like `` sdfd '' . And I 've found this : MSS_E_CATALOGNOTFOUND - 0x80042103 - ( 8451 ) WindowsSearchErrors.hI 've tried to use `` localhost '' instead of the machine name , but that did n't help.The MSDN docs say this : Currently Microsoft Windows Desktop Search ( WDS ) 3.0 supports only one catalog and it is named SystemIndex.I 'm not sure how to understand this . Perhaps the method is not able to choose between different machines ? If so , is there a way to connect to a remote catalog and make these queries , other than using something like PsExec ? Re Ben N 's answer : This is starting to become deep water for me , but I 'm more fascinated than afraid . : ) Your code worked for me after several modifications : CSearchManagerClass manager = System.Runtime.InteropServices.Marshal.CreateWrapperOfType ( comManager , typeof ( CSearchManagerClass ) ) ; would not compile on Visual Studio 2015 and would give the following errors : The second error was easy to fix by just adding a cast : As for the `` Interop type can not be embedded '' error message , I found this question . There are two suggested solutions : Change the Embed Interop Types property of the Microsoft.Search.Interop reference to False.Change CSearchManagerClass to CSearchManager.The first solution makes the program compile , but it affects portability . Now the program wo n't run on a computer that does n't have the .dll on it . The second solution compiles but throws An unhandled exception of type 'System.ArgumentException ' occurred in mscorlib.dll Additional information : The type must be __ComObject or be derived from __ComObject.on that exact line when I run it against my own machine.But there is another problem , and this one I have no clue about . When I run it against my colleague 's machine ( I 'm an administrator on his computer and Visual Studio is running with admin permissions ) , I 'm getting An unhandled exception of type 'System.UnauthorizedAccessException ' occurred in mscorlib.dll Additional information : Retrieving the COM class factory for remote component with CLSID { 7D096C5F-AC08-4F1F-BEB7-5C22C517CE39 } from machine computername failed due to the following error : 80070005 computername.This does scare me a little bit because I know next to nothing about COM . I 've checked that DCOM is enabled on his computer and on mine . But when I try to go to his computer in Component Services it shows as a and DCOM Config is missing from the tree . And the same happens for other computers on the domain ( even though I have admin rights on all workstations ) . This blog suggests it could be a firewall issue and if it is , it 's not something that will be feasible to overcome . Both of your answers are definitely bounty worthy already , but if you have any suggestions or would be able to shed some light on what 's happening , I would be very grateful . If I ca n't make it work , it 's fine , but I would definitely like to take as much knowledge as possible from this . <code> using System ; using Microsoft.Search.Interop ; namespace IndexStatus { class Program { static void Main ( string [ ] args ) { CSearchManager manager = new CSearchManager ( ) ; CSearchCatalogManager catalogManager = manager.GetCatalog ( `` SystemIndex '' ) ; _CatalogPausedReason pReason ; _CatalogStatus pStatus ; Console.WriteLine ( catalogManager.NumberOfItems ( ) .ToString ( ) ) ; int plIncrementalCount ; int plNotificationQueue ; int plHighPriorityQueue ; catalogManager.NumberOfItemsToIndex ( out plIncrementalCount , out plNotificationQueue , out plHighPriorityQueue ) ; Console.WriteLine ( plIncrementalCount.ToString ( ) ) ; Console.WriteLine ( plNotificationQueue.ToString ( ) ) ; Console.WriteLine ( plHighPriorityQueue.ToString ( ) ) ; catalogManager.GetCatalogStatus ( out pStatus , out pReason ) ; Console.WriteLine ( pStatus.ToString ( ) + `` `` + pReason.ToString ( ) ) ; Console.ReadLine ( ) ; } } } The specified catalog was not found . Check to see if it was deleted , or if there are errors in your application code . CSearchManagerClass manager = ( CSearchManagerClass ) System.Runtime.InteropServices.Marshal.CreateWrapperOfType ( comManager , typeof ( CSearchManagerClass ) ) ;
Ca n't query SystemIndex on my own machine when I specify the machine name
C_sharp : I have been through the Identity Server 4 QuickStart for using Entity Framework for persistent storage of configuration and operational data . In the QuickStart , the ApiResources are loaded into the database in code . The Api secret is set with in the ApiResource constructor . When , in Startup.InitializeDatabase , that ApiResource is added to the ConfigurationDbContext.ApiResources DbSet , the record in the child ApiSecrets table contains a readable text value in the ApiSecrets.Value field . I would like to manage my configuration data through SQL scripts , but I ca n't figure out how to set the ApiSecrets.Value correctly . I 've tried using T-SQL HASHBYTES ( 'SHA2_256 ' , 'secret ' ) , but that produces an unreadable ( I think binary ) value in ApiSecrets.Value . Is there a way to set the hashed secret correctly through T-SQL ? <code> new ApiResource ( `` api1 '' , `` My API '' ) { ApiSecrets = { new Secret ( `` secret '' .Sha256 ( ) ) } } foreach ( var resource in Config.GetApiResources ( ) ) { context.ApiResources.Add ( resource.ToEntity ( ) ) ; } context.SaveChanges ( ) ; K7gNU3sdo+OL0wNhqoVWhr3g6s1xYv72ol/pe/Unols=
How to insert Identity Server 4 persisted ApiSecret values using T-SQL
C_sharp : We have a Web Service using WebApi 2 , .NET 4.5 on Server 2012 . We were seeing occasional latency increases by 10-30ms with no good reason . We were able to track down the problematic piece of code to LOH and GC.There is some text which we convert to its UTF8 byte representation ( actually , the serialization library we use does that ) . As long as the text is shorter than 85000 bytes , latency is stable and short : ~0.2 ms on average and at 99 % . As soon as the 85000 boundary is crossed , average latency increases to ~1ms while the 99 % jumps to 16-20ms . Profiler shows that most of the time is spent in GC . To be certain , if I put GC.Collect between iterations , the measured latency goes back to 0.2ms.I have two questions : Where does the latency come from ? As far as I understand the LOHis n't compacted . SOH is being compacted , but does n't show the latency . Is there a practical way to work around this ? Note that I can ’ t control the size of the data and make it smaller. -- <code> public void PerfTestMeasureGetBytes ( ) { var text = File.ReadAllText ( @ '' C : \Temp\ContactsModelsInferences.txt '' ) ; var smallText = text.Substring ( 0 , 85000 + 100 ) ; int count = 1000 ; List < double > latencies = new List < double > ( count ) ; for ( int i = 0 ; i < count ; i++ ) { Stopwatch sw = new Stopwatch ( ) ; sw.Start ( ) ; var bytes = Encoding.UTF8.GetBytes ( smallText ) ; sw.Stop ( ) ; latencies.Add ( sw.Elapsed.TotalMilliseconds ) ; //GC.Collect ( 2 , GCCollectionMode.Default , true ) ; } latencies.Sort ( ) ; Console.WriteLine ( `` Average : { 0 } '' , latencies.Average ( ) ) ; Console.WriteLine ( `` 99 % : { 0 } '' , latencies [ ( int ) ( latencies.Count * 0.99 ) ] ) ; }
Extensive use of LOH causes significant performance issue
C_sharp : I 'm writing a library which includes scheduling functionality ( not the standard TaskScheduler , IScheduler ... ) based on .Net Tasks . I 'm using TaskCompletionSource , and Task.Status is critical for representing the status of underlying operations , including TaskStatus.Created , i.e . created but not yet started . I know returned Tasks should normally be hot , but for my manually controlled proxy Tasks , I really do want them initially as Created.Unfortunately for me , the initial status of TaskCompletionSource.Task is WaitingForActivation , i.e . it 's already gone past Created . Put differently , TaskCompletionSource supports two states , but I need three states : Question : How can I get a Task that I can manually set to three different states ? I.e . Task.Status can be set to : 1 ) Created2 ) One of WaitingForActivation/WaitingForChildrenToComplete/WaitingToRun/Running3 ) Either of RanToCompletion/Canceled/FaultedThe code below understandably complains about the type mismatch . I can instead wrap the Task by changing new Task < TResult > to new Task < Task < TResult > > , but to get back to Task < TResult > I have to Unwrap ( ) it , and the unwrapped task will have status WaitingForActivation , bringing me back to square one.I will have a large number of these , so blocking a thread with Wait ( ) for each is not an option.I have considered inheriting from Task and overriding members ( using new ) , but if possible it would be nice to give the library user an actual Task instead of a DerivedTask , especially since I present regular Tasks to also be awaited in many other places.Ideas ? Errors : * Can not convert lambda expression to delegate type 'System.Func ' because some of the return types in the block are not implicitly convertible to the delegate return type* Can not implicitly convert type 'System.Threading.Tasks.Task ' to 'TResult ' <code> private TaskCompletionSource < TResult > tcs ; private async Task < TResult > CreateStartCompleteAsync ( ) { await tcs.Task ; if ( tcs.Task.IsCanceled ) { throw new OperationCanceledException ( `` '' ) ; } else if // etc . } public ColdTaskCompletionSource ( ) { tcs = new TaskCompletionSource < TResult > ( ) ; Task = new Task < TResult > ( ( ) = > CreateStartCompleteAsync ( ) ) ; }
Create ice cold TaskCompletionSource ?
C_sharp : Background : In the spirit of `` program to an interface , not an implementation '' and Haskell type classes , and as a coding experiment , I am thinking about what it would mean to create an API that is principally founded on the combination of interfaces and extension methods . I have two guidelines in mind : Avoid class inheritance whenever possible . Interfaces should be implemented as sealed classes . ( This is for two reasons : First , because subclassing raises some nasty questions about how to specify and enforce the base class ' contract in its derived classes . Second , and that 's the Haskell type class influence , polymorphism does n't require subclassing . ) Avoid instance methods wherever possible . If it can be done with extension methods , these are preferred . ( This is intended to help keep the interfaces compact : Everything that can be done through a combination of other instance methods becomes an extension method . What remains in the interface is core functionality , and notably state-changing methods . ) Problem : I am having problems with the second guideline . Consider this : Obviously , for the expected outcome ( `` Eat it yourself… '' ) , Eat ought to be a regular instance method.Question : What would be a refined / more accurate guideline about the use of extension methods vs. ( virtual ) instance methods ? When does the use of extension methods for `` programming to an interface '' go too far ? In what cases are instance methods actually required ? I do n't know if there is any clear , general rule , so I am not expecting a perfect , universal answer . Any well-argued improvements to guideline ( 2 ) above are appreciated . <code> interface IApple { } static void Eat ( this IApple apple ) { Console.WriteLine ( `` Yummy , that was good ! `` ) ; } interface IRottenApple : IApple { } static void Eat ( this IRottenApple apple ) { Console.WriteLine ( `` Eat it yourself , you disgusting human , you ! `` ) ; } sealed class RottenApple : IRottenApple { } IApple apple = new RottenApple ( ) ; // API user might expect virtual dispatch to happen ( as usual ) when 'Eat ' is called : apple.Eat ( ) ; // == > `` Yummy , that was good ! ''
`` Program to an interface '' using extension methods : When does it go too far ?
C_sharp : I have a Report object that has Recipients property ( of String datatype ) . The Recipients property will hold all the recipients ’ email address in comma separated string . I need to create a “ Collection ” of Email objects from the comma separated string . I have the following code that uses a List of string to get the email address first . Then I create a collection of email objects . Is there a better way to avoid the redundant List and Collection using LINQ ? References : Better code for avoiding one dictionary - Case Sensitivity IssueRemove duplicates in the list using linqUsing LINQ to find duplicates across multiple propertiesC # : Difference between List < T > and Collection < T > ( CA1002 , Do not expose generic lists ) CA1002 : Do not expose generic lists . System.Collections.Generic.List is a generic collection designed for performance not inheritance and , therefore , does not contain any virtual members . http : //msdn.microsoft.com/en-us/library/ms182142 ( v=vs.80 ) .aspx <code> Report report = new Report ( ) ; report.Recipients = `` test @ test.com , demo @ demo.com '' ; List < string > emailAddressList = new List < string > ( report.Recipients.Split ( ' , ' ) ) ; Collection < Email > emailObjectCollection = new Collection < Email > ( ) ; foreach ( string emailAddress in emailAddressList ) { Email email = new Email ( ) ; email.EmailAddress = emailAddress ; emailObjectCollection.Add ( email ) ; }
How to avoid redundant List using LINQ
C_sharp : Reference : How can a dynamic be used as a generic ? This enters with CheckEntity ( 16 , '' Container '' ) ; . After the first line runs , AnyObject becomes a blank Assembly.Models.DbModels.Container when inspected with the debugger . If var AnyType = AnyObject.GetType ( ) ; is used , then AnyType shows as Assembly.Models.DbModels.Container . However , when the call to CheckWithInference ( AnyObject , entityId ) ; is made an exception is thrown.outer : Object reference not set to an instance of an object . inner : Microsoft.CSharp.RuntimeBinder.SymbolTable.GetOriginalTypeParameterType ( Type t ) +10I made a self-contained example here - but it runs without error : ( Note , this is in asp.net mvc 3 c # HomeController.cs : Example.csIndex.cshtmlI am at a loss . Why am getting this exception ? I was unable to easily reproduce it . I am not sure what else to include for the example as this is all that the actual code has in it.The really confusing part is that in the application , when this exception occurs , the action fails . However , upon revisiting the page and trying a second time , there is no exception thrown . <code> public void CheckEntity ( int entityId , string entityType = null ) { dynamic AnyObject = Activator.CreateInstance ( `` Assembly '' , '' Assembly.Models.DbModels . '' + entityType ) .Unwrap ( ) ; CheckWithInference ( AnyObject , entityId ) ; } private static void CheckWithInference < T > ( T ignored , int entityId ) where T : class { Check < T > ( entityId ) ; } private static void Check < T > ( int entityId ) where T : class { using ( var gr = new GenericRepository < T > ( ) ) { } } using System ; using System.Collections.Generic ; using System.Linq ; using System.Web ; using System.Web.Mvc ; namespace InferenceExample.Controllers { public class HomeController : Controller { // // GET : /Home/ public ActionResult Index ( ) { return View ( ) ; } public void CheckEntity ( int entityId , string entityType = null ) { dynamic AnyObject = Activator.CreateInstance ( `` InferenceExample '' , `` InferenceExample.Models . '' + entityType ) .Unwrap ( ) ; CheckWithInference ( AnyObject , entityId ) ; } private static void CheckWithInference < T > ( T ignored , int entityId ) where T : class { Check < T > ( entityId ) ; } private static void Check < T > ( int entityId ) where T : class { var repo = new List < T > ( ) ; } } } using System ; using System.Collections.Generic ; using System.Linq ; using System.Web ; namespace InferenceExample.Models { public class Example { public int ExampleId { get ; set ; } public string Name { get ; set ; } } } @ { ViewBag.Title = `` Index '' ; } < h2 > Index < /h2 > @ Html.ActionLink ( `` Start '' , `` CheckEntity '' , new { entityId = 16 , entityType = `` Example '' } )
GetOriginalTypeParameterType throws Object reference not set to an instance of an object exception
C_sharp : Here comes a silly question . I 'm playing with the parse function of System.Single and it behaves unexpected which might be because I do n't really understand floating-point numbers . The MSDN page of System.Single.MaxValue states that the max value is 3.402823e38 , in standard form that isIf I use this string as an argument for the Parse ( ) method , it will succeed without error , if I change any of the zeros to an arbitrary digit it will still succeed without error ( although it seems to ignore them looking at the result ) . In my understanding , that exceeds the limit , so What am I missing ? <code> 340282300000000000000000000000000000000
Parsing floats with Single.Parse ( )
C_sharp : I am seeking some advice on what is the recommend way to use 'constant ' strings within my classes , e.g.The reason I would like to implement these , i.e . either via a const or via a getter , is because throughout my class ( es ) , I have methods and constructors that use these strings as parameters and I was thinking to avoid typos and also to avoid using strings ( weakly-typed ? ) , I wanted to reference them strongly , e.g.What are others doings ? Any advice will be greatly appreciated ! Is this good/bad ? <code> public string EmployeesString { get { return `` Employees '' ; } } const string EmployeeString = `` Employee '' ; DoSomething ( this.EmployeeString , employee ) ;
Design Advice on Getter or Const for String in Classes - what are others doing ?
C_sharp : My following C # code is obviously a hack so how do I capture the index value in the Where method ? <code> string [ ] IntArray = { `` a '' , `` b '' , `` c '' , `` b '' , `` b '' } ; int index=0 ; var query = IntArray.Where ( ( s , i ) = > ( s== '' b '' ) & ( ( index=i ) ==i ) ) ; // '' & '' and `` ==i '' only exists to return a bool after the assignment ofindex foreach ( string s in query ) { Console.WriteLine ( `` { 0 } is the original index of { 1 } '' , index , s ) ; } //outputs ... //1 is the original index of b//3 is the original index of b//4 is the original index of b
Is there a way to capture the index value in a LINQ Where method in C # ?
C_sharp : I have no other developers to ask for advice or `` what do you think - I 'm thinking this '' so please , if you have time , have a read and let me know what you think.It 's easier to show than describe , but the app is essentially like a point of sale app with 3 major parts : Items , OrderItems and the Order.The item class is the data as it comes from the datastore.The order item class is an item line on an order.Currently when you add fees or discounts to an order it 's as simple as : I like it , it makes sense and a base class that Order inherits from iterates through the items in the list , calculates appropriate taxes , and allows for other Order-type documents ( of which there are 2 ) to inherit from the base class that calculates all of this without re-implimenting anything . If an order-type document does n't have discounts , it 's as easy as just not adding a - $ value OrderItem.The only problem that I 'm having is displaying this data . The form ( s ) that this goes on has a grid where the Sale items ( ie . not fees/discounts ) should be displayed . Likewise there are textboxes for certain fees and certain discounts . I would very much like to databind those ui elements to the fields in this class so that it 's easier on the user ( and me ) .MY THOUGHTHave 2 interfaces : IHasFees , IHasDiscounts and have Order implement them ; both of which would have a single member of List . That way , I could access only Sale items , only Fees and only Discounts ( and bind them to controls if need be ) .What I do n't like about it : - Now I 've got 3 different add/remove method for the class ( AddItem/AddFee/AddDiscount/Remove ... ) - I 'm duplicating ( triplicating ? ) functionality as all of them are simply lists of the same type of item , just that each list has a different meaning.Am I on the right path ? I suspect that this is a solved problem to most people ( considering that this type of software is very common ) . <code> public class Item : IComparable < OrderItem > , IEquatable < OrderItem > { public Int32 ID { get ; set ; } public String Description { get ; set ; } public decimal Cost { get ; set ; } public Item ( Int32 id , String description , decimal cost ) { ID = id ; Description = description ; Cost = cost ; } // Extraneous Detail Omitted } public class OrderItem : Item , IBillableItem , IComparable < OrderItem > , IEquatable < OrderItem > { // IBillableItem members public Boolean IsTaxed { get ; set ; } public decimal ExtendedCost { get { return Cost * Quantity ; } } public Int32 Quantity { get ; set ; } public OrderItem ( Item i , Int32 quantity ) : base ( i.ID , i.Description , i.Cost ) { Quantity = quantity ; IsTaxed = false ; } // Extraneous Detail Omitted } Order order = new Order ( ) ; // Feeorder.Add ( new OrderItem ( new Item ( `` Admin Fee '' , 20 ) , 1 ) ) ; // Discountorder.Add ( new OrderItem ( new Item ( `` Today 's Special '' , -5 ) , 1 ) ) ;
Should I incorporate list of fees/discounts into an order class or have them be itemlines
C_sharp : Can someone help me to understand following codeIs it valid to assign a disposing object to MyFont property ? <code> public Font MyFont { get ; set ; } void AssignFont ( ) { using ( Font f = new Font ( `` Shyam '' ,2 ) ) { this.MyFont = f ; } }
C # using statement more understanding
C_sharp : Consider this MCVE class : When I evaluate and print such an object in C # Interactive , it looks like this : That 's not useful . I 'd like it to look like this : How do I do that ? I 've tried overriding ToString like this : This does n't produce quite what I 'd like : There 's at least three issues with this output : The value is not in quotes . I 'd like it to be `` bar '' instead of bar.The type argument is displayed as System.String instead of string.The entire value is surrounded by square brackets . This is the least of my concerns.Is there a way to make C # interactive display an object with a custom format ? I know that I can add a public property to the class in order to display the value , but I do n't want to do that because of encapsulation concerns . To be clear , though , here 's what I mean : This prints closer to what I 'd like : but , as I wrote , I do n't want to add a public property.How do I get it to behave like the following ? Notice that when using anything else than a string ( e.g . an int ) , there should be no quotes . <code> public class Foo < T > { private readonly T value ; public Foo ( T value ) { this.value = value ; } } > new Foo < string > ( `` bar '' ) Foo < string > { } Foo < string > { `` bar '' } public override string ToString ( ) { return $ '' Foo { typeof ( T ) } { { { value } } } '' ; } > new Foo < string > ( `` bar '' ) [ Foo < System.String > { bar } ] public class Foo < T > { public Foo ( T value ) { Value = value ; } public T Value { get ; } } > new Foo < string > ( `` bar '' ) Foo < string > { Value= '' bar '' } > new Foo < string > ( `` bar '' ) Foo < string > { `` bar '' } > new Foo < int > ( 42 ) Foo < int > { 42 }
Custom print of object in C # Interactive
C_sharp : I 'm trying to deep clone an object which contains a System.Random variable . My application must be deterministic and so I need to capture the the random object state . My project is based on .Net Core 2.0.I 'm using some deep clone code from here ( How do you do a deep copy of an object in .NET ( C # specifically ) ? ) which uses serialization.The documentation for System.Random is mixed : Serializablehttps : //msdn.microsoft.com/en-us/library/system.random ( v=vs.110 ) .aspxhttp : //referencesource.microsoft.com/ # mscorlib/system/random.cs , bb77e610694e64ca ( source code ) Not Serializablehttps : //docs.microsoft.com/en-us/dotnet/api/system.random ? view=netframework-4.7.1https : //docs.microsoft.com/en-us/dotnet/api/system.random ? view=netcore-2.0and I get the following error . System.Runtime.Serialization.SerializationException HResult=0x8013150C Message=Type 'System.Random ' in Assembly 'System.Private.CoreLib , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=7cec85d7bea7798e ' is not marked as serializable . Source=System.Runtime.Serialization.FormattersCan System.Random it be cloned in the way I want ? I created a small program to illustrate.I probably do n't need the Container object , but this structure more closely resembles my application.Making R [ NonSerialized ] removes the error but I do n't get my Random object back after deserialization . I tried re-creating the random object , but it starts a new random sequence and so breaks the deterministic requirement . <code> using System ; using System.IO ; using System.Runtime.Serialization.Formatters.Binary ; namespace RandomTest { class Program { static void Main ( string [ ] args ) { Container C = new Container ( ) ; Container CopyC = DeepClone ( C ) ; } public static T DeepClone < T > ( T obj ) { using ( var ms = new MemoryStream ( ) ) { var formatter = new BinaryFormatter ( ) ; formatter.Serialize ( ms , obj ) ; // < -- error here ms.Position = 0 ; return ( T ) formatter.Deserialize ( ms ) ; } } } [ Serializable ] public class Container { public ObjectType AnObject ; public Container ( ) { AnObject = new ObjectType ( ) ; } } [ Serializable ] public class ObjectType { // [ NonSerialized ] // Uncommenting here removes the error internal System.Random R ; } }
Deep clone of System.Random
C_sharp : I want to create a simple ASP.Net form , that will get birth dates.I have a model with this property : and in my view ( is using the datepicker ) : The only one setting on my javascript datepicker is : because I want show dates without times.Now , I ca n't save , because of the validation error : The value '12/23/2000 ' is not valid for BirthDate.Now , I KNOW , its a globalization error ... I need set culture in < globalization > element in web.config , etc ... But , have you noticed I set no formats ( except the datepicker format `` L '' ) ? I want that form get birthdates from people in any country , no a specific culture/format etc.Is this possible ? How can I do it ? Edit : which date picker are u using ? The JQuery one , but this is not a requeriment , I can change to any datepicker that can easily handle different save formats `` yyyy-mm-dd '' and display format . Which locale your server is located and which format do you prefer to work within your MVC code and to persist in database ? I dont know where my customer will host the site , its AWS ... I prefer work with en-us . <code> [ DataType ( DataType.Date ) ] public DateTime ? BirthDate { get ; set ; } @ Html.LabelFor ( model = > model.BirthDate ) @ Html.TextBoxFor ( model = > model.BirthDate , new { @ class = `` form-control date-picker '' } ) @ Html.ValidationMessageFor ( model = > model.BirthDate , `` '' , new { @ class = `` text-danger '' } ) format : ' L '
Posting valid DateTimes from anywhere
C_sharp : I 'm using VS2017 on Windows 10 to work on a C # project . It is a really small console app that does nothing but require administrator privileges and then runs an HTA.The code references only these .NET assemblies : Since all of these exist in .NET since 2.0 and forward , it seems it should be possible to create the app without having to specify anything except .NET 2.0 . But doing this causes the app to display the `` must install .NET 2.0 or 3.5 '' message when running it on a system which has only .NET 4.0 or greater.Is there a way to create this app so it does n't specify a .NET version ? I tried deleting the < TargetFrameworkVersion > from the .csproj file but it still builds thinking it is a .NET 4.0 app.UPDATEBased upon a suggested answer and this article , I updated the App.config to show it supports both v2 and v4 : I then built with target set to NET Framework 4.6.1 and ran it on a Win7Pro-64bit system with only NET Framework 2.0/3.5 installed . It displayed the message `` You must first install one of the following versions of .NET Framework '' and only listed v4.0.30319.I then built with target set to NET Framework 2.0 and ran it on a Win10Pro-64bit system with only NET Framework 4.0 installed . It displayed a message that I had to `` NET Framework 3.5 '' or my app may not work correctly . I tried the `` skip this '' option and the app did n't work.Running on the system according to the target , the app works fine.Why wo n't it just use whichever framework is available since it is designated as supporting both ? <code> using System ; using System.Diagnostics ; using System.IO ; < startup useLegacyV2RuntimeActivationPolicy= '' true '' > < supportedRuntime version= '' v2.0.50727 '' / > < supportedRuntime version= '' v4.0 '' / > < /startup >
Create a .NET app that works on any .NET version if only basic requirements
C_sharp : Using Entity Framework one often writes queries such asWhat really makes my stomach churn is the `` Customer '' string argument . I have a hard time believing that EF does not generate table names as constants somewhere . Does anyone know a better approach than to using a string ? for the Include fetch option ? <code> var orders = from o in context.Orders.Include ( `` Customer '' ) where o.OrderDate.HasValue & & o.OrderDate.Value.Year == 1997 orderby o.Freight select o ;
Entity framework autogenerated table names
C_sharp : Somehow EF disposes the ObjectContext in between two queries , without any further notice , but apparently not randomly and not due to a timeout.I added the using so the example is self contained but it does the same with the DbContext used in the whole application.Notice db is not yet disposed by using so this is out of the question.The error also happens with .First ( ) and .Where ( ) .Single/First ( ) .Inverting the two requests does not do the trick : I do not use any navigation propery of Employee either , and this does not solve the problem : What I have noted is this problem does n't occur on the WebSite project but only in the UnitTests project . I have set the same connectionString for the two ( apart from the db name ) but that did n't do anything either.Worse yet : The timeout is set to 20000 and MultipleActiveResultSets is set to true.For now the only workaround I found was to call .ToList ( ) on the whole DbSet before trying .Single ( ) : But this is n't acceptable because the operation is frequent and I expect the DbSet to be quite big so this will take a lot of time for nothing . <code> using ( MyDbContext db = new MyDbContext ( ) ) { //I am sure these are unique Employee emp = db.Employees.Single ( e = > e.FirstName == `` Bob '' & & e.LastName == `` Morane '' ) ; Node node = db.Nodes.Single ( n = > n.ShortName == `` stuff '' ) ; //Here the request throws // `` ObjectContext instance has been disposed and can no longer be used for operations that require a connection '' } using ( MyDbContext db = new MyDbContext ( ) ) { Node node = db.Nodes.Single ( n = > n.ShortName == `` stuff '' ) ; Employee emp = db.Employees.Single ( e = > e.FirstName == `` Bob '' & & e.LastName == `` Morane '' ) ; //Here the request throws // `` ObjectContext instance has been disposed and can no longer be used for operations that require a connection '' } using ( MyDbContext db = new MyDbContext ( ) ) { // According to every post I 've found this `` should fix the objectcontext disposed error '' db.Configuration.ProxyCreationEnabled = false ; db.Configuration.LazyLoadingEnabled = false ; Employee emp = db.Employees.Single ( e = > e.FirstName == `` Bob '' & & e.LastName == `` Morane '' ) ; Node node = db.Nodes.Single ( n = > n.ShortName == `` stuff '' ) ; //But it does n't : same error here } using ( MyDbContext db = new MyDbContext ( ) ) { Node node = db.Nodes.Single ( n = > n.ShortName == `` stuff '' ) ; Employee emp = db.Employees.Single ( e = > e.FirstName == `` Bob '' & & e.LastName == `` Morane '' ) ; // boom node.Should ( ) .NotBeNull ( ) ; } using ( MyDbContext db = new MyDbContext ( ) ) { Node node = db.Nodes.Single ( n = > n.ShortName == `` stuff '' ) ; node.Should ( ) .NotBeNull ( ) ; Employee emp = db.Employees.Single ( e = > e.FirstName == `` Bob '' & & e.LastName == `` Morane '' ) ; // no boom } using ( MyDbContext db = new MyDbContext ( ) ) { Employee emp = db.Employees.Single ( e = > e.FirstName == `` Bob '' & & e.LastName == `` Morane '' ) ; Node node = db.Nodes.ToList ( ) .Single ( n = > n.ShortName == `` stuff '' ) ; //Works }
ObjectContext has been disposed throwed by EnsureConnection ( ) in consecutive queries ( No navigation properties used and no using ( ) )
C_sharp : I have a UWP project with two monitors that I want to use to open a new window on a secondary monitor . The application includes three parts : Open Main Page on first monitorCreate new pageOpen on secondary monitorI wrote the first and second parts correctly , but I ca n't find a solution for the third part.Please help me with moving the window to another monitor . <code> public sealed partial class MainPage : Page { public MainPage ( ) { this.InitializeComponent ( ) ; //called creat new page function NewWindow ( ) ; } private async void NewWindow ( ) { var myview = CoreApplication.CreateNewView ( ) ; int newid = 0 ; await myview.Dispatcher.RunAsync ( CoreDispatcherPriority.Normal , ( ) = > { Frame newframe = new Frame ( ) ; newframe.Navigate ( typeof ( Newpage ) , null ) ; Window.Current.Content = newframe ; Window.Current.Activate ( ) ; ApplicationView.GetForCurrentView ( ) .Title = `` Z '' ; newid = ApplicationView.GetForCurrentView ( ) .Id ; } ) ; await ApplicationViewSwitcher.TryShowAsStandaloneAsync ( newid , ViewSizePreference.UseMinimum ) ; } }
Open new window on secondary monitor in UWP
C_sharp : Here 's a little LinqToSql GOTCHA : Guess what - if you pass a null State object to this method , you get a null reference exception ! It seems that LinqToSql does n't use the || shortcut operator as a shortcut ! Answer credit goes to whoever proposes the best explanation & workaround for this . <code> // Returns the number of counties in a state , // or all counties in the USA if the state is nullpublic static int CountCounties ( State s ) { var q = from cy in County.GetTable ( ) // my method to get the ITable where ( s == null || s.Code == cy.StateCode ) // shortcut OR operator , right ... ? select cy ; return q.Count ( ) ; }
Conditional shortcuts in LinqToSql query
C_sharp : I am modifying the default analyzer project that comes from the code analyzer template to try and get it to report at all of the declarations for a partial class.I have modified the code to : In two separate files , I have partial classes like this : I put breakpoints on the ReportDiagnostic and am seeing it called for each location , but within Visual Studio it only reports diagnostics within a single file.If I put multiple implementations of Foo in a single file ( and it happens to be reporting on that files declaration ) then I will see both diagnostics reported.Am I misunderstanding how diagnostics are supposed to be reported or is this a bug ? If it is a bug , is it a Roslyn problem or is it a problem with Visual Studio 's consumption of Roslyn ? <code> public override void Initialize ( AnalysisContext context ) { context.RegisterSymbolAction ( AnalyzeSymbol , SymbolKind.NamedType ) ; } private static void AnalyzeSymbol ( SymbolAnalysisContext context ) { var namedTypeSymbol = ( INamedTypeSymbol ) context.Symbol ; // Find just those named type symbols with names containing lowercase letters . if ( namedTypeSymbol.Name.ToCharArray ( ) .Any ( char.IsLower ) ) { foreach ( var location in namedTypeSymbol.Locations ) { // For all such symbols , produce a diagnostic . var diagnostic = Diagnostic.Create ( Rule , location , namedTypeSymbol.Name ) ; context.ReportDiagnostic ( diagnostic ) ; } } } // File1.cspartial class Foo { public string BarString ; } // File2.cspartial class Foo { public string FooBarString ; }
ReportDiagnostic on Partial Classes
C_sharp : I have a CheckBoxList control that contains dynamically generated checkbox items . This checkboxlist will contain usernames . I am using Gravatar control from AjaxControlToolkit to allow users to have their own profile pictures . What I want is that when a checkbox with username as a text is added to the CheckBoxList , a Gravatar control should also be added before or after the checkbox , showing the corresponding display picture of the user . An alternative way came to my mind is to have a custom user control with a checkbox and gravatar . But if any other lite and easy solution available then please suggest me . Following is the code : As you can see it also has a listbox that contains the selected item from checkboxlist . If possible please suggest me the same for the listbox . <code> < table class= '' style1 '' > < tr > < td align= '' right '' style= '' padding : 5px '' width= '' 25 % '' > Username/Email : < /td > < td style= '' padding : 5px '' > < asp : TextBox ID= '' TextBox1 '' runat= '' server '' > < /asp : TextBox > & nbsp ; < asp : Button ID= '' Button1 '' runat= '' server '' CssClass= '' newButton '' onclick= '' Button1_Click '' Text= '' Search '' / > < /td > < /tr > < tr > < td align= '' right '' style= '' padding : 5px '' valign= '' top '' width= '' 25 % '' > Results : < /td > < td style= '' padding : 5px '' > < asp : CheckBoxList ID= '' CheckBoxList1 '' runat= '' server '' onselectedindexchanged= '' CheckBoxList1_SelectedIndexChanged '' AutoPostBack= '' True '' > < /asp : CheckBoxList > < /td > < /tr > < tr > < td align= '' right '' style= '' padding : 5px '' width= '' 25 % '' valign= '' top '' > Selected People : < /td > < td style= '' padding : 5px '' > < asp : ListBox ID= '' ListBox1 '' runat= '' server '' Height= '' 149px '' Width= '' 260px '' > < /asp : ListBox > < /td > < /tr > < /table >
How to add AjaxControlToolkit 's Gravatar Control before or after checkbox in checkboxlist control
C_sharp : I was investigating some strange object lifetime issues , and came across this very puzzling behaviour of the C # compiler : Consider the following test class : The compiler generates the following : The original class contains two lambdas : s = > hashSet.Add ( s ) and ( ) = > File.OpenRead ( file ) . The first closes over local variable hashSet , the second closes over local variable file . However , the compiler generates a single closure implementation class < > c__DisplayClass1_0 that contains both hashSet and file . As a consequence , the returned CreateStream delegate contains and keeps alive a reference to the hashSet object that should have been available for GC once TestMethod returned.In the actual scenario where I 've encountered this issue , a very substantial ( ie , > 100mb ) object is incorrectly enclosed.My specific questions are : Is this a bug ? If not , why is this behaviour considered desirable ? Update : The C # 5 spec 7.15.5.1 says : When an outer variable is referenced by an anonymous function , the outer variable is said to have been captured by the anonymous function . Ordinarily , the lifetime of a local variable is limited to execution of the block or statement with which it is associated ( §5.1.7 ) . However , the lifetime of a captured outer variable is extended at least until the delegate or expression tree created from the anonymous function becomes eligible for garbage collection.This would appear to be open to some degree of interpretation , and does not explicitly prohibit a lambda from capturing variables that it does not reference . However , this question covers a related scenario , which @ eric-lippert considered to be a bug . IMHO , I see the combined closure implementation provided by the compiler as a good optimization , but that the optimization should not be used for lambdas which the compiler can reasonably detect may have lifetime beyond the current stack frame.How do I code against this without abandoning the use of lambdas all together ? Notably how do I code against this defensively , so that future code changes do n't suddenly cause some other unchanged lambda in the same method to start enclosing something that it should n't ? Update : The code example I 've provided is by necessity contrived . Clearly , refactoring lambda creation out to a separate method works around the problem . My question is not intended to be about design best practices ( as well covered by @ peter-duniho ) . Rather , given the content of the TestMethod as it stands , I 'd like to know if there is any way to coerce the compiler to exclude the createStream lambda from the combined closure implementation.For the record , I 'm targeting .NET 4.6 with VS 2015 . <code> class Test { delegate Stream CreateStream ( ) ; CreateStream TestMethod ( IEnumerable < string > data ) { string file = `` dummy.txt '' ; var hashSet = new HashSet < string > ( ) ; var count = data.Count ( s = > hashSet.Add ( s ) ) ; CreateStream createStream = ( ) = > File.OpenRead ( file ) ; return createStream ; } } internal class Test { public Test ( ) { base..ctor ( ) ; } private Test.CreateStream TestMethod ( IEnumerable < string > data ) { Test. < > c__DisplayClass1_0 cDisplayClass10 = new Test. < > c__DisplayClass1_0 ( ) ; cDisplayClass10.file = `` dummy.txt '' ; cDisplayClass10.hashSet = new HashSet < string > ( ) ; Enumerable.Count < string > ( data , new Func < string , bool > ( ( object ) cDisplayClass10 , __methodptr ( < TestMethod > b__0 ) ) ) ; return new Test.CreateStream ( ( object ) cDisplayClass10 , __methodptr ( < TestMethod > b__1 ) ) ; } private delegate Stream CreateStream ( ) ; [ CompilerGenerated ] private sealed class < > c__DisplayClass1_0 { public HashSet < string > hashSet ; public string file ; public < > c__DisplayClass1_0 ( ) { base..ctor ( ) ; } internal bool < TestMethod > b__0 ( string s ) { return this.hashSet.Add ( s ) ; } internal Stream < TestMethod > b__1 ( ) { return ( Stream ) File.OpenRead ( this.file ) ; } } }
Is this closure combination behaviour a C # compiler bug ?
C_sharp : I 'm trying to create a method which returns a list of whichever type the user wants . To do this I 'm using generics , which I 'm not too familiar with so this question may be obvious . The problem is that this code does n't work and throws the error message Can not convert type Systems.Collections.Generic.List < CatalogueLibrary.Categories.Brand > to Systems.Collection.Generic.List < T > But if I use IList instead , there are no errors . Why can I use IList but not List in this case ? collection.Brands returns a BrandCollection type from a third party library so I do n't know how that 's created . Could it be that BrandCollection may derive from IList ( just guessing that it does ) and so it can be converted to it but not to a normal List ? <code> private List < T > ConvertToList < T > ( Category cat ) { switch ( cat ) { case Category.Brands : return ( List < T > ) collection.Brands.ToList < Brand > ( ) ; } ... } private IList < T > ConvertToList < T > ( Category cat ) { switch ( cat ) { case Category.Brands : return ( IList < T > ) collection.Brands.ToList < Brand > ( ) ; } ... }
Can use IList but not List in generic method
C_sharp : We 'll start with a standalone story , just so you understand why : I want to treat any actions that change data against the same interface : ICommandThere are things that exist out there called ICommandHandlers that handle any command I want.So , if I want a CreatePersonCommand I 'd need a CreatePersonCommandHandler out there.So here 's the body of a console application that demonstrates this : ( Requires Simple Injector ) So for whatever reason SimpleInjector always tries to resolve the DeleteCommandHandler < > for the CreateBaseCommand < > that I have . Again , the order does not matter.I have other , closed-type , commandhandlers ( and their respective commands ) that just inherits ICommandHandler < , > which work fine.I spent a good bit of time going through every possible type of registration I could from this . <code> // The e.g . CreatePersonCommand , with TResult being Person , as an example.public interface ICommand < TResult > { } //This handles the command , so CreatePersonCommandHandlerpublic interface ICommandHandler < in TCommand , out TResult > where TCommand : ICommand < TResult > { TResult Handle ( TCommand command ) ; } // Imagine a generic CRUD set of operations here where we pass // in an instance of what we need madepublic class CreateBaseCommand < TModel > : ICommand < TModel > { public TModel ItemToCreate { get ; set ; } } public class DeleteBaseCommand < TModel > : ICommand < TModel > { public TModel ItemToDelete { get ; set ; } } public class CreateCommandBaseHandler < TModel > : ICommandHandler < CreateBaseCommand < TModel > , TModel > { public TModel Handle ( CreateBaseCommand < TModel > command ) { // create the thing return default ( TModel ) ; } } public class DeleteCommandBaseHandler < TModel > : ICommandHandler < DeleteBaseCommand < TModel > , TModel > { public TModel Handle ( DeleteBaseCommand < TModel > command ) { // delete the thing return default ( TModel ) ; } } public class Program { private static Container container ; static void Main ( string [ ] args ) { container = new Container ( ) ; // Order does not seem to matter , I 've tried both ways . container.RegisterOpenGeneric ( typeof ( ICommandHandler < , > ) , typeof ( DeleteCommandBaseHandler < > ) ) ; container.RegisterOpenGeneric ( typeof ( ICommandHandler < , > ) , typeof ( CreateCommandBaseHandler < > ) ) ; container.Verify ( ) ; // So I want to make the usual hello world var commandToProcess = new CreateBaseCommand < string > { ItemToCreate = `` hello world '' } ; // Send it away ! Send ( commandToProcess ) ; } private static void Send < TResult > ( ICommand < TResult > commandToProcess ) { // { CreateBaseCommand ` 1 [ [ System.String , ... '' } var command = commandToProcess.GetType ( ) ; // { Name = `` String '' FullName = `` System.String '' } var resultType = typeof ( TResult ) ; // '' ICommandHandler ` 2 [ [ CreateBaseCommand ` 1 [ [ System.String , ... '' } // so it 's the right type here var type = typeof ( ICommandHandler < , > ) .MakeGenericType ( command , resultType ) ; // This is where we break ! var instance = container.GetInstance ( type ) ; // The supplied type DeleteCommandBaseHandler < String > does not implement // ICommandHandler < CreateBaseCommand < String > , String > . // Parameter name : implementationType } }
RegisterOpenGeneric with SimpleInjector resolves incorrect type
C_sharp : Related question : Accessing a Class property without using dot operatorI 've created a class called MyDouble looks like thisI am able to do all kinds of operations on MyDouble . Examples : However , this still throws an errorHow can I define it such that an operation like ( Int64 ) a automatically converts to ( Int64 ) a.value ? I do n't want the user to ever have to worry about the existence of the value property . <code> class MyDouble { double value ; //overloaded operators and methods } MyDouble a = 5.0 ; a += 3.0 ; ... etc MyDouble a = 5.0 ; long b = ( Int64 ) a ; //errorlong b = ( int64 ) a.value ; //works
Casting my Class to Int64 , Double etc
C_sharp : Hopefully someone can explain this to me . Sorry if it 's a repeat , the keywords to explain what I 'm seeing are beyond me for now..here is some code that compilesand here is some code that does notBy adding the constructor overload , this apparently creates ambiguity but I 'm not sure why . Math.Sqrt is not overloaded and clearly has a return type of double , not Task < double > .Here is the error : The call is ambiguous between the following methods or properties : 'ConsoleApplication1.Transformer < double , double > .Transformer ( System.Func < double , double > ) ' and 'ConsoleApplication1.Transformer < double , double > .Transformer ( System.Func < double , System.Threading.Tasks.Task < double > > ) 'Can someone explain why the choice is not obvious to the compiler ? Easy workaround for those who care : <code> class Program { static void Main ( string [ ] args ) { new Transformer < double , double > ( Math.Sqrt ) ; } } class Transformer < Tin , Tout > { Func < Tin , Task < Tout > > actor ; public Transformer ( Func < Tin , Tout > actor ) { this.actor = input = > Task.Run < Tout > ( ( ) = > actor ( input ) ) ; } } class Program { static void Main ( string [ ] args ) { new Transformer < double , double > ( Math.Sqrt ) ; } } public class Transformer < Tin , Tout > { Func < Tin , Task < Tout > > actor ; public Transformer ( Func < Tin , Tout > actor ) { this.actor = input = > Task.Run < Tout > ( ( ) = > actor ( input ) ) ; } public Transformer ( Func < Tin , Task < Tout > > actor ) { this.actor = actor ; } } class Program { static void Main ( string [ ] args ) { new Transformer < double , double > ( d = > Math.Sqrt ( d ) ) ; } }
C # Call is Ambiguous when passing a method group as delegate
C_sharp : In the example below , is there a way for a method of the implementing class to explicitly tell the compiler which interface member it implements ? I know it 's possible to resolve ambiguity between interfaces , but here it is within one interface . <code> interface IFoo < A , B > { void Bar ( A a ) ; void Bar ( B b ) ; } class Foo : IFoo < string , string > { public void Bar ( string a ) { } public void Bar ( string b ) { } // ambiguous signature }
How to resolve ambiguous interface method signatures , occuring when multiple generic type arguments are identical
C_sharp : I have this code : When I run the code in a Console Application , everything works fine , stream.IsAuthenticated and stream.IsMutuallyAuthenticated return true and stream.LocalCertificate contains the correct certificate object.However when running the exact same code in a Windows Service ( as LOCAL SYSTEM user ) , although stream.IsAuthenticated returns true , stream.IsMutuallyAuthenticated returns false and stream.LocalCertificate returns null.This happens while in both scenarios , after the first line is ran clientCertificate loads the correct certification data and contains the correct information for Certificate 's Subject and Issuer.I have also tried forcing the SslStream to pick the Certificate using this code : However the code still does n't work and stream.IsMutuallyAuthenticated returns false and stream.LocalCertificate returns null.I have been exploring this for a few days now and I ca n't figure it out . Any help is highly appreciated.Edit : After trying the certificate with WinHttpCertCfg tool it turns out that unlike similar question ( s ) , LOCAL SYSTEM account already has access to the private key for the target certificate as you can see in the picture below : Therefore the problem still remains unsolved . <code> string certificateFilePath = @ '' C : \Users\Administrator\Documents\Certificate.pfx '' ; string certificateFilePassword = `` Some Password Here '' ; X509Certificate clientCertificate = new X509Certificate ( certificateFilePath , certificateFilePassword ) ; TcpClient client = new TcpClient ( host , port ) ; SslStream stream = new SslStream ( client.GetStream ( ) , false , ( sender , certificate , chain , errors ) = > true ) ; X509CertificateCollection clientCertificates = new X509CertificateCollection { clientCertificate } ; stream.AuthenticateAsClient ( host , clientCertificates , SslProtocols.Tls , false ) ; string certificateFilePath = @ '' C : \Users\Administrator\Documents\Certificate.pfx '' ; string certificateFilePassword = `` Some Password Here '' ; X509Certificate clientCertificate = new X509Certificate ( certificateFilePath , certificateFilePassword ) ; TcpClient client = new TcpClient ( host , port ) ; SslStream stream = new SslStream ( client.GetStream ( ) , false , ( sender , certificate , chain , errors ) = > true , ( sender , host , certificates , certificate , issuers ) = > clientCertificate ) ; X509CertificateCollection clientCertificates = new X509CertificateCollection { clientCertificate } ; stream.AuthenticateAsClient ( host , clientCertificates , SslProtocols.Tls , false ) ;
SslStream Authentication fails under LOCAL SYSTEM account
C_sharp : I have a simple question for you ( i hope ) : ) I have pretty much always used void as a `` return '' type when doing CRUD operations on data.Eg . Consider this code : and then considen this code : It actually just comes down to whether you should notify that something was inserted ( and went well ) or not ? <code> public void Insert ( IAuctionItem item ) { if ( item == null ) { AuctionLogger.LogException ( new ArgumentNullException ( `` item is null '' ) ) ; } _dataStore.DataContext.AuctionItems.InsertOnSubmit ( ( AuctionItem ) item ) ; _dataStore.DataContext.SubmitChanges ( ) ; } public bool Insert ( IAuctionItem item ) { if ( item == null ) { AuctionLogger.LogException ( new ArgumentNullException ( `` item is null '' ) ) ; } _dataStore.DataContext.AuctionItems.InsertOnSubmit ( ( AuctionItem ) item ) ; _dataStore.DataContext.SubmitChanges ( ) ; return true ; }
CRUD operations ; do you notify whether the insert , update etc . went well ?
C_sharp : I 'm trying to figure out how to properly pass properties through multiple classes . I know I can just implement INotifyPropertyChanged in each class and listen for changes on the property , but this seems to be quite a lot of unnecessary code.The situation : I have a class ( let 's call it Class1 ) with two dependency properties : FilterStatement ( String ) and Filter ( Filter class ) . Setting the statement affects the filter and vice versa . The conversion logic between statement and filter , however , is n't located in Class1 , but in Class3 - which Class1 does n't know directly . In between there is Class2 which just has to pass through the changes . ( You can imagine class 1 to 3 beeing Viewmodel , Model and Repository , though in the real situation this does n't completly match ) . My naive solution would be to duplicate the properties across all three classes , implement INotifyPropertyChanged in Class2 and Class3 and listen to the changes , propagating everything down to Class3 and in Result back up to Class1 . Is n't there a better solution to this ? <code> public class Class1 { public static readonly DependencyProperty FilterProperty = DependencyProperty.Register ( `` Filter '' , typeof ( Filter ) , typeof ( Class1 ) , new FrameworkPropertyMetadata ( null ) ) ; public static readonly DependencyProperty FilterStatementProperty = DependencyProperty.Register ( `` FilterStatement '' , typeof ( String ) , typeof ( Class1 ) , new FrameworkPropertyMetadata ( null ) ) ; public Filter Filter { get { return ( Filter ) GetValue ( FilterProperty ) ; } set { SetValue ( FilterProperty , value ) ; } } public string FilterStatement { get { return ( string ) GetValue ( FilterStatementProperty ) ; } set { SetValue ( FilterStatementProperty , value ) ; } } public Class2 MyClass2Instance { get ; set ; } } public class Class2 { public Class3 MyClass3Instance { get ; set ; } public void ChangeClass3Instance ( object someParam ) { ... // this can change the instance of MyClass3Instance and is called frome somewhere else // when changed , the new Class3 instance has to get the property values of Class1 } } public class Class3 { private Filter _filter ; // here is where the filter set in Class 1 or determined by the statement set in class 1 has to be put public string MyFilterToStatementConversionMemberFunction ( Filter filter ) { ... } public Filter MyStatementToFilterConversionMemberFunction ( string statement ) { ... } }
Propagate property changes through multiple classes
C_sharp : I have a collection of variables in my viewmodel : The ObservableVariable class has two properties : string Name , and bool Selected ; the class implements INotifyPropertyChanged , My goal is to have this collection bound to a checklist in a WPF view , and to have a 'select all ' checkbox bound to that list implemented using MultiBinding . The following image illustrates the desired view.Observe the XAML below : The LogicalOrConverter takes any number of bools ; if any are true , return true . As you can see above each checkbox is bound to a variable in the viewmodel and the state of the 'select all ' checkbox . Currently , everything works as desired EXCEPT the following : If I click 'Select All , ' the checkboxes update in the view , but the change does NOT propagate back to the viewmodel.Note , most things in my implementation work correctly . For example , if I click an individual checkbox , the viewmodel is updated correctly . The problem in more detail : When I click an individual checkbox the OnPropertyChanged event is fired in the variable whose box was just changed ; the ConvertBack function in the converter is fired ; the viewmodel is updated and all is well.However , when I click the `` Select All '' checkbox , the individual checkboxes are updated in the view , but OnPropertyChanged is not called in any variable , and the ConvertBack function in the converter is not called . Also relevent , if I uncheck `` Select All , '' the individual checks go back to what they were before . The only way to update the viewmodel is to click in the individual checkboxes . However , the multibinding works for the purposes of the view . My question is : Why are n't changes to the checkbox propagated to the source collection in the viewmodelThe converter : ObservableVariable definition : <code> public ObservableCollection < ObservableVariable > Variables { get ; } = new ObservableCollection < ObservableVariable > ( ) ; < CheckBox Content= '' Select All '' Name= '' SelectAllCheckbox '' > < /CheckBox > ... < ListBox ItemsSource= '' { Binding Variables } '' > < ListBox.ItemTemplate > < DataTemplate > < CheckBox Content= '' { Binding Name } '' > < CheckBox.IsChecked > < MultiBinding Converter= '' { StaticResource LogicalOrConverter } '' Mode= '' TwoWay '' > < Binding Path= '' Selected '' > < /Binding > < Binding ElementName= '' SelectAllCheckbox '' Path= '' IsChecked '' > < /Binding > < /MultiBinding > < /CheckBox.IsChecked > < /CheckBox > < /DataTemplate > < /ListBox.ItemTemplate > < /ListBox > public class LogicalOrConverter : IMultiValueConverter { public object Convert ( object [ ] values , Type targetType , object parameter , CultureInfo culture ) { foreach ( object arg in values ) { if ( ( arg is bool ) & & ( bool ) arg == true ) { return true ; } } return false ; } public object [ ] ConvertBack ( object value , Type [ ] targetTypes , object parameter , CultureInfo culture ) { object [ ] values = new object [ 2 ] { false , false } ; if ( value is bool & & ( bool ) value == true ) values [ 0 ] = true ; return values ; } } public class ObservableVariable : INotifyPropertyChanged { private string _name ; public string Name { get { return _name ; } set { _name = value ; OnPropertyChanged ( nameof ( Name ) ) ; } } private bool _selected ; public bool Selected { get { return _selected ; } set { _selected = value ; OnPropertyChanged ( nameof ( Selected ) ) ; } } public event PropertyChangedEventHandler PropertyChanged ; protected virtual void OnPropertyChanged ( string propertyName = null ) { PropertyChanged ? .Invoke ( this , new PropertyChangedEventArgs ( propertyName ) ) ; } }
WPF Multibinding not Updating Source when Expected ; Checkboxes with 'Select All '
C_sharp : I am binding DataGrid.ItemsSource property to the List < PersonDetails > object . I am getting datas through Silverlight-enabled WCF Service . So the PersonDetails class is implemented in Web Project . Each DataGrid 's header text is changing as i want if the class is located in Silverlight project . But then I can not use this class in the web service . The only solution is to add same class in to the both of the projects . But , is there any other way ? The class looks like that : It seems attributes are n't generated in web project . I know that I can change header text using DataGrid events . But i want to make it work using attributes . <code> [ DataContract ] public class PersonGeneralDetails { // Properties [ DataMember ] [ DisplayAttribute ( Name = `` Sira '' ) ] public int RowNumber { get ; set ; } [ DataMember ] [ DisplayAttribute ( Name = `` Seriyasi '' ) ] public string SerialNumber { get ; set ; } }
DisplayAttribute name property not working in Silverlight
C_sharp : From my recent question , I try to centralize the domain model by including some silly logic in domain interface . However , I found some problem that need to include or exclude some properties from validating.Basically , I can use expression tree like the following code . Nevertheless , I do not like it because I need to define local variable ( `` u '' ) each time when I create lambda expression . Do you have any source code that is shorter than me ? Moreover , I need some method to quickly access selected properties.Thanks , <code> public void IncludeProperties < T > ( params Expression < Func < IUser , object > > [ ] selectedProperties ) { // some logic to store parameter } IncludeProperties < IUser > ( u = > u.ID , u = > u.LogOnName , u = > u.HashedPassword ) ;
What 's the best way to define & access selected properties in C # ?
C_sharp : I 'm trying to get a list of items to update whenever a message is received from a message queue.This only seems to work every other time a message is received though . It 's definitely hitting the anonymous method inside the SubscribeAsync call each time , and I ca n't work out why it 's not updating every time . I 'm assuming it 's related to that anonymous method being in a different thread . Any ideas what I 'm doing wrong ? <code> @ page `` / '' @ inject IMessageQueueHelperFactory MessageQueueHelperFactory @ inject ILogger < Index > Logger @ using Microsoft.Extensions.Logging @ using Newtonsoft.Json < ul class= '' list-group '' > @ foreach ( var user in Users ) { < li class= '' list-group-item '' > @ user < /li > } < /ul > @ code { private List < string > Users { get ; set ; } = new List < string > ( ) ; protected override void OnInitialized ( ) { MessageQueueHelperFactory.Create ( Queues.UserRegistration ) .SubscribeAsync ( async x = > { var user = JsonConvert.DeserializeObject < UserRegistrationData > ( x ) ; Users.Add ( user.Username ) ; await InvokeAsync ( StateHasChanged ) ; } ) ; base.OnInitialized ( ) ; } }
Update list of items in Blazor from another thread
C_sharp : So I have run into an interesting problem where I am getting duplicate keys in C # Dictionary when using a key of type PhysicalAddress . It is interesting because it only happens after a very long period of time , and I can not reproduce it using the same code in a unit test on a completely different machine . I can reproduce it reliably on a Windows XP SP3 machine but only after letting it run for days at a time , and even then it only occurs once.Below is the code that I am using and beneath that is the log output for that part of the code.Code : And process messages is used as follows : GetFromTagReports CodeWhere Physical Address is createdNote the following : Every 'Tag ' in messages.Tags contains a 'new ' PhysicalAddress.Each TagData that is returned is also 'new'.The 'tagRules ' methods do not modify the passed in 'tag ' in any way.Individual testing with trying to put two instances of a PhysicalAddress ( that were created from the same bytes ) into a Dictionary throws a 'KeyAlreadyExists ' exception.I also tried TryGetValue and it produced the same result.Log output where everything was fine : Log output where we get a duplicate key : Notice that everything is happening on a single thread ( see the [ 8 ] ) so there is no chance of the dictionary having been concurrently modified . The excerpts are from the same log and the same process instance . Also notice that in the second set of logs we end up with two keys that are the same ! What I am looking into : I have changed PhysicalAddress to a string to see if I can eliminate that from the list of suspects.My questions are : Is there a problem that I 'm not seeing in the code above ? Is there a problem with the equality methods on PhysicalAddress ? ( That only error every now and then ? ) Is there a problem with the Dictionary ? <code> private void ProcessMessages ( ) { IDictionary < PhysicalAddress , TagData > displayableTags = new Dictionary < PhysicalAddress , TagData > ( ) ; while ( true ) { try { var message = incomingMessages.Take ( cancellationToken.Token ) ; VipTagsDisappeared tagsDisappeared = message as VipTagsDisappeared ; if ( message is VipTagsDisappeared ) { foreach ( var tag in tagDataRepository.GetFromTagReports ( tagsDisappeared.Tags ) ) { log.DebugFormat ( CultureInfo.InvariantCulture , `` Lost tag { 0 } '' , tag ) ; RemoveTag ( tag , displayableTags ) ; } LogKeysAndValues ( displayableTags ) ; PublishCurrentDisplayableTags ( displayableTags ) ; } else if ( message is ClearAllTags ) { displayableTags.Clear ( ) ; eventAggregator.Publish ( new TagReaderError ( ) ) ; } else if ( message is VipTagsAppeared ) { foreach ( TagData tag in tagDataRepository.GetFromTagReports ( message.Tags ) ) { log.DebugFormat ( CultureInfo.InvariantCulture , `` Detected tag ( { 0 } ) with Exciter Id ( { 1 } ) '' , tag.MacAddress , tag.ExciterId ) ; if ( tagRules.IsTagRssiWithinThreshold ( tag ) & & tagRules.IsTagExciterValid ( tag ) ) { log.DebugFormat ( CultureInfo.InvariantCulture , `` Detected tag is displayable ( { 0 } ) '' , tag ) ; bool elementAlreadyExists = displayableTags.ContainsKey ( tag.MacAddress ) ; if ( elementAlreadyExists ) { displayableTags [ tag.MacAddress ] .Rssi = tag.Rssi ; } else { displayableTags.Add ( tag.MacAddress , tag ) ; } } else { log.DebugFormat ( CultureInfo.InvariantCulture , `` Detected tag is not displayable ( { 0 } ) '' , tag ) ; RemoveTag ( tag , displayableTags ) ; } } LogKeysAndValues ( displayableTags ) ; PublishCurrentDisplayableTags ( displayableTags ) ; } else { log.WarnFormat ( CultureInfo.InvariantCulture , `` Received message of unknown type { 0 } . `` , message.GetType ( ) ) ; } } catch ( OperationCanceledException ) { break ; } } } private void PublishCurrentDisplayableTags ( IDictionary < PhysicalAddress , TagData > displayableTags ) { eventAggregator.Publish ( new CurrentDisplayableTags ( displayableTags.Values.Distinct ( ) .ToList ( ) ) ) ; } private void RemoveTag ( TagData tag , IDictionary < PhysicalAddress , TagData > displayableTags ) { displayableTags.Remove ( tag.MacAddress ) ; // Now try to remove any duplicates and if there are then log it out bool removalWasSuccesful = displayableTags.Remove ( tag.MacAddress ) ; while ( removalWasSuccesful ) { log.WarnFormat ( CultureInfo.InvariantCulture , `` Duplicate tag removed from dictionary : { 0 } '' , tag.MacAddress ) ; removalWasSuccesful = displayableTags.Remove ( tag.MacAddress ) ; } } private void LogKeysAndValues ( IDictionary < PhysicalAddress , TagData > displayableTags ) { log.TraceFormat ( CultureInfo.InvariantCulture , `` Keys '' ) ; foreach ( var physicalAddress in displayableTags.Keys ) { log.TraceFormat ( CultureInfo.InvariantCulture , `` Address : { 0 } '' , physicalAddress ) ; } log.TraceFormat ( CultureInfo.InvariantCulture , `` Values '' ) ; foreach ( TagData physicalAddress in displayableTags.Values ) { log.TraceFormat ( CultureInfo.InvariantCulture , `` Address : { 0 } Name : { 1 } '' , physicalAddress.MacAddress , physicalAddress.Name ) ; } } Thread processingThread = new Thread ( ProcessMessages ) ; public IEnumerable < TagData > GetFromTagReports ( IEnumerable < TagReport > tagReports ) { foreach ( var tagReport in tagReports ) { TagData tagData = GetFromMacAddress ( tagReport.MacAddress ) ; tagData.Rssi = tagReport.ReceivedSignalStrength ; tagData.ExciterId = tagReport.ExciterId ; tagData.MacAddress = tagReport.MacAddress ; tagData.Arrived = tagReport.TimeStamp ; yield return tagData ; } } public TagData GetFromMacAddress ( PhysicalAddress macAddress ) { TagId physicalAddressToTagId = TagId.Parse ( macAddress ) ; var personEntity = personFinder.ByTagId ( physicalAddressToTagId ) ; if ( personEntity.Person ! = null & & ! ( personEntity.Person is UnknownPerson ) ) { return new TagData ( TagType.Person , personEntity.Person.Name ) ; } var tagEntity = tagFinder.ByTagId ( physicalAddressToTagId ) ; if ( TagId.Invalid == tagEntity.Tag ) { return TagData.CreateUnknownTagData ( macAddress ) ; } var equipmentEntity = equipmentFinder.ById ( tagEntity.MineSuiteId ) ; if ( equipmentEntity.Equipment ! = null & & ! ( equipmentEntity.Equipment is UnknownEquipment ) ) { return new TagData ( TagType.Vehicle , equipmentEntity.Equipment.Name ) ; } return TagData.CreateUnknownTagData ( macAddress ) ; } var physicalAddressBytes = new byte [ 6 ] ; ByteWriter.WriteBytesToBuffer ( physicalAddressBytes , 0 , protocolDataUnit.Payload , 4 , 6 ) ; var args = new TagReport { Version = protocolDataUnit.Version , MacAddress = new PhysicalAddress ( physicalAddressBytes ) , BatteryStatus = protocolDataUnit.Payload [ 10 ] , ReceivedSignalStrength = IPAddress.NetworkToHostOrder ( BitConverter.ToInt16 ( protocolDataUnit.Payload , 12 ) ) , ExciterId = IPAddress.NetworkToHostOrder ( BitConverter.ToInt16 ( protocolDataUnit.Payload , 14 ) ) } ; public static void WriteBytesToBuffer ( byte [ ] oldValues , int oldValuesStartindex , byte [ ] newValues , int newValuesStartindex , int max ) { var loopmax = ( max > newValues.Length || max < 0 ) ? newValues.Length : max ; for ( int i = 0 ; i < loopmax ; ++i ) { oldValues [ oldValuesStartindex + i ] = newValues [ newValuesStartindex + i ] ; } } 2013-04-26 18:28:34,347 [ 8 ] DEBUG ClassName - Detected tag ( 000CCC756081 ) with Exciter Id ( 0 ) 2013-04-26 18:28:34,347 [ 8 ] DEBUG ClassName - Detected tag is displayable ( Unknown : ? 56081 ) 2013-04-26 18:28:34,347 [ 8 ] TRACE ClassName - Keys2013-04-26 18:28:34,347 [ 8 ] TRACE ClassName - Address : 000CCC7558982013-04-26 18:28:34,347 [ 8 ] TRACE ClassName - Address : 000CCC7560812013-04-26 18:28:34,347 [ 8 ] TRACE ClassName - Address : 000CCC755A272013-04-26 18:28:34,347 [ 8 ] TRACE ClassName - Address : 000CCC755B472013-04-26 18:28:34,347 [ 8 ] TRACE ClassName - Values2013-04-26 18:28:34,347 [ 8 ] TRACE ClassName - Address : 000CCC755898 Name : Scotty McTester2013-04-26 18:28:34,347 [ 8 ] TRACE ClassName - Address : 000CCC756081 Name : ? 560812013-04-26 18:28:34,347 [ 8 ] TRACE ClassName - Address : 000CCC755A27 Name : JDTest12013-04-26 18:28:34,347 [ 8 ] TRACE ClassName - Address : 000CCC755B47 Name : 33 12013-04-26 18:28:34,347 [ 8 ] TRACE ClassName - Current tags : Scotty McTester , ? 56081 , JDTest1 , 33 1 2013-04-26 18:28:35,608 [ 8 ] DEBUG ClassName - Detected tag ( 000CCC756081 ) with Exciter Id ( 0 ) 2013-04-26 18:28:35,608 [ 8 ] DEBUG ClassName - Detected tag is displayable ( Unknown : ? 56081 ) 2013-04-26 18:28:35,608 [ 8 ] TRACE ClassName - Keys2013-04-26 18:28:35,608 [ 8 ] TRACE ClassName - Address : 000CCC7558982013-04-26 18:28:35,608 [ 8 ] TRACE ClassName - Address : 000CCC7560812013-04-26 18:28:35,618 [ 8 ] TRACE ClassName - Address : 000CCC755A272013-04-26 18:28:35,618 [ 8 ] TRACE ClassName - Address : 000CCC755B472013-04-26 18:28:35,618 [ 8 ] TRACE ClassName - Address : 000CCC7560812013-04-26 18:28:35,618 [ 8 ] TRACE ClassName - Values2013-04-26 18:28:35,618 [ 8 ] TRACE ClassName - Address : 000CCC755898 Name : Scotty McTester2013-04-26 18:28:35,618 [ 8 ] TRACE ClassName - Address : 000CCC756081 Name : ? 560812013-04-26 18:28:35,648 [ 8 ] TRACE ClassName - Address : 000CCC755A27 Name : JDTest12013-04-26 18:28:35,648 [ 8 ] TRACE ClassName - Address : 000CCC755B47 Name : 33 12013-04-26 18:28:35,648 [ 8 ] TRACE ClassName - Address : 000CCC756081 Name : ? 560812013-04-26 18:28:35,648 [ 8 ] TRACE ClassName - Current tags : Scotty McTester , ? 56081 , JDTest1 , 33 1 , ? 56081
Duplicate keys in Dictionary when using PhysicalAddress as the key
C_sharp : Hello fellow StackOverflow users ( or Stackoverflowers ? ) : I 'm learning-by-coding WPF . I read several articles/saw several screencasts , and coming from a WEB dev background , I fired up VS2010 and started doing a sample application that would help me learn the basics.I read some about MVVM too , and started using it . I set up my solution to use WPF 4.0 , ActiveRecord 2.1 and SQLite , and everything went kind well . But I still have some doubts : I created a MainWindowViewModel , and am using the RelayCommand class from here to ... relay the command . Am I breaking any guidelines by having a MenuItem from the MainWindow to have its command bound to a property of this viewmodel ? This action I 'm binding the MenuItem command to is going to instantiate a new ViewModel and a new View , and show it . Again , is that ok in the MVVM context ? My MainWindow will be a kind of `` dashboard '' , and I will have more than one model attached to this dashboard . Should I just wrap all those models in a single view model ? Something like this : TIA ! <code> public class MainWindowViewModel { private ObservableCollection < Order > openOrders ; private Address deliveryAddress ; private Order newOrder ; /* Wrappers for the OpenOrders Collection */ /* Wrappers for Delivery Address */ /* Wrappers for New Order */ /* Command Bindings */ }
WPF MVVM Doubts
C_sharp : Given the following class , how would you go about writing a unit test for it ? I have read that any test that does file IO is not a unit test , so is this an integration test that needs to be written ? I am using xUnit and MOQ for testing and I am very new to it , so maybe I could MOQ the file ? Not sure . <code> public class Serializer { public static T LoadFromXmlFile < T > ( string path ) where T : class { var serializer = new XmlSerializer ( typeof ( T ) ) ; using ( var reader = new StreamReader ( path ) ) { return serializer.Deserialize ( reader ) as T ; } } public static void SaveToXmlFile < T > ( T instance , string path ) { var serializer = new XmlSerializer ( typeof ( T ) ) ; using ( var writer = new StreamWriter ( path ) ) { serializer.Serialize ( writer , instance ) ; writer.Flush ( ) ; } } }
How do you test code that does file IO ?
C_sharp : I have an SQL connection service that I 'm trying to build . I essentially do this : DoStuffWithSqlAsync operates like this : And RunQueryAsync operates like this : The problem I 'm running into is that DoStuffWithSqlAsync continuously fails with a System.InvalidOperationException stating that conn is in a closed state . However , when I examine the stack trace , I find execution is still inside the using statement . I also know that conn is not closed anywhere inside this operation as execution must necessarily return to the statement and any exception inside should be bubbled up to the enclosing try-catch and caught there . Additionally , the connection is pooled and MARS is enabled . So then , why is this being closed ? UPDATE : It was pointed out that I had n't opened my connection . I have done so but the error persists except now _conn.State is set to Open.UPDATE : I was having an issue wherein I used await conn.OpenAsync.ConfigureAwait ( false ) ; which would not block execution . So , when I tried to connect to the database , I would get an exception stating that the connection state was closed but by that point it would have opened so on examination it would show Open . It was suggested that I make the calling method async void but as the application is console , not UI I do n't think that will help . I have since reverted to using the synchronous method . <code> var data = await GetDataFromFlatFilesAsync ( dir ) .ConfigureAwait ( false ) ; using ( var conn = new SqlConnection ( MyConnectionString ) ) { try { conn.Open ( ) ; var rw = new SqlReaderWriter ( conn ) ; await DoStuffWithSqlAsync ( rw , data ) .ConfigureAwait ( false ) ; } catch ( Exception ex ) { // Do exceptional stuff here } } private async Task DoStuffWithSqlAsync ( SqlReaderWriter rw , IEnumerable < Thing > data ) { await Task.WhenAll ( data.Select ( rw.RunQueryAsync ) ) .ConfigureAwait ( false ) ; } public async Task RunQueryAsync < T > ( T content ) { // _conn is assigned to in the constructor with conn try { var dataQuery = _conn.CreateCommand ( ) ; dataQuery.CommandText = TranslateContentToQuery ( content ) ; await dataQuery.ExecuteNonQueryAsync ( ) .ConfigureAwait ( false ) ; } catch ( Exception ex ) { // Do exceptional stuff here } }
SqlConnection closes unexpectedly inside using statement
C_sharp : In C # 5 , they introduced the Caller Info attributes . One of the useful applications is , quite obviously , logging . In fact , their example given is exactly that : I am currently developing an application and I am at the point where I would like to introduce the usage of the caller info in my logging routines . Assume that I had the relatively simple logging interface of : Normally , I 'd use Moq to verify the behavior I desire : That 's all fine . Now I 'd like to modify my logging interface such that it accepts caller info parameters : For brevity , you can assume the implementation is similar to the TraceMessage example above . I ca n't simply create and verify my mock as above . The compiler error I receive is : An expression tree may not contain a call or invocation that uses optional argumentsThe only way around this is to use the It.IsAny < T > matcher in Moq : Unfortunately , I ca n't assert or verify that the call site looks the way I expect it to : Which brings me to my question : How can I verify the behavior of Caller Info attributes in a unit test ? I do n't particularly like the It.IsAny < T > hack . I can write the unit test , run through a red-green cycle and all is well until someone tries to modify it . Then , someone can come along and modify my implementation to contain erroneous parameters and the test will still pass.SolutionBased on Herr Kater 's answer , I was able to wrap the caller information into a utility class with the following method : I could then inject this dependency into my code and verify that the logger implementation was properly using it . My callers can now be properly tested if they are using the logging correctly . <code> public void TraceMessage ( string message , [ CallerMemberName ] string memberName = `` '' , [ CallerFilePath ] string sourceFilePath = `` '' , [ CallerLineNumber ] int sourceLineNumber = 0 ) { Trace.WriteLine ( `` message : `` + message ) ; Trace.WriteLine ( `` member name : `` + memberName ) ; Trace.WriteLine ( `` source file path : `` + sourceFilePath ) ; Trace.WriteLine ( `` source line number : `` + sourceLineNumber ) ; } public interface ILogger { void Info ( String message ) ; } // Arrangevar logger = new Mock < ILogger > ( ) ; var sut = new SystemUnderTest ( logger.Object ) ; // Actsut.DoIt ( ) ; // Assertlogger.Verify ( log = > log.Info ( `` DoIt was called '' ) ) ; public interface ILogger { void Info ( String message , [ CallerMemberName ] string memberName = `` '' , [ CallerFilePath ] string sourceFilePath = `` '' , [ CallerLineNumber ] int sourceLineNumber = 0 ) ; } // Arrangevar logger = new Mock < ILogger > ( ) ; var sut = new SystemUnderTest ( logger.Object ) ; // Actsut.DoIt ( ) ; // Assertlogger.Verify ( log = > log.Info ( `` DoIt was called '' , It.IsAny < string > ( ) , It.IsAny < String > ( ) , It.IsAny < int > ( ) ) ) ; public void DoIt ( ) { // do hard work _logger.Info ( `` DoIt was called '' ) ; } public CallerInfo GetCallerInformation ( ) { var frame = new StackFrame ( 2 , true ) ; return new CallerInfo { FileName = frame.GetFileName ( ) , MethodName = frame.GetMethod ( ) .Name , LineNumber = frame.GetFileLineNumber ( ) } ; } // Arrangevar backingLog = new IMock < IBackingLog > ( ) ; var callerInfoUtility = new Mock < ICallerInfoUtility > ( ) ; var info = new CallerInfo { MethodName = `` Test '' , FileName = `` File '' , LineNumber = 123 } ; callerInfoUtility.Setup ( utility = > utility.GetCallerInformation ( ) ) .Returns ( info ) ; var logger = new Logger ( backingLog.Object , callerInfoUtility.Object ) ; // Actlogger.Log ( `` test '' ) ; // Assertlogger.Verify ( log = > log.Info ( `` test was called : Line 123 of Test in File '' ) ) ;
How I can I do TDD with Caller Info attributes ?
C_sharp : I read that when in a catch block , I can rethrow the current exception using `` throw ; '' or `` throw ex ; '' .From : http : //msdn.microsoft.com/en-us/library/ms182363 % 28VS.80 % 29.aspx '' To keep the original stack trace information with the exception , use the throw statement without specifying the exception . '' But when I try this withI get three different stacks . I was expecting the first and second trace to be the same . What am I doing wrong ? ( or understanding wrong ? ) System.Exception : test at ConsoleApplication1.Program.Main ( String [ ] args ) in c : \Program.cs : line 13System.Exception : test at ConsoleApplication1.Program.Main ( String [ ] args ) in c : \Program.cs : line 16System.Exception : test at ConsoleApplication1.Program.Main ( String [ ] args ) in c : \Program.cs : line 20 <code> try { try { try { throw new Exception ( `` test '' ) ; // 13 } catch ( Exception ex1 ) { Console.WriteLine ( ex1.ToString ( ) ) ; throw ; // 16 } } catch ( Exception ex2 ) { Console.WriteLine ( ex2.ToString ( ) ) ; // expected same stack trace throw ex2 ; // 20 } } catch ( Exception ex3 ) { Console.WriteLine ( ex3.ToString ( ) ) ; }
Why do `` throw '' and `` throw ex '' in a catch block behave the same way ?
C_sharp : I have a kind a simple question but I 'm surprised.This code works : Why do n't I have to do itemID.ToString ( ) in this case ? <code> int itemID = 1 ; string dirPath = @ '' C : \ '' + itemID + @ '' \abc '' ;
int to string without explicit conversion ?
C_sharp : The problem is this : I have a form that accepts a TextBox text and 2 buttons , one to save the text into the database and the other one to cancel and close the form . The form also has an ErrorProvider that 's used in the TextBox.Validating event like this : It does what is expected , to not let the user to do anything in the form until the required field is filled , except for 1 thing : to let the user close the form via the Cancel button.I tried comparing the object sender to the button cmdCancel but it 's not possible because the sender is always the TextBox.Any advice as to how to ignore the Validating event when the user clicks on cmdCancel ? <code> private void txtNombre_Validating ( object sender , CancelEventArgs e ) { string errorMsg ; if ( ! ValidateText ( txtNombre.Text , out errorMsg ) ) { // Cancel the event and select the text to be corrected by the user . e.Cancel = true ; txtNombre.Select ( 0 , txtNombre.Text.Length ) ; // Set the ErrorProvider error with the text to display . this.errorProvider1.SetError ( txtNombre , errorMsg ) ; } }
In a textbox validating event , how to ignore clicks to a certain button ?
C_sharp : Disclaimer : It is well known that catch ( ex ) { throw ex ; } is bad practice . This question is not about that.While digging through Microsoft reference sources , I noticed the following pattern in a lot of methods : No logging , no debugging code—just a plain simple catch { throw ; } .Since , obviously , the guys at Microsoft should be fairly proficient in the use of C # , what could be the point of doing that instead of just omitting the catch block ( and the try statement ) altogether ? Is there a technical reason for coding like this , or is it purely a stylistic choice ? Note : I do n't know if it is relevant , but all such instances I could find also contain a try-finally block nested inside the try clause of the try-catch block . <code> try { ... } catch { throw ; }
Is there any technical reason to write a catch block containing only a throw statement ?
C_sharp : I 'm trying to create a not in clause with the NHibernate Criteria API using NHLambdaExtensions . Reading the documentation I was able to implement the in clause by doingHowever , when I wrap it around SqlExpression.Not I get the errorI 'm using this piece of codeHow can I accomplish this ? Using the regular Criteria API I was able to do this <code> .Add ( SqlExpression.In < Zone > ( z = > zoneAlias.ZoneId , new int [ ] { 1008 , 1010 } ) ) Error 5 The best overloaded method match for 'NHibernate.LambdaExtensions.SqlExpression.Not < oms_dal.Models.Zone > ( System.Linq.Expressions.Expression < System.Func < oms_dal.Models.Zone , bool > > ) ' has some invalid argumentsError 6 Argument ' 1 ' : can not convert from 'NHibernate.Criterion.ICriterion ' to 'System.Linq.Expressions.Expression < System.Func < oms_dal.Models.Zone , bool > > ' .Add ( SqlExpression.Not < Zone > ( SqlExpression.In < Zone > ( x = > zoneAlias.ZoneId , new int [ ] { 1008 , 1010 } ) ) ) .Add ( Restrictions.Not ( Restrictions.In ( `` z.ZoneId '' , new [ ] { 1008 , 1010 } ) ) )
How do I express “ not in ” using lambdas ?
C_sharp : For a dynamic binary translation simulator , I need to generate collectible .NET assemblies with classes that access static fields . However , when using static fields inside collectible assemblies , execution performance is by factor of 2-3 lower compared to non-collectible assemblies . This phenomen is not present incollectible assemblies that do not use static fields.In the code below the method MyMethod of abstract class AbstrTest is implemented by collectible and non-collectible dynamic assemblies . Using CreateTypeConst the MyMethod multiplies the ulong argument value by a constant value of two , while using CreateTypeField the second factor is taken froma constructor initialized static field MyField.To obtain realistic results , the MyMethod results are accumulated in a for loop.Here are the measurement results ( .NET CLR 4.5/4.6 ) : Here is my reproducer code : So my question is : Why is it slower ? <code> Testing non-collectible const multiply : Elapsed : 8721.2867 msTesting collectible const multiply : Elapsed : 8696.8124 msTesting non-collectible field multiply : Elapsed : 10151.6921 msTesting collectible field multiply : Elapsed : 33404.4878 ms using System ; using System.Reflection ; using System.Reflection.Emit ; using System.Diagnostics ; public abstract class AbstrTest { public abstract ulong MyMethod ( ulong x ) ; } public class DerivedClassBuilder { private static Type CreateTypeConst ( string name , bool collect ) { // Create an assembly . AssemblyName myAssemblyName = new AssemblyName ( ) ; myAssemblyName.Name = name ; AssemblyBuilder myAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly ( myAssemblyName , collect ? AssemblyBuilderAccess.RunAndCollect : AssemblyBuilderAccess.Run ) ; // Create a dynamic module in Dynamic Assembly . ModuleBuilder myModuleBuilder = myAssembly.DefineDynamicModule ( name ) ; // Define a public class named `` MyClass '' in the assembly . TypeBuilder myTypeBuilder = myModuleBuilder.DefineType ( `` MyClass '' , TypeAttributes.Public , typeof ( AbstrTest ) ) ; // Create the MyMethod method . MethodBuilder myMethodBuilder = myTypeBuilder.DefineMethod ( `` MyMethod '' , MethodAttributes.Public | MethodAttributes.ReuseSlot | MethodAttributes.Virtual | MethodAttributes.HideBySig , typeof ( ulong ) , new Type [ ] { typeof ( ulong ) } ) ; ILGenerator methodIL = myMethodBuilder.GetILGenerator ( ) ; methodIL.Emit ( OpCodes.Ldarg_1 ) ; methodIL.Emit ( OpCodes.Ldc_I4_2 ) ; methodIL.Emit ( OpCodes.Conv_U8 ) ; methodIL.Emit ( OpCodes.Mul ) ; methodIL.Emit ( OpCodes.Ret ) ; return myTypeBuilder.CreateType ( ) ; } private static Type CreateTypeField ( string name , bool collect ) { // Create an assembly . AssemblyName myAssemblyName = new AssemblyName ( ) ; myAssemblyName.Name = name ; AssemblyBuilder myAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly ( myAssemblyName , collect ? AssemblyBuilderAccess.RunAndCollect : AssemblyBuilderAccess.Run ) ; // Create a dynamic module in Dynamic Assembly . ModuleBuilder myModuleBuilder = myAssembly.DefineDynamicModule ( name ) ; // Define a public class named `` MyClass '' in the assembly . TypeBuilder myTypeBuilder = myModuleBuilder.DefineType ( `` MyClass '' , TypeAttributes.Public , typeof ( AbstrTest ) ) ; // Define a private String field named `` MyField '' in the type . FieldBuilder myFieldBuilder = myTypeBuilder.DefineField ( `` MyField '' , typeof ( ulong ) , FieldAttributes.Private | FieldAttributes.Static ) ; // Create the constructor . ConstructorBuilder constructor = myTypeBuilder.DefineConstructor ( MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName | MethodAttributes.HideBySig , CallingConventions.Standard , Type.EmptyTypes ) ; ConstructorInfo superConstructor = typeof ( AbstrTest ) .GetConstructor ( BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance , null , Type.EmptyTypes , null ) ; ILGenerator constructorIL = constructor.GetILGenerator ( ) ; constructorIL.Emit ( OpCodes.Ldarg_0 ) ; constructorIL.Emit ( OpCodes.Call , superConstructor ) ; constructorIL.Emit ( OpCodes.Ldc_I4_2 ) ; constructorIL.Emit ( OpCodes.Conv_U8 ) ; constructorIL.Emit ( OpCodes.Stsfld , myFieldBuilder ) ; constructorIL.Emit ( OpCodes.Ret ) ; // Create the MyMethod method . MethodBuilder myMethodBuilder = myTypeBuilder.DefineMethod ( `` MyMethod '' , MethodAttributes.Public | MethodAttributes.ReuseSlot | MethodAttributes.Virtual | MethodAttributes.HideBySig , typeof ( ulong ) , new Type [ ] { typeof ( ulong ) } ) ; ILGenerator methodIL = myMethodBuilder.GetILGenerator ( ) ; methodIL.Emit ( OpCodes.Ldarg_1 ) ; methodIL.Emit ( OpCodes.Ldsfld , myFieldBuilder ) ; methodIL.Emit ( OpCodes.Mul ) ; methodIL.Emit ( OpCodes.Ret ) ; return myTypeBuilder.CreateType ( ) ; } public static void Main ( ) { ulong accu ; Stopwatch stopwatch ; try { Console.WriteLine ( `` Testing non-collectible const multiply : '' ) ; AbstrTest i0 = ( AbstrTest ) Activator.CreateInstance ( CreateTypeConst ( `` MyClassModule0 '' , false ) ) ; stopwatch = Stopwatch.StartNew ( ) ; accu = 0 ; for ( uint i = 0 ; i < 0xffffffff ; i++ ) accu += i0.MyMethod ( i ) ; stopwatch.Stop ( ) ; Console.WriteLine ( `` Elapsed : `` + stopwatch.Elapsed.TotalMilliseconds + `` ms '' ) ; Console.WriteLine ( `` Testing collectible const multiply : '' ) ; AbstrTest i1 = ( AbstrTest ) Activator.CreateInstance ( CreateTypeConst ( `` MyClassModule1 '' , true ) ) ; stopwatch = Stopwatch.StartNew ( ) ; accu = 0 ; for ( uint i = 0 ; i < 0xffffffff ; i++ ) accu += i1.MyMethod ( i ) ; stopwatch.Stop ( ) ; Console.WriteLine ( `` Elapsed : `` + stopwatch.Elapsed.TotalMilliseconds + `` ms '' ) ; Console.WriteLine ( `` Testing non-collectible field multiply : '' ) ; AbstrTest i2 = ( AbstrTest ) Activator.CreateInstance ( CreateTypeField ( `` MyClassModule2 '' , false ) ) ; stopwatch = Stopwatch.StartNew ( ) ; accu = 0 ; for ( uint i = 0 ; i < 0xffffffff ; i++ ) accu += i2.MyMethod ( i ) ; stopwatch.Stop ( ) ; Console.WriteLine ( `` Elapsed : `` + stopwatch.Elapsed.TotalMilliseconds + `` ms '' ) ; Console.WriteLine ( `` Testing collectible field multiply : '' ) ; AbstrTest i3 = ( AbstrTest ) Activator.CreateInstance ( CreateTypeField ( `` MyClassModule3 '' , true ) ) ; stopwatch = Stopwatch.StartNew ( ) ; accu = 0 ; for ( uint i = 0 ; i < 0xffffffff ; i++ ) accu += i3.MyMethod ( i ) ; stopwatch.Stop ( ) ; Console.WriteLine ( `` Elapsed : `` + stopwatch.Elapsed.TotalMilliseconds + `` ms '' ) ; } catch ( Exception e ) { Console.WriteLine ( `` Exception Caught `` + e.Message ) ; } } }
Static field access in collectible dynamic assemblies lacks performance
C_sharp : This is something I encountered while using the C # IList collectionsAs far as I know , in C # ( on the contrary of C++ ) when we create an object with this syntax , the object type get the right side ( assignment ) and not the left one ( declaration ) .Do I miss something here ! EDITI still do n't get it , even after your answers , foo and bar have the same type ! <code> IList < MyClass > foo = new List < MyClass > ( ) ; var bar = new List < MyClass > ( ) ; foo.AddRange ( ) // does n't compilebar.AddRange ( ) // compile
Object assignment in C #
C_sharp : I 've been at this for a few days now . My original ( and eventual ) goal was to use CommonCrypto on iOS to encrypt a password with a given IV and key , then successfully decrypt it using .NET . After tons of research and failures I 've narrowed down my goal to simply producing the same encrypted bytes on iOS and .NET , then going from there . I 've created simple test projects in .NET ( C # , framework 4.5 ) and iOS ( 8.1 ) . Please note the following code is not intended to be secure , but rather winnow down the variables in the larger process . Also , iOS is the variable here . The final .NET encryption code will be deployed by a client so it 's up to me to bring the iOS encryption in line . Unless this is confirmed impossible the .NET code will not be changed.The relevant .NET encryption code : The relevant iOS encryption code : The relevant code for passing the pass , key , and IV in .NET and printing result : The relevant code for passing the parameters and printing the result in iOS : Upon running the .NET code it prints out the following bytes after encryption : [ 0 ] 194 [ 1 ] 154 [ 2 ] 141 [ 3 ] 238 [ 4 ] 77 [ 5 ] 109 [ 6 ] 33 [ 7 ] 94 [ 8 ] 158 [ 9 ] 5 [ 10 ] 7 [ 11 ] 187 [ 12 ] 193 [ 13 ] 165 [ 14 ] 70 [ 15 ] 5 Conversely , iOS prints the following after encryption : [ 0 ] 77 [ 1 ] 213 [ 2 ] 61 [ 3 ] 190 [ 4 ] 197 [ 5 ] 191 [ 6 ] 55 [ 7 ] 230 [ 8 ] 150 [ 9 ] 144 [ 10 ] 5 [ 11 ] 253 [ 12 ] 253 [ 13 ] 158 [ 14 ] 34 [ 15 ] 138 I can not for the life of me determine what is causing this difference . Some things I 've already confirmed : Both iOS and .NET can successfully decrypt their encrypted data.The lines of code in the .NET project : aesAlg.Padding = PaddingMode.PKCS7 ; aesAlg.KeySize = 256 ; aesAlg.BlockSize = 128 ; Do not affect the result . They can be commented and the output is the same . I assume this means they are the default valus . I 've only left them in to make it obvious I 'm matching iOS 's encryption properties as closely as possible for this example.If I print out the bytes in the iOS NSData objects `` ivData '' and `` keyData '' it produces the same list of bytes that I created them with- so I do n't think this is a C < - > ObjC bridging problem for the initial parameters.If I print out the bytes in the iOS variable `` passData '' it prints the same single byte as .NET ( 88 ) . So I 'm fairly certain they are starting the encryption with the exact same data.Due to how concise the .NET code is I 've run out of obvious avenues of experimentation . My only thought is that someone may be able to point out a problem in my `` AES256EncryptData : withKey : iv : '' method . That code has been modified from the ubiquitous iOS AES256 code floating around because the key we are provided is a byte array- not a string . I 'm pretty studied at ObjC but not nearly as comfortable with the C nonsense- so it 's certainly possible I 've fumbled the required modifications.All help or suggestions would be greatly appreciated . <code> static byte [ ] EncryptStringToBytes_Aes ( string plainText , byte [ ] Key , byte [ ] IV ) { byte [ ] encrypted ; // Create an Aes object // with the specified key and IV . using ( Aes aesAlg = Aes.Create ( ) ) { aesAlg.Padding = PaddingMode.PKCS7 ; aesAlg.KeySize = 256 ; aesAlg.BlockSize = 128 ; // Create an encryptor to perform the stream transform . ICryptoTransform encryptor = aesAlg.CreateEncryptor ( Key , IV ) ; // Create the streams used for encryption . using ( MemoryStream msEncrypt = new MemoryStream ( ) ) { using ( CryptoStream csEncrypt = new CryptoStream ( msEncrypt , encryptor , CryptoStreamMode.Write ) ) { using ( StreamWriter swEncrypt = new StreamWriter ( csEncrypt ) ) { //Write all data to the stream . swEncrypt.Write ( plainText ) ; } encrypted = msEncrypt.ToArray ( ) ; } } } return encrypted ; } + ( NSData* ) AES256EncryptData : ( NSData * ) data withKey : ( NSData* ) key iv : ( NSData* ) ivector { Byte keyPtr [ kCCKeySizeAES256+1 ] ; // Pointer with room for terminator ( unused ) // Pad to the required sizebzero ( keyPtr , sizeof ( keyPtr ) ) ; // fetch key data [ key getBytes : keyPtr length : sizeof ( keyPtr ) ] ; // -- IV LOGICByte ivPtr [ 16 ] ; bzero ( ivPtr , sizeof ( ivPtr ) ) ; [ ivector getBytes : ivPtr length : sizeof ( ivPtr ) ] ; // Data lengthNSUInteger dataLength = data.length ; // See the doc : For block ciphers , the output size will always be less than or equal to the input size plus the size of one block.// That 's why we need to add the size of one block heresize_t bufferSize = dataLength + kCCBlockSizeAES128 ; void *buffer = malloc ( bufferSize ) ; size_t numBytesEncrypted = 0 ; CCCryptorStatus cryptStatus = CCCrypt ( kCCEncrypt , kCCAlgorithmAES128 , kCCOptionPKCS7Padding , keyPtr , kCCKeySizeAES256 , ivPtr , data.bytes , dataLength , buffer , bufferSize , & numBytesEncrypted ) ; if ( cryptStatus == kCCSuccess ) { return [ NSData dataWithBytesNoCopy : buffer length : numBytesEncrypted ] ; } free ( buffer ) ; return nil ; } byte [ ] c_IV = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 16 } ; byte [ ] c_Key = { 16 , 15 , 14 , 13 , 12 , 11 , 10 , 9 , 8 , 7 , 6 , 5 , 4 , 3 , 2 , 1 } ; String passPhrase = `` X '' ; // Encryptbyte [ ] encrypted = EncryptStringToBytes_Aes ( passPhrase , c_Key , c_IV ) ; // Print resultfor ( int i = 0 ; i < encrypted.Count ( ) ; i++ ) { Console.WriteLine ( `` [ { 0 } ] { 1 } '' , i , encrypted [ i ] ) ; } Byte c_iv [ 16 ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 16 } ; Byte c_key [ 16 ] = { 16 , 15 , 14 , 13 , 12 , 11 , 10 , 9 , 8 , 7 , 6 , 5 , 4 , 3 , 2 , 1 } ; NSString* passPhrase = @ '' X '' ; // Convert to dataNSData* ivData = [ NSData dataWithBytes : c_iv length : sizeof ( c_iv ) ] ; NSData* keyData = [ NSData dataWithBytes : c_key length : sizeof ( c_key ) ] ; // Convert string to encrypt to dataNSData* passData = [ passPhrase dataUsingEncoding : NSUTF8StringEncoding ] ; NSData* encryptedData = [ CryptoHelper AES256EncryptData : passData withKey : keyData iv : ivData ] ; long size = sizeof ( Byte ) ; for ( int i = 0 ; i < encryptedData.length / size ; i++ ) { Byte val ; NSRange range = NSMakeRange ( i * size , size ) ; [ encryptedData getBytes : & val range : range ] ; NSLog ( @ '' [ % i ] % hhu '' , i , val ) ; }
iOS & .NET Produce Different AES256 Results
C_sharp : I need help with GDAL . The string value with Chinese symbols is not readed/saved correctly ( C # ) .For SAVING grid value we using : private static extern void GDALRATSetValueAsString ( IntPtr handle , int row , int field , [ In ] [ MarshalAs ( UnmanagedType.LPStr ) ] string value ) ; method ( c # ) to save string value , it seems that this method saves string as ANSI string.For READING : In . Example my string `` 银行Flamwood C2 '' There is for methods to get value by pointer ( use in GDALRATGetValueAsString metho ) : Q : So how I can get Unicode string with was saved ( so I can get using this Marshal.PtrToStringUni ( pointer ) ) or most likely how to save the Unicode string to GDALRAT ( GDAL RAT - GDAL Raster Attribute Table ) ? GDAL version : 1.11.1I tried to set CharSet = CharSet.Unicode but id does not helped , still get not correct string : Thanks for any help.P.S . If the GDAL source files need to be build again to save string as unicode string , then what build parameters and where has to be set ? <code> private static extern IntPtr GDALRATGetValueAsString ( IntPtr handle , int row , int field ) ; var pointer = GDALRATGetValueAsString ( GDALRasterAttributeTableH , row , field ) ; a ) var b = Marshal.PtrToStringUni ( pointer ) ; // value : `` 㼿汆浡潷摯䌠2 '' b ) var a = Marshal.PtrToStringAnsi ( pointer ) ; // value : `` ? ? Flamwood C2 '' c ) var c = Marshal.PtrToStringAuto ( pointer ) ; // value : `` 㼿汆浡潷摯䌠2 '' d ) var d = Marshal.PtrToStringBSTR ( pointer ) ; //Throws an error out of memory . [ DllImport ( GdalWrapper.GdalDLL , CallingConvention = CallingConvention.StdCall , CharSet = CharSet.Unicode ) ] private static extern void GDALRATSetValueAsString ( IntPtr handle , int row , int field , [ In ] [ MarshalAs ( UnmanagedType.LPStr ) ] string value ) ;
GDAL GDALRATSetValueAsString ( ) how to save Chinese characters ( c # ) ?
C_sharp : I am currently using Visual Studio Express C++ 2008 , and have some questions about catch block ordering . Unfortunately , I could not find the answer on the internet so I am posing these questions to the experts.I notice that unless catch ( ... ) is placed at the end of a catch block , the compilation will fail with error C2311 . For example , the following would compile : while the following would not : a . Could I ask if this is defined in the C++ language standard , or if this is just the Microsoft compiler being strict ? b . Do C # and Java have the same rules as well ? c . As an aside , I have also tried making a base class and a derived class , and putting the catch statement for the base class before the catch statement for the derived class . This compiled without problems . Are there no language standards guarding against such practice please ? <code> catch ( MyException ) { } catch ( ... ) { } catch ( ... ) { } catch ( MyException ) { }
Questions regarding ordering of catch statements in catch block - compiler specific or language standard ?
C_sharp : I have a bunch of methods that take the WPF 's WriteableBitmap and read from its BackBuffer directly , using unsafe code.It 's not entirely clear whether I should use GC.KeepAlive whenever I do something like this : On the one hand , there remains a reference to bmp on MyMethod 's stack . On the other , it seems like relying on implementation detail - this could compile to a tail call , for example , keeping no reference to bmp the moment DoUnsafeWork is entered.Similarly , imagine the following hypothetical code : In theory , a reference to bmp1 remains on the stack until the method returns , but again , it seems like using an implementation detail . Surely the compiler is free to merge bmp1 and bmp2 because they 're never live at the same time , and even if the compiler never does that surely the JITter still can , and probably does ( e.g . by storing them both in the same register , first one , then the other ) .So , in general : should I rely on locals/arguments being valid references to an object , or should I always use GC.KeepAlive to guarantee correctness ? This is especially puzzling since , apparently , FxCop thinks GC.KeepAlive is always bad . <code> int MyMethod ( WriteableBitmap bmp ) { return DoUnsafeWork ( bmp.BackBuffer ) ; } int MyMethod ( ) { WriteableBitmap bmp1 = getABitmap ( ) ; var ptr = bmp.BackBuffer ; WriteableBitmap bmp2 = getABitmap ( ) ; return DoUnsafeWork ( ptr , bmp2 ) ; }
Is GC.KeepAlive required here , or can I rely on locals and arguments keeping an object alive ?
C_sharp : I want to have an enum as in : How to achieve this ? Is there a better way to do this ? It 's gon na be used for an instance of an object where it 's gon na be serialized/deserialized . It 's also gon na populate a dropdownlist . <code> enum FilterType { Rigid = `` Rigid '' , SoftGlow = `` Soft / Glow '' , Ghost = `` Ghost '' , }
Possible to have strings for enums ?
C_sharp : I have a class that calls out to an internet service to get some data : Currently I have two providers : HttpDataProvider and FileDataProvider . Normally I will wire up to the HttpDataProvider but if the external web service fails , I 'd like to change the system to bind to the FileDataProvider . Something like : So when this has been executed all future instances of MarketingService will automatically be wired up to the FileDataProvider . How to change a Windsor binding on the fly ? <code> public class MarketingService { private IDataProvider _provider ; public MarketingService ( IDataProvider provider ) { _provider = provider ; } public string GetData ( int id ) { return _provider.Get ( id ) ; } } public string GetData ( int id ) { string result = `` '' ; try { result = GetData ( id ) ; // call to HttpDataProvider } catch ( Exception ) { // change the Windsor binding so that all future calls go automatically to the // FileDataProvier // And while I 'm at it , retry against the FileDataProvider } return result ; }
programmatically change a dependency in Castle Windsor
C_sharp : I have an interface called Identifiable < TId > that contains a single property Id of the given type . I want to create a generic class that takes one of these as a type parameter . It should be generic because I want to return concrete type , call other generic methods from within it and use things like typeof ( T ) .This works fine : Problem is that calling code has to pass in two types . eg . new ClassName < Person , int > ( ) I am wondering if in .net 3.5 there is some way to write this so that TId could be inferred by T ? Allowing the caller to just do new ClassName < Person > ( ) ? <code> public class ClassName < T , TId > where T : Identifiable < TId >
Is it possible to implement this interface generically so that it can be passed only one type parameter ?
C_sharp : The MSDN recommends putting any instantiation of classes that implement IDisposable into a using block . Or alternatively , if it is being instantiated within a try-catch block , then Dispose in Finally.Are there any problems with using a using block within a try-catch block like so ? Of course I can just call Dispose in a Finally block , but I 'm a newbie to programming and I 'm just curious to know if doing something like this is practically acceptable or if someone would smack me up the back of my head and yell at me that I 'm Doing-It-Wrong™.Or rather , I 'm more interested in knowing why this would be wrong if it is . <code> try { using ( Foo bar = new Foo ( ) ) { bar.doStuff ( ) ; } } catch ( Exception e ) { //vomit e }
Are there any issues with using block for an IDisposable within a try catch block ?
C_sharp : Can anybody shed any light on why this unit test is failing in Visual Studio 2013 ? <code> [ TestMethod ] public void Inconceivable ( ) { int ? x = 0 ; Assert.AreEqual ( typeof ( int ? ) , x.GetType ( ) ) ; }
Is the C # compiler optimizing nullable types ?
C_sharp : I 'd like to ensure that two interfaces are never found on the same class at compile-time , similar to how AttributeUsage checks custom Attributes at compile-time.e.g . : I can obviously do this at runtime with reflection , but I 'm interested in a compile-time solution.I 'd imagine that one probably does n't exist out of the box - but is there a way to create a custom attribute that is run at compile-time , much like AttributeUsage is ? <code> [ InterfaceUsage ( MutuallyExclusive = typeof ( B ) ) ] interface A { // ... } interface B { // ... } class C : A , B { //should throw an error on compile time // ... }
Ensure mutually exclusive interfaces at compile-time ?
C_sharp : Suppose I have a collection of strings : And I would like to generate a comma separated values from the list into something like : Notice the lack of `` , `` at the end.I am aware that there are dozens of ways to generate this : use for-loop and string.Format ( ) or StringBuilder.use integer counter and remove the ending `` , `` if the value > 0do n't put `` , `` on the first runetc.Sample code of what I have right now : What is the best code that is highly reusable for the above scenario , and why ? <code> `` foo '' '' bar '' '' xyz '' `` foo , bar , xyz '' if ( strs.Count ( ) > 0 ) { var sb = new StringBuilder ( ) ; foreach ( var str in strs ) sb.AppendFormat ( `` { 0 } , `` , str ) ; return sb.Remove ( 0 , 2 ) .ToString ( ) ; }
Generating Comma Separated Values
C_sharp : I 'm getting quite annoyed with a feature of Resharper that I just can not find how to disable independently.With Resharper turned off , whenever I type prop in VS2015 and press TAB , I get the following auto-generated code : and I 'm then able to switch between int and MyProperty repeatedly by pressing TAB again.I 'm also able to use autocomplete to fill in the variable type as I type.For example , lets say I wanted to create a property called `` test '' of type `` string '' , I would do the following : type proppress TAB to generate the property code templatetype stripress TAB to autocomplete the variable type with stringpress TAB to move to the variable name placeholdertype test press Return to finishperfect.However , with Resharper enabled , whilst steps 1,2 and 3 still work , it all goes to pot after that ! If I press TAB to try and autocomplete the variable type , the cursor simply moves over to the variable name , leaving the variable type as stri.If I then press TAB ( or even SHIFT+TAB ) again to try and get back to it , it simply finishes the line.To make things clearer , I 've included two gifs demonstrating my problem.This first one shows what happens with Resharper disabled : Whilst this one illustrates the frustration I 'm currently experiencing with Resharper enabled : <code> public int MyProperty { get ; set ; }
Resharper - Disable 'help ' when using `` prop '' shortcut in C #
C_sharp : I create objects by initializing the fields in this way : Is it always for field `` a '' to be initialized before field `` b '' ? Otherwise , an unpleasant error can occur when the values from the stream are subtracted in a different order . Thanks ! UPD : In the comments , many did not understand what I mean.I will clarify the question . Do these records always be identical in behavior on different ( .NET , Mono , etc ) compilers ? First : Second : <code> class Example { public int a ; public int b ; } var obj = new Example { a = stream.ReadInt ( ) , b = stream.ReadInt ( ) } ; var obj = new Example { a = stream.ReadInt ( ) , b = stream.ReadInt ( ) } ; var a = stream.ReadInt ( ) ; var b = stream.ReadInt ( ) ; var obj = new Example { a = a , b = b } ;
C # The order of fields initialization
C_sharp : I want to put all the signatures of Windows API functions I 'm using in programs in one class , such as WinAPI , and in a file WinAPI.cs I will include in my projects . The class will be internal static and the methods public static extern . ( Something like the huge NativeMethods.cs from the .NET Framework source code ) .Let 's say WinAPI.cs has one hundred native methods signatures like : If I 'm only going to use a few of them in a project ( even one or two ) , if I include the WinAPI.cs file in my project , will the final .exe be filled with the unnecessary method declarations I 'm not using ( the other 99 or so ) ? What about native structure declarations , If I 'm not using them in the current project , will they still be included in the final .exe ? What about constants declarations or readonly members like : <code> [ DllImport ( `` user32.dll '' ) ] internal static extern bool ShowWindow ( IntPtr hWnd , int nCmdShow ) ; [ StructLayout ( LayoutKind.Sequential ) ] public struct POINT { public int X ; public int Y ; } public const int WH_JOURNALPLAYBACK = 1 ; public static readonly int WM_GETTEXT = 0x0D ;
Big C # source file with Windows API method signatures , structures , constants : will they all be included in the final .exe ?
C_sharp : I generated a .cur file to use it in my WPF application , the pointing position by default is left top corner , and I want to set it to the center.I found some threads here that help resolve that problem by setting the HotSpots , where you can do stuff like this : The problem is that is in WindosForms . In WPF the Cursor class constructor does n't accept a IntPtr , it accepts only a Stream or String ( file path ) .How can I achieve this in WPF and is there a whole other way to do it ? ? <code> public static Cursor CreateCursorNoResize ( Bitmap bmp , int xHotSpot , int yHotSpot ) { IntPtr ptr = bmp.GetHicon ( ) ; IconInfo tmp = new IconInfo ( ) ; GetIconInfo ( ptr , ref tmp ) ; tmp.xHotspot = xHotSpot ; tmp.yHotspot = yHotSpot ; tmp.fIcon = false ; ptr = CreateIconIndirect ( ref tmp ) ; return new Cursor ( ptr ) ; }
How to change the pointing position of a mouse cursor in WPF
C_sharp : This is a question based on the article `` Closing over the loop variable considered harmful '' by Eric Lippert.It is a good read , Eric explains why after this piece of code all funcs will return the last value in v : And the correct version looks like : Now my question is how and where are those captured 'v2 ' variables stored . In my understanding of the stack , all those v2 variables would occupy the same piece of memory . My first thought was boxing , each func member keeping a reference to a boxed v2 . But that would not explain the first case . <code> var funcs = new List < Func < int > > ( ) ; foreach ( var v in values ) { funcs.Add ( ( ) = > v ) ; } foreach ( var v in values ) { int v2 = v ; funcs.Add ( ( ) = > v2 ) ; }
How|Where are closed-over variables stored ?
C_sharp : The following piece of C # code does not compile : This behaviour is correct according to the C # 4.0 specification ( paragraph 10.1.4.1 ) : While determining the meaning of the direct base class specification A of a class B , the direct base class of B is temporarily assumed to be object . Intuitively this ensures that the meaning of a base class specification can not recursively depend on itself.My question is : why is n't this behaviour allowed ? Intellisense does n't have a problem with it - although I know that does n't say much , after witnessing Visual Studio crash when Intellisense tries to make sense of some evil class combination with variant generics.Searching the internet for the above quote from the specification yields nothing , so I 'm guessing this has n't been brought up yet anywhere.Why do I care ? I designed the following piece of code : Lo behold , we have achieved covariant return types ! There is one small detail however.Try instantiating a BinarySearchTree . To do that , we need to specify BinarySearchTreeContainer.BinarySearchTree for some suitable Tree and Node classes . For Tree , we 'd like to use BinarySearchTree , for which we 'd need to specify BinarySearchTreeContainer.BinarySearchTree ... And we 're stuck.This is essentially the curiously recurring template pattern ( CRTP ) . Unfortunately , we ca n't fix it as in CRTP : And we 're back to my original question : the top two class definitions are not allowed by the C # specification . If this class definition was allowed , my binary search trees would be usable . Right now , they merely compile : they ca n't be used . <code> public class A { public interface B { } } public class C : A , C.B // Error given here : The type name ' B ' does not exist in the type ' C ' . { } public class D : C.B // Compiles without problems if we comment out ' C.B ' above . { } // The next three classes should really be interfaces , // but I 'm going to override a method later on to prove my point.// This is a container class , that does nothing except contain two classes.public class IBagContainer < Bag , Pointer > where Bag : IBagContainer < Bag , Pointer > .IBag where Pointer : IBagContainer < Bag , Pointer > .IPointer { // This could be an interface for any type of collection . public class IBag { // Insert some object , and return a pointer object to it . // The pointer object could be used to speed up certain operations , // so you do n't have to search for the object again . public virtual Pointer Insert ( object o ) { return null ; } } // This is a pointer type that points somewhere insice an IBag . public class IPointer { // Returns the Bag it belongs to . public Bag GetSet ( ) { return null ; } } } // This is another container class , that implements a specific type of IBag.public class BinarySearchTreeContainer < Tree , Node > : IBagContainer < Tree , Node > where Tree : BinarySearchTreeContainer < Tree , Node > .BinarySearchTree where Node : BinarySearchTreeContainer < Tree , Node > .BinarySearchTreeNode { // This is your basic binary search tree . public class BinarySearchTree : IBagContainer < Tree , Node > .IBag { // We can search for objects we 've put in the tree . public Node Search ( object o ) { return null ; } // See what I did here ? Insert does n't return a Pointer or IPointer , // it returns a Node ! Covariant return types ! public override Node Insert ( object o ) { return null ; } } // A node in the binary tree . This is a basic example of an IPointer . public class BinarySearchTreeNode : IBagContainer < Tree , Node > .IPointer { // Moar covariant return types ! public override Tree GetSet ( ) { return null ; } // If we maintain next and prev pointers in every node , // these operations are O ( 1 ) . You ca n't expect every IBag // to support these operations . public Node GetNext ( ) { return null ; } public Node GetPrev ( ) { return null ; } } } public class BinarySearchTreeContainer : BinarySearchTreeContainer < BinarySearchTreeContainer.BinarySearchTree , BinarySearchTreeContainer.BinarySearchTreeNode > { } public class IBagContainer : IBagContainer < IBagContainer.IBag , IBagContainer.IPointer > { } ( ... ) BinarySearchTreeContainer.BinarySearchTree tree = new BinarySearchTreeContainer.BinarySearchTree ( ) ; tree.Search ( null ) ; IBagContainer.IBag bag = tree ; // No cast ! //bag.Search ( null ) ; // Invalid ! //BinarySearchTreeContainer.BinarySearchTreeNode node// = bag.Insert ( null ) ; // Invalid !
Why ca n't the meaning of a base class specification recursively depend on itself in C # ?
C_sharp : Microsoft 's documention of Parallel.For contains the following method : In this method , potentially multiple threads read values from matA and matB , which were both created and initialized on the calling thread , and potentially multiple threads write values to result , which is later read by the calling thread . Within the lambda passed to Parallel.For , there is no explicit locking around the array reads and writes . Because this example comes from Microsoft , I assume it 's thread-safe , but I 'm trying to understand what 's going on behind the scenes to make it thread-safe.To the best of my understanding from what I 've read and other questions I 've asked on SO ( for example this one ) , several memory barriers are needed to make this all work . Those are : a memory barrier on the calling thread after creating and intializing matA and matB , a memory barrier on each non-calling thread before reading values from matA and matB , a memory barrier on each non-calling thread after writing values to result , anda memory barrier on the calling thread before reading values from result.Have I understood this correctly ? If so , does Parallel.For do all of that somehow ? I went digging in the reference source but had trouble following the code . I did n't see any lock blocks or MemoryBarrier calls . <code> static void MultiplyMatricesParallel ( double [ , ] matA , double [ , ] matB , double [ , ] result ) { int matACols = matA.GetLength ( 1 ) ; int matBCols = matB.GetLength ( 1 ) ; int matARows = matA.GetLength ( 0 ) ; // A basic matrix multiplication . // Parallelize the outer loop to partition the source array by rows . Parallel.For ( 0 , matARows , i = > { for ( int j = 0 ; j < matBCols ; j++ ) { double temp = 0 ; for ( int k = 0 ; k < matACols ; k++ ) { temp += matA [ i , k ] * matB [ k , j ] ; } result [ i , j ] = temp ; } } ) ; // Parallel.For }
Memory barriers in Parallel.For
C_sharp : For methods where ... there exists a static one-to-one mapping between the input and the output , andthe cost of creating the output object is relatively high , andthe method is called repeatedly with the same input ... there is a need for caching result values.In my code the following result value caching pattern is repeated a lot ( pseudo-code in Java , but the question is language-agnostic ) : Repeating this structure all the time is a clear violation of the DRY principle.Ideally , I 'd like the code above to be reduced to the following : Where the theoretical CacheResult annotation would take care of the caching I 'm currently doing by hand . The general term for this type of caching is `` memoization '' .A good example of the exact functionality I 'm looking for is Perl core module `` Memoize '' .In which languages does such a Memoize-like caching solution exist ( either at the language level or the library level ) ? In particular - does such a solution exist for any major platform such as Java or .NET ? <code> private static Map < Input , Output > fooResultMap = new HashMap < Input , Output > ( ) ; public getFoo ( Input input ) { if ( fooResultMap.get ( input ) ! = null ) { return fooResultMap.get ( input ) ; } Output output = null ; // Some code to obtain the object since we do n't have it in the cache . fooResultMap.put ( input , output ) ; return output ; } @ CacheResultpublic getFoo ( Input input ) { Output output = null ; // Some code to obtain the object since we do n't have it in the cache . return output ; }
Which languages have support for return value caching without boilerplate code ?
C_sharp : I came across a behavior that surprises me . Given the following two classes : I can write code like this : The IDE makes it confusing , too , because , while it allows the assignment , it also indicates that the overridden property is read-only : Furthermore , this override is only allowed when I 'm using the base class ' getter : What is going on here ? <code> class Parent { public virtual bool Property { get ; set ; } } class Child : Parent { public override bool Property { get = > base.Property ; } } Child child = new Child ( ) ; child.Property = true ; // this is allowed
Why can a full property in C # be overridden with only a getter but it can still be set ?
C_sharp : I have a question regarding raising base class events . I am currently reading the MSDN C # Programming Guide and I can not understand one thing from the below article : http : //msdn.microsoft.com/en-us/library/vstudio/hy3sefw3.aspxOK , so we are registering the delegate with an event and we 'll be calling the private method HandleShapeChanged when the event is raised.And here we are calling the base class method OnShapeChanged , which , in success , will fire the event . But the event is based in the Shape class , so how can it access the method HandleShapeChanged , which is private ? I have just started to learn the language , so please bear with me . My understanding of this example may be well off target . <code> public void AddShape ( Shape s ) { _list.Add ( s ) ; s.ShapeChanged += HandleShapeChanged ; } public void Update ( double d ) { radius = d ; area = Math.PI * radius * radius ; OnShapeChanged ( new ShapeEventArgs ( area ) ) ; } protected override void OnShapeChanged ( ShapeEventArgs e ) { base.OnShapeChanged ( e ) ; }
Why can a base class event call a private method ?
C_sharp : I have the following classes and I am trying to call Compare method from ExportFileBaseBL class but I get the errorCannot implicitly convert type 'Class1 ' to 'T ' . An explicit conversion exists ( are you missing a cast ? ) Should n't the type conversion be implicit ? Am I missing something ? <code> public abstract class Class1 < T > where T : Class2 { public abstract Class1 < T > Compare ( Class1 < T > otherObj ) ; } public abstract class Class3 < T , U > where T : Class1 < U > where U : Class2 { public T Compare ( T obj1 , T obj2 ) { if ( obj1.Prop1 > obj2.Prop1 ) { return obj1.Compare ( obj2 ) ; // Compiler Error here } else { return obj2.Compare ( obj1 ) ; // Compiler Error here } } }
C # Generics - Calling generic method from a generic class
C_sharp : I 've been toying with parallelism and I 'm having some trouble understanding what 's going on in my program.I 'm trying to replicate some of the functionality of the XNA framework . I 'm using a component-style setup and one way I thought of making my program a little more efficient was to call the Update method of each component in a separate Task . However , I 'm obviously doing something horribly wrong.The code I 'm using in my loop for an update call is : This throws a weird error : An unhandled exception of type 'System.AggregateException ' occurred in mscorlib.dllThe inner exception talks about an index being out of range.If I change to then this seems to work ( or at least the program executes without an exception ) , but there is n't enough room in the array for all of the components . Nonetheless , all of the components are updated , despite there not being enough room in the tasks array to hold them all.However , the gameTime object that is passed as a parameter goes somewhat insane when the game is running . I 've found it hard to pin-point the problem , but I have two components that both simply move a circle 's x-position using However , when using Tasks , their x-positions very quickly become disparate from one another , when they should in fact be the same . Each engineComponent.Update ( gameTime ) is called once per-update cycle , and the same gameTime object is passed.When using tasks [ i ] .RunSynchronously ( ) ; in place of tasks [ i ] .Start ( ) ; , the program runs exactly as expected.I understand that using Tasks in this manner may not be a particularly efficient programming practice , so my question is one of curiosity : why is n't the above code working as I would expect ? I know I 'm missing something obvious , but I 've been unable to track down what specifically is wrong with this implementation.Apologies for the long question , and thanks for reading ; ) <code> public void Update ( GameTime gameTime ) { Task [ ] tasks = new Task [ engineComponents.Count ] ; for ( int i = 0 ; i < tasks.Length ; i++ ) { tasks [ i ] = new Task ( ( ) = > engineComponents [ i ] .Update ( gameTime ) ) ; tasks [ i ] .Start ( ) ; } Task.WaitAll ( tasks ) ; } Task [ ] tasks = new Task [ engineComponents.Count ] ; Task [ ] tasks = new Task [ engineComponents.Count - 1 ] ; x += ( float ) ( gameTime.ElapsedGameTime.TotalSeconds * 10 ) ;
C # Tasks not working as expected . Bizarre error
C_sharp : Given a collection of disparate objects , is it possible to find the most-specific base class they all share ? For instance , given objects with these class hierarchies ... ( For fun ... http : //www.wired.com/autopia/2011/03/green-machine-bike-is-a-big-wheel-for-grownups ) Is it possible to write a function with this signature ... ... and have it return 'WheeledVehicle ' ? My thinking is to somehow build up lists of inheritance chains for each object , reverse them so they all start with 'object ' , then walk down each of them checking for a match across all lists . If any of the items do n't match , then the step before is your deepest matching base type.However , I 'm not sure how to go about building up the chain since 'base ' is an internal member . Is this something you can use Reflection to determine ? <code> object - > Vehicle - > WheeledVehicle - > Car - > SportsCarobject - > Vehicle - > WheeledVehicle - > Busobject - > Vehicle - > WheeledVehicle - > MotorCycleobject - > Vehicle - > WheeledVehicle - > Tricycle - > BigWheelobject - > Vehicle - > WheeledVehicle - > Tricycle - > Green Machine public Type GetCommonBaseType ( List < object > objects ) { ... } ;
How can you programmatically find the deepest common base type from a bunch of subclasses ?
C_sharp : It all started with a trick question that someone posed to me.. ( It 's mentioned in the book - C # in a nutshell ) Here 's the gist of it.The above does n't seem right . a should always be == to itself ( reference equality ) & both should be consistent.Seems like Double overloads the == operator . Confirmed by reflector as follows : Strange that looks recursive and no mention of the NaN specific behavior . So why does it return false ? So I add some more code to distinguishNow I see for doubles , the == operator call translates to a ceq IL opcode where as for strings , it translates to System.String : :op_Equality ( string , string ) .Sure enough the documentation for ceq specifies that it is special-cased for floating point numbers and NaN . This explains the observations.Questions : Why is the op_Equality defined on Double ? ( And the implementation does not factor in the NaN specific behavior ) When is it invoked ? <code> Double a = Double.NaN ; Console.WriteLine ( a == a ) ; // = > falseConsole.WriteLine ( a.Equals ( a ) ) ; // = > true [ __DynamicallyInvokable ] public static bool operator == ( double left , double right ) { return ( left == right ) ; } var x = `` abc '' ; var y = `` xyz '' ; Console.WriteLine ( x == y ) ; // = > false L_0001 : ldc.r8 NaN L_000a : stloc.0 L_000b : ldloc.0 L_000c : ldloc.0 L_000d : ceq L_000f : call void [ mscorlib ] System.Console : :WriteLine ( bool ) L_0014 : nop L_0015 : ldloca.s a L_0017 : ldloc.0 L_0018 : call instance bool [ mscorlib ] System.Double : :Equals ( float64 ) L_001d : call void [ mscorlib ] System.Console : :WriteLine ( bool ) L_0022 : nop L_0023 : ldstr `` abc '' L_0028 : stloc.1 L_0029 : ldstr `` xyz '' L_002e : stloc.2 L_002f : ldloc.1 L_0030 : ldloc.2 L_0031 : call bool [ mscorlib ] System.String : :op_Equality ( string , string ) L_0036 : call void [ mscorlib ] System.Console : :WriteLine ( bool )
When is Double 's == operator invoked ?
C_sharp : We have a controller which expects some parameters in a get route , but the OData functions like $ top is n't working.According to the docs it ( custom query options ) should work fine just declaring the @ prefix at the custom options but it 's not : Using @ as the prefix ( as suggested at docs ) the parameter filtro is n't being filled and get default values to all its properties.Using no prefix it 's not returning an error but the $ top function is being ignored and I 'm getting too many records to show ( 2K+ ) .There is another answer here on SO to something similar , but we are using OData V3 which has no explicit Edm Model Builders , it 's inferred . Have you guys solved such an issue ? Here is my code : GET Request : Controller method : Thanks . <code> ~/ProdutosRelevantes ? $ top=5 & filtro.Cnpjs [ 0 ] =00000000000001 & filtro.DataInicio=2018-01-01 & filtro.DataFim=2018-12-01 & filtro.IndMercado=2 & [ HttpGet ] public IHttpActionResult ProdutosRelevantes ( [ FromUri ] ParametrosAnalise filtro ) { var retorno = GetService ( ) .GetProdutosRelevantes ( filtro ) ; return Content ( HttpStatusCode.OK , retorno ) ; } public class ParametrosAnalise { public Guid IdCliente { get ; set ; } public string [ ] Cnpjs { get ; set ; } public DateTime ? DataInicio { get ; set ; } public DateTime ? DataFim { get ; set ; } public EnumEscopoMercado ? IndMercado { get ; set ; } // Enum declaration public enum EnumEscopoMercado { [ Description ( `` INCLUI NACIONAL '' ) ] InternoEExterno = 1 , [ Description ( `` EXTERIOR '' ) ] Externo = 2 } }
Get route using OData and custom query options
C_sharp : Somewhere in the back of my head a tiny voice is telling me `` the C # code below smells '' .The constant STR_ConnectionString is used in other places in the code as well.How to get rid of the smell ? <code> private const string STR_ConnectionString = `` ConnectionString '' ; private readonly string upperCaseConnectionString = STR_ConnectionString.ToUpperInvariant ( ) ; // a lot further onstring keyAttributeValue = keyAttribute.Value ; if ( keyAttributeValue.ToUpperInvariant ( ) .StartsWith ( upperCaseConnectionString ) ) { // some C # code handling a key that starts with `` ConnectionString '' }
C # : better way than to combine StartsWith and two ToUpperInvariant calls
C_sharp : Do C # console applications appear in the task manager ? I 'm trying to get it both to appear , and the Publisher and Process Name columns to be what I expect.In my AssemblyInfo.cs I have done this : But while my console app is running ( ran from command line as the current user ) I do n't see any of these values in the Task Manager 's Processes or Details tabs ( Windows 10 ) .I know if I create a WinForms project I can get the columns to populate as I expect in Task Manager.Edit : My goal is to see all processes whose binary was created by my company . The `` Details '' tab of Task Manager shows the application filename ( without extension ) as the Description , and has no tab for Company/Publisher ( right clicking on the header and choosing `` Select Columns '' does n't have a publisher option.The `` Processes '' tab does show the expected publisher , but it has no available Description column and if the program is run from the command prompt you need to first expand the correct Windows Command Processor record in Task Manager . <code> [ assembly : AssemblyTitle ( `` Test Title '' ) ] [ assembly : AssemblyDescription ( `` Test Desc '' ) ] [ assembly : AssemblyCompany ( `` Test Company '' ) ] [ assembly : AssemblyProduct ( `` Test Product '' ) ]
Does a C # ( .NET 4.5 ) application appear in the Windows ' Task Manager ?
C_sharp : Can someone please explain to me the following method ? I do n't quite understand what it does , and how it does it . <code> private List < Label > CreateLabels ( params string [ ] names ) { return new List < Label > ( names.Select ( x = > new Label { ID = 0 , Name = x } ) ) ; }
Help understanding some C # code
C_sharp : This seems odd to me , but I remember a thread where Eric Lippert commented on the inability ( by design , or at least convention , I think ) of C # to overload methods based on return type , so perhaps it 's in some convoluted way related to that.Is there any reason this does not work : But this does : From a certain perspective , they 're both fine , in that you 're not Repeating Yourself ( in a very small way ) , but is this just a different pass of the compiler ? <code> public static T Test < T > ( ) where T : new ( ) { return new T ( ) ; } // ElsewhereSomeObject myObj = Test ( ) ; var myObj = Test < SomeObject > ( ) ;
Is the C # compiler unable to infer method type parameters by expected return type ?
C_sharp : I have a distributed system of actors , some on Windows , and some on Linux machine . Sometimes one actor may need to connect other actor and make some communications . Of course , there are cases when one of them is on Windows , and other is on Linux system.Actors connect each other via ActorSelection . There problem is , that when Windows actor is trying to communicate with Linux one , all works fine . But when Linux actor initiating communication , the ActorSelection.ResolveOne failes.I 've made a little sample here : Configuration in app.config is the following : The public-hostname is publicly available ip address.So , here are the cases : When running Windows/Windows , both instances see each other ( I give them remote address - they output `` Resolved `` ) When running Windows/Linux , and give linux actor 's address to windows actor , it outputs `` Resolved '' . So windows connects linux with no problem . After that giving windows actor 's address to linux actor also gives `` Resolved '' - I suppose , the connection is already established and there is no real handshakes passingBUT when running Windiws/Linux and give windows actor 's address to linux actor , it gives `` Failed '' . No messages about any errors or dropping packages . At the end of the log there is the following : Akka.Remote.Transport.AkkaProtocolManager|now supervising akka : //TestSystem/system/transports/akkaprotocolmanager.tcp.0/akkaProtocol-tcp % 3A % 2F % 2FTestSystem % 40 % 5B % 3A % 3Affff % 3A192.168.0.252 % 5D % 3A36983-1|||| 13:20:08.3766|DEBUGAkka.Remote.Transport.ProtocolStateActor|Started ( Akka.Remote.Transport.ProtocolStateActor ) |||| 13:20:08.3922|DEBUG|Akka.Remote.Transport.ProtocolStateActor|Stopped||||The issue with similar logs is described here : Akka.net starting and stopping with no activityThe reason there is that system protocols are not compatible . Is this the same issue ? As I got from Akka.NET docs and release notes , it has full linux support ... So , am I missing something in configuration ? Can anybody make this sample work with Linux - > Windows connection ? <code> static void Main ( string [ ] args ) { ActorSystem system = ActorSystem.Create ( `` TestSystem '' ) ; system.ActorOf ( Props.Create ( ( ) = > new ConnectActor ( ) ) , `` test '' ) ; while ( true ) { var address = Console.ReadLine ( ) ; if ( string.IsNullOrEmpty ( address ) ) { system.Terminate ( ) ; return ; } var remoteAddress = $ '' akka.tcp : // { system.Name } @ { address } /user/test '' ; try { var actor = system.ActorSelection ( remoteAddress ) .ResolveOne ( TimeSpan.FromMilliseconds ( 5000 ) ) .Result ; Console.WriteLine ( `` Resolved : `` + actor.Path ) ; } catch ( Exception ex ) { Console.WriteLine ( `` Failed : `` + ex.Message ) ; } } } akka { loggers = [ `` Akka.Logger.NLog.NLogLogger , Akka.Logger.NLog '' ] suppress-json-serializer-warning = on loglevel = `` DEBUG '' log-config-on-start = on actor { provider = `` Akka.Remote.RemoteActorRefProvider , Akka.Remote '' debug { receive = on autoreceive = on lifecycle = on event-stream = on unhandled = on } } remote { log-remote-lifecycle-events = DEBUG log-received-messages = on helios.tcp { transport-class = `` Akka.Remote.Transport.Helios.HeliosTcpTransport , Akka.Remote '' transport-protocol = tcp applied-adapters = [ ] port = 9000 hostname = `` 0.0.0.0 '' public-hostname = `` 192.168.0.251 '' // This is different for different hosts , of course } } }
Akka.NET Remote between Linux and Windows
C_sharp : I 'm currently working on a website which is being developed using Asp.Net and C # . I 'm making use of Asp.Net Handler to allow users to download files . I can download the files no problem . However I need to log which files were downloaded successfully . This part does n't seem to work correctly for me . E.g . if I click on the file to download and then click cancel on the browser prompt my code still writes to the log . I ca n't seem to figure out how can I write to log only when the file has successfully downloaded . My Code is below.I appreciate all your help and support . <code> public void ProcessRequest ( HttpContext context ) { string logFilePath = `` PathToMyLogFile '' ; string filePath = Uri.UnescapeDataString ( context.Request.QueryString [ `` file '' ] ) ; string fileName = Path.GetFileName ( filePath ) ; if ( context.Response.IsClientConnected ) //Should n't this tell me if the client is connected or not ? { using ( var writer = new StreamWriter ( logFilePath , true ) ) { if ( ! File.Exists ( logFilePath ) ) { //Create log file if one does not exist File.Create ( logFilePath ) ; } else { writer.WriteLine ( `` The following file was downloaded \ '' { 0 } \ '' on { 1 } '' , fileName , DateTime.Now.ToString ( `` dd/MM/yyyy '' ) + `` at `` + DateTime.Now.ToString ( `` HH : mm : ss '' ) ) ; writer.WriteLine ( Environment.NewLine + `` -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - '' + Environment.NewLine ) ; } } } context.Response.ContentType = `` application/octet-stream '' ; context.Response.AppendHeader ( `` Content-Disposition '' , `` attachment ; filename=\ '' '' + Path.GetFileName ( filePath ) ) ; context.Response.WriteFile ( filePath ) ; context.Response.End ( ) ; }
Using Handler to keep track of files
C_sharp : I 'm trying to get non-standard-format data from the clipboard using DataPackageView.GetDataAsync . I am stumped on converting the returned system.__ComObject to a string . Here is the code : I am looking for a solution that will work with any non-standard clipboard format . `` FileName '' is an easily testable format as you can put it on the clipboard by copying a file in Windows Explorer.In C++/Win32 , I can get the clipboard data as follows : In C++ , the clipboard data is just an array of bytes . It must be possible to get the same array of bytes in C # , but I have no clue on unwrapping/converting the system.__ComObjectEdit : Rephrasing the question : How do I get a string or array of byes out of the system.__ComObject returned by dataPackageView.GetDataAsync ( someFormat ) , where someFormat is an arbitrary clipboard format created by another application ? It is very clear to me how to get the data . The difficult part is using the data that is returned.The accepted answer must show how to create a string or array of bytes from the `` data '' returned by <code> var dataPackageView = Windows.ApplicationModel.DataTransfer.Clipboard.GetContent ( ) ; if ( dataPackageView.Contains ( `` FileName '' ) ) { var data = await dataPackageView.GetDataAsync ( `` FileName '' ) ; // How to convert data to string ? } OpenClipboard ( nullptr ) ; UINT clipboarFormat = RegisterClipboardFormat ( L '' FileName '' ) ; HANDLE hData = GetClipboardData ( clipboarFormat ) ; char * pszText = static_cast < char* > ( GlobalLock ( hData ) ) ; GlobalUnlock ( hData ) ; CloseClipboard ( ) ; var data = await dataPackageView.GetDataAsync ( someFormat ) ;
How to get string from dataPackageView.GetDataAsync ( )
C_sharp : So I am looking at this question and the general consensus is that uint cast version is more efficient than range check with 0 . Since the code is also in MS 's implementation of List I assume it is a real optimization . However I have failed to produce a code sample that results in better performance for the uint version . I have tried different tests and there is something missing or some other part of my code is dwarfing the time for the checks . My last attempt looks like this : The code is a bit of a mess because I tried many things to make uint check perform faster like moving the compared variable into a field of a class , generating random index access and so on but in every case the result seems to be the same for both versions . So is this change applicable on modern x86 processors and can someone demonstrate it somehow ? Note that I am not asking for someone to fix my sample or explain what is wrong with it . I just want to see the case where the optimization does work . <code> class TestType { public TestType ( int size ) { MaxSize = size ; Random rand = new Random ( 100 ) ; for ( int i = 0 ; i < MaxIterations ; i++ ) { indexes [ i ] = rand.Next ( 0 , MaxSize ) ; } } public const int MaxIterations = 10000000 ; private int MaxSize ; private int [ ] indexes = new int [ MaxIterations ] ; public void Test ( ) { var timer = new Stopwatch ( ) ; int inRange = 0 ; int outOfRange = 0 ; timer.Start ( ) ; for ( int i = 0 ; i < MaxIterations ; i++ ) { int x = indexes [ i ] ; if ( x < 0 || x > MaxSize ) { throw new Exception ( ) ; } inRange += indexes [ x ] ; } timer.Stop ( ) ; Console.WriteLine ( `` Comparision 1 : `` + inRange + `` / '' + outOfRange + `` , elapsed : `` + timer.ElapsedMilliseconds + `` ms '' ) ; inRange = 0 ; outOfRange = 0 ; timer.Reset ( ) ; timer.Start ( ) ; for ( int i = 0 ; i < MaxIterations ; i++ ) { int x = indexes [ i ] ; if ( ( uint ) x > ( uint ) MaxSize ) { throw new Exception ( ) ; } inRange += indexes [ x ] ; } timer.Stop ( ) ; Console.WriteLine ( `` Comparision 2 : `` + inRange + `` / '' + outOfRange + `` , elapsed : `` + timer.ElapsedMilliseconds + `` ms '' ) ; } } class Program { static void Main ( ) { TestType t = new TestType ( TestType.MaxIterations ) ; t.Test ( ) ; TestType t2 = new TestType ( TestType.MaxIterations ) ; t2.Test ( ) ; TestType t3 = new TestType ( TestType.MaxIterations ) ; t3.Test ( ) ; } }
Code sample that shows casting to uint is more efficient than range check
C_sharp : I am building an ASP.NET Core application which will need to handle large file uploads— as much as 200GB . My goal is to write these files to disk and capture an MD5 Hash at the same time.I 've already gone through and created my own method to identify the file stream from an HTTP client request as outlined in Uploading large files with streaming . Once I 've located the stream I am using the below code to write to disk and create the MD5 Hash.What 's awesome is that the above works ( file created and hash generated ) . What 's not so awesome is that I do n't fully understand how this works : Is the cryptoStream being copied to and then writing to the targetStream ? Is the cryptoStream holding the bytes in memory or just reading them as they go by ? Are both the cryptoStream and targetStream occurring asynchronously ? Or is it an asynchronous copy to the cryptoStream and a synchronous write to the targetStream ? I am happy this works , but without fully understanding it I am concerned I have introduced something evil . <code> // removed the curly brackets from using statements for readability on Stack Overflowvar md5 = MD5.Create ( ) ; using ( var targetStream = File.OpenWrite ( pathAndFileName ) ) using ( var cryptoStream = new CryptoStream ( targetStream , md5 , CryptoStreamMode.Write ) ) using ( var sourceStream = fileNameAndStream.FileStream ) { await sourceStream.CopyToAsync ( cryptoStream ) ; } var hash = md5.Hash ; md5.Dispose ( ) ;
How does asynchronous file hash and disk write actually work ?
C_sharp : When I used to develop in C++ , I remember that Visual Studio had an entry in its Autos window whenever returning from a function call . This entry would tell me what value was returned from that function.One might argue that if a function returns a value , then you should set a variable to that value , i.e.But as a contrived example , suppose I wanted to do this : Instead of stepping into CycleTushKicker to figure out how many lickings my kid gets , I 'd just like to know the value as soon as I exit GetRandomInt.Is there a way to get this when using C # ? EDIT -- followed @ Michael Goldshetyn 's advice and filed a feature suggestion on Microsoft Connect . You can place your votes here : https : //connect.microsoft.com/VisualStudio/feedback/details/636130/display-return-value-from-function-in-autos-window-for-c <code> int i = GetRandomInt ( ) ; CycleTushKicker ( GetRandomInt ( ) ) ;
Return value in Visual Studio 's Autos window
C_sharp : I 'm implementing some 32-bit float trigonometry in C # using Mono , hopefully utilizing Mono.Simd . I 'm only missing solid range reduction currently.I 'm rather stuck now , because apparently Mono 's SIMD extensions does not include conversions between floats and integers , meaning I have no access to rounding/truncation which would be the usual method . I can however convert bitwise between ints and floats.Can something like this be done ? I can scale the domain up and down if needed , but ideally the range reduction should result in a domain of [ 0 , 2 pi ] or [ -pi , pi ] . I have a hunch that it would be possible to do some IEEE magic with the exponent , if the domain is a power of 2 , but I 'm really not sure how to.Edit : Okay , I 've tried messing around with this C code and it feels like I 'm on the verge of something ( it does n't work but the fractional part is always correct , in decimal / base10 at least ... ) . The core principle seems to be getting the exponent difference between your domain and the input exponent , and composing a new float with a shifted mantissa and an adjusted exponent.. But it wo n't work for negatives , and I have no idea how to handle non-powers of 2 ( or anything fractional - in fact , anything else than 2 does n't work ! ) .Edit 2 : Okay , I 'm really trying to understand this in terms of the ieee binary system . If we write the modulus operation like this : We can see the output in all cases is a new number , with no original exponent and the mantissa shifted an amount ( that is based on the exponent and the first non-zero bits of the mantissa after the first exponent-bits of the mantissa is ignored ) into the exponent . But I 'm not really sure if this is the correct approach , it just works out nicely on paper.Edit3 : I 'm stuck on Mono version 2.0.50727.1433 <code> // here 's another more correct attempt : float fmodulus ( float val , int domain ) { const int mantissaMask = 0x7FFFFF ; const int exponentMask = 0x7F800000 ; int ival = * ( int* ) & val ; int mantissa = ival & mantissaMask ; int rawExponent = ival & exponentMask ; int exponent = ( rawExponent > > 23 ) - ( 129 - domain ) ; // powers over one : int p = exponent ; mantissa < < = p ; rawExponent = exponent > > p ; rawExponent += 127 ; rawExponent < < = 23 ; int newVal = rawExponent & exponentMask ; newVal |= mantissa & mantissaMask ; float ret = * ( float* ) & newVal ; return ret ; } float range_reduce ( float value , int range ) { const int mantissaMask = 0x7FFFFF ; const int exponentMask = 0x7F800000 ; int ival = * ( int* ) & value ; // grab exponent : unsigned exponent = ( ival & exponentMask ) > > 23 ; // grab mantissa : unsigned mantissa = ival & mantissaMask ; // remove bias , and see how much the exponent is over range/domain unsigned char erange = ( unsigned char ) ( exponent - ( 125 + range ) ) ; // check if sign bit is set - that is , the exponent is under our range if ( erange & 0x80 ) { // do n't do anything then . erange = 0 ; } // shift mantissa ( and chop off bits ) by the reduced amount int inewVal = ( mantissa < < ( erange ) ) & mantissaMask ; // add exponent , and subtract the amount we reduced the argument with inewVal |= ( ( exponent - erange ) < < 23 ) & exponentMask ; // reinterpret float newValue = * ( float* ) & inewVal ; return newValue ; //return newValue - ( ( erange ) & 0x1 ? 1.0f : 0.0f ) ; } int main ( ) { float val = 2.687f ; int ival = * ( int* ) & val ; float correct = fmod ( val , 2 ) ; float own = range_reduce ( val , 2 ) ; getc ( stdin ) ; } output = input % 2 [ exponent ] + [ mantissa_bit_n_times_exponent ] 3.5 = [ 2 ] + [ 1 + 0.5 ] - > [ 1 ] + [ 0.5 ] = 1.54.5 = [ 4 ] + [ 0 + 0 + 0.5 ] - > [ 0.5 ] + [ 0 ] = 0.55.5 = [ 4 ] + [ 0 + 1 + 0.5 ] - > [ 1 ] + [ 0.5 ] = 1.52.5 = [ 2 ] + [ 0 + 0.5 ] - > [ 0.5 ] + [ 0 ] = 0.52.25 = [ 2 ] + [ 0 + 0 + 0.25 ] - > [ 0.25 ] = 0.252.375 = [ 2 ] + [ 0 + 0 + 0.25 + 0.125 ] - > [ 0.25 ] + [ 0.125 ] = 0.37513.5 = [ 8 ] + [ 4 + 0 + 1 + 0.5 ] - > [ 1 ] + [ 0.5 ] = 1.556.5 = [ 32 ] + [ 16 + 8 + 0 + 0 + 0 + 0.5 ] - > [ 0.5 ] = 0.5
Floating point range reduction
C_sharp : Let 's say I have a method : It 's clear that I should use ArgumentNullException as it shown above to validate that user is not null . Now how can I validate that user.Name is not empty ? Would it be a good practice to do like that : <code> public void SayHello ( User user ) { if ( user == null ) throw new ArgumentNullException ( `` user '' ) ; Console.Write ( string.Format ( `` Hello from { 0 } '' , user.Name ) ) ; } if ( string.IsNullOrWhiteSpace ( user.Name ) ) throw new ArgumentNullException ( `` user '' , `` Username is empty '' ) ;
ArgumentNullException for nested members
C_sharp : Perhaps a useless question : One of exceptions thrown by the above method is also OverflowException : The sum of the elements in the sequence is larger than Int64.MaxValue.I assume reason for this exception is that sum of the averaged values is computed using variable S of type long ? But since return value is of type double , why did n't designers choose to make S also of type double ? Thank you <code> public static double Average < TSource > ( this IEnumerable < TSource > source , Func < TSource , int > selector )
Enumerable.Average and OverflowException
C_sharp : Apologies if this is already answered on this site or in the extensive ServiceStack documentation - I have looked , but if it does exist , I would appreciate a pointer ! I 've been trying to knock up an example service stack ( 1.0.35 ) service which demonstrates the usage of OAuth2 using .NET core ( not .NET 4.5.x ) .I have found this web page and have added the AuthFeature plugin as described , which seems to be fine for the providers that are available . My question : The Yahoo , OpenId , Google and LinkedIn providers do n't appear part of the ServiceStack.Auth namespace ( yet ? ) . I have looked at the Servicestack.Authentication.OAuth2 NuGET package , but this appears to be targeted at .NET 4.6.x . Is this functionality available or on the roadmap for ServiceStack .NET core ? Full Code repo of my demo app : <code> namespace ServiceStackAuthTest1 { public class Program { public static void Main ( string [ ] args ) { IWebHost host = new WebHostBuilder ( ) .UseKestrel ( ) .UseContentRoot ( Directory.GetCurrentDirectory ( ) ) .UseStartup < Startup > ( ) .UseUrls ( `` http : //*:40000/ '' ) .Build ( ) ; host.Run ( ) ; } } public class Startup { public void ConfigureServices ( IServiceCollection services ) { services.AddLogging ( ) ; } public void Configure ( IApplicationBuilder app , IHostingEnvironment env ) { app.UseServiceStack ( ( AppHostBase ) Activator.CreateInstance < AppHost > ( ) ) ; app.Run ( ( RequestDelegate ) ( context = > ( Task ) Task.FromResult < int > ( 0 ) ) ) ; } } public class AppHost : AppHostBase { public AppHost ( ) : base ( `` My Test Service '' , typeof ( MyService ) .GetAssembly ( ) ) { } public override void Configure ( Container container ) { Plugins.Add ( new AuthFeature ( ( ) = > new AuthUserSession ( ) , new IAuthProvider [ ] { new JwtAuthProvider ( AppSettings ) { HashAlgorithm = `` RS256 '' , PrivateKeyXml = AppSettings.GetString ( `` PrivateKeyXml '' ) } , new ApiKeyAuthProvider ( AppSettings ) , //Sign-in with API Key new CredentialsAuthProvider ( ) , //Sign-in with UserName/Password credentials new BasicAuthProvider ( ) , //Sign-in with HTTP Basic Auth new DigestAuthProvider ( AppSettings ) , //Sign-in with HTTP Digest Auth new TwitterAuthProvider ( AppSettings ) , //Sign-in with Twitter new FacebookAuthProvider ( AppSettings ) , //Sign-in with Facebook //new YahooOpenIdOAuthProvider ( AppSettings ) , //Sign-in with Yahoo OpenId //new OpenIdOAuthProvider ( AppSettings ) , //Sign-in with Custom OpenId //new GoogleOAuth2Provider ( AppSettings ) , //Sign-in with Google OAuth2 Provider //new LinkedInOAuth2Provider ( AppSettings ) , //Sign-in with LinkedIn OAuth2 Provider new GithubAuthProvider ( AppSettings ) , //Sign-in with GitHub OAuth Provider new YandexAuthProvider ( AppSettings ) , //Sign-in with Yandex OAuth Provider new VkAuthProvider ( AppSettings ) , //Sign-in with VK.com OAuth Provider } ) ) ; } } public class MyService : Service { }
OAuth2 authentication plugin for ServiceStack .NET Core
C_sharp : I 'm currently making my own very basic generic list class ( to get a better understanding on how the predefined ones work ) . Only problem I have is that I ca n't reach the elements inside the array as you normally do in say using `` System.Collections.Generic.List '' . This works fine , but when trying to access `` whatever '' I want to be able to write : But that obviously does n't work since I 'm clearly missing something in the code , what is it I need to add to my otherwise fully working generic class ? <code> GenericList < type > list = new GenericList < type > ( ) ; list.Add ( whatever ) ; list [ 0 ] ;
generic list class in c #
C_sharp : So I have just caught this bug in our code : Is the order of execution in function invocation specified regarding the order of parameters ? What is written here is : Which means that the first parameter 's reference is saved before the second parameter 's function is invoked.Is this defined behavior ? I could not find specific information on the order of execution in C # lang spec . <code> class A { public int a ; } var x = new A ( ) ; x.a = 1 ; A qwe ( ref A t ) { t = new A ( ) ; t.a = 2 ; return t ; } void asd ( A m , A n ) { Console.WriteLine ( m.a ) ; Console.WriteLine ( n.a ) ; } asd ( x , qwe ( ref x ) ) ; asd ( x , qwe ( ref x ) ) ; 1222
What is C # order of execution in function call with ref ?
C_sharp : So , the quote comes from `` Dependency Injection in .NET '' . Having that in consideration , is the following class wrongly designed ? So this FallingPiece class has the responsibility of controlling the current falling piece in a tetris game . When the piece hits the bottom or some other place , raises an event signaling that and then , through the factory , generates another new piece that starts falling again from above.The only alternative I see is to have an Initialize ( ) method that would generate the piece , but IMO that goes a bit against the idea of having the constructor put your object in a valid state . <code> class FallingPiece { //depicts the current falling piece in a tetris game private readonly IPieceGenerator pieceGenerator ; private IPiece currentPiece ; public FallingPiece ( IPieceGenerator pieceGenerator ) { this.pieceGenerator = pieceGenerator ; this.currentPiece = pieceGenerator.Generate ( ) ; //I 'm performing work in the constructor with a dependency ! } ... }
`` Classes should never perform work involving Dependencies in their constructors . ''
C_sharp : This example is a simplification of the real problem , but how can I get this to compile ? I would expect the generics constraints to propagate.Since T is a TClass and TClass is a class , why isnt T a class ? EDIT : This actually works . Eric Lippert made me think , thanks.Since T is a TClass and TClass is a TAnotherType , T is actually TAnotherType . <code> public class MyClass < TClass > where TClass : class { public void FuncA < Ta > ( ) where Ta : class { } public void FuncB < Tb > ( ) where Tb : TClass { } public void Func < T > ( ) where T : TClass { FuncA < T > ( ) ; FuncB < T > ( ) ; } } public class MyClass < TClass , TAnotherType > where TClass : TAnotherType { public void FuncA < Ta > ( ) where Ta : TClass { } public void FuncB < Tb > ( ) where Tb : TAnotherType { } public void Func < T > ( ) where T : TClass { FuncA < T > ( ) ; FuncB < T > ( ) ; } }
C # generics contraints propagation
C_sharp : My colleague keeps telling me of the things listed in comments.I am confused.Can somebody please demystify these things for me ? <code> class Bar { private int _a ; public int A { get { return _a ; } set { _a = value ; } } private Foo _objfoo ; public Foo OFoo { get { return _objfoo ; } set { _objfoo = value ; } } public Bar ( int a , Foo foo ) { // this is a bad idea A = a ; OFoo = foo ; } // MYTHS private void Method ( ) { this.A //1 - this._a //2 - use this when inside the class e.g . if ( this._a == 2 ) A //3 - use this outside the class e.g . barObj.A _a //4 - // Not using this.xxx creates threading issues . } } class Foo { // implementation }
C # myths about best practices ?
C_sharp : I get a ProtoException ( `` Possible recursion detected ( offset : 4 level ( s ) ) : o EOW '' ) when serializing a tree structure like so : The tree implementation : Am I decorating with the wrong attributes or have I simply designed a non-serializable tree ? Edit : tried this to no avail : <code> var tree = new PrefixTree ( ) ; tree.Add ( `` racket '' .ToCharArray ( ) ) ; tree.Add ( `` rambo '' .ToCharArray ( ) ) ; using ( var stream = File.Open ( `` test.prefix '' , FileMode.Create ) ) { Serializer.Serialize ( stream , tree ) ; } [ ProtoContract ] public class PrefixTree { public PrefixTree ( ) { _nodes = new Dictionary < char , PrefixTree > ( ) ; } public PrefixTree ( char [ ] chars , PrefixTree parent ) { if ( chars == null ) throw new ArgumentNullException ( `` chars '' ) ; if ( parent == null ) throw new ArgumentNullException ( `` parent '' ) ; if ( chars.Length == 0 ) throw new ArgumentException ( ) ; _parent = parent ; _nodes = new Dictionary < char , PrefixTree > ( ) ; _value = chars [ 0 ] ; var overflow = chars.SubSet ( 1 ) ; if ( ! overflow.Any ( ) ) _endOfWord = true ; else Add ( overflow.ToArray ( ) ) ; } [ ProtoMember ( 1 ) ] private readonly char _value ; [ ProtoMember ( 2 ) ] private readonly bool _endOfWord ; [ ProtoMember ( 3 ) ] private readonly IDictionary < char , PrefixTree > _nodes ; [ ProtoMember ( 4 , AsReference = true ) ] private readonly PrefixTree _parent ; public void Add ( char [ ] word ) { if ( word == null ) throw new ArgumentNullException ( `` word '' ) ; if ( word.Length == 0 ) return ; var character = word [ 0 ] ; PrefixTree node ; if ( _nodes.TryGetValue ( character , out node ) ) { node.Add ( word.SubSet ( 1 ) ) ; } else { node = new PrefixTree ( word , this ) ; _nodes.Add ( character , node ) ; } } public override string ToString ( ) { return _endOfWord ? _value + `` EOW '' : _value.ToString ( ) ; } } public static class ListHelper { public static char [ ] SubSet ( this char [ ] source , int start ) { return source.SubSet ( start , source.Length - start ) ; } public static char [ ] SubSet ( this char [ ] source , int start , int length ) { if ( start < 0 ) throw new ArgumentOutOfRangeException ( ) ; if ( start > source.Length ) throw new ArgumentOutOfRangeException ( ) ; if ( length < 0 ) throw new ArgumentOutOfRangeException ( ) ; var result = new char [ length ] ; Array.Copy ( source , start , result , 0 , length ) ; return result ; } } var typeModel = RuntimeTypeModel.Default ; var type = typeModel.Add ( typeof ( PrefixTree ) , false ) ; type.AsReferenceDefault = true ; type.Add ( `` _value '' , `` _endOfWord '' , `` _nodes '' , `` _parent '' ) ; var tree = new PrefixTree ( ) ; tree.Add ( `` racket '' .ToCharArray ( ) ) ; tree.Add ( `` rambo '' .ToCharArray ( ) ) ; using ( var stream = File.Open ( `` test.prefix '' , FileMode.Create ) ) { typeModel.Serialize ( stream , tree ) ; }
Serialize prefix tree
C_sharp : I defined this method : For converting Lists of Type 1 to Lists of Type 2.Unfortunately I forgot , that C # compiler can not say at this stage that T1 is convertible to T2 , so it throws error : error CS0030 : Can not convert type T1 to T2Can someone direct me how to do it properly ? I need this method for now only to convert list of custom class to list of object , so as in .NET everything derives from object it should work.Basically what I would expect is some syntax to tell compiler that T2 ( object ) is base for T1 ( MyClass ) , so something like : ( ... where T2 : base of T1 ) <code> public static List < T2 > ConvertList < T1 , T2 > ( List < T1 > param ) where T1 : class where T2 : class { List < T2 > result = new List < T2 > ( ) ; foreach ( T1 p in param ) result.Add ( ( T2 ) p ) ; return result ; } public static List < T2 > ConvertList < T1 , T2 > ( List < T1 > param ) where T2 : base of T1
Generic method and converting : how to define that Type 1 is convertible to Type 2
C_sharp : When using a very simple expression as key to create an ILookup with Enumerable.ToLookup < TSource , TKey > Method ( IEnumerable < TSource > , Func < TSource , TKey > ) I can use a lambda expression : or a local function : I 'm curious if there is a difference in this simple case.In his answer to Local function vs Lambda C # 7.0 SO user svick gives a good argument why –in general– local functions are preferable to lambdas.An important point is the difference in performance : When creating a lambda , a delegate has to be created , which is an unnecessary allocation in this case . Local functions are really just functions , no delegates are necessary.But since we pass it to ToLookup ( ) a delegate is created anyway . Is there still a difference in performance ? I can imagine that the compiler has to create a fresh delegate lambda for each invocation of myItems.ToLookup , whereas there only needs to be a single delegate instance for the local method ; is this true ? A second point of difference in performance in svick 's answer is the capturing of variables and the creation of closures : Also , local functions are more efficient with capturing local variables : lambdas usually capture variables into a class , while local functions can use a struct ( passed using ref ) , which again avoids an allocation.However , since the expression does not use variables from the outer scope , there does not have to be a closure as stated by Reed Copsey and expanded by Eric Lippert in answer to Are Lambda expressions in C # closures ? : A lambda may be implemented using a closure , but it is not itself necessarily a closure . — Reed Copsey [ ... ] a function that can be treated as an object is just a delegate . What makes a lambda a closure is that it captures its outer variables . — Eric LippertThis is somewhat contradicted Eric Lippert himself is his answer to Assigning local functions to delegates Eric Lippert explains a local function as a named lambda : A local function is basically just a lambda with an associated name.But this is at a level of lesser technical detail and for delegates of lambda's/local functions that do capture outer scope variables.This simple expression is not recursive , not generic , and not an iterator . And which looks better is a matter of opinion.So , are there any differences in performance ( or otherwise ) between simple not capturing , non recursive , non generic , and non iterator lambda expressions and local functions ? <code> var lk = myItems.ToLookup ( ( x ) = > x.Name ) ; var lk = myItems.ToLookup ( ByName ) ; string ByName ( MyClass x ) { return x.Name ; }
Performance of assigning a simple lambda expression or a local function to a delegate
C_sharp : The aim is to see the list as a list of 'name's.Here 's the dictionary : Here 's the attribute 'name ' I 'm after : And here 's the problem : I just ca n't think how to make that line work ! Your advice is much appreciated ! Thanks <code> class Scripts { public Dictionary < int , Script > scripts = new Dictionary < int , Script > ( ) ; ... } class Script { public string name { get ; set ; } ... } public partial class MainForm : Form { Scripts allScripts ; public MainForm ( ) { InitializeComponent ( ) ; allScripts = new Scripts ( ) ; setupDataSources ( ) ; } private void setupDataSources ( ) { BindingSource ketchup = new BindingSource ( allScripts.scripts , null ) ; //THIS LINE : listBoxScripts.DisplayMember = allScripts.scripts [ `` Key '' ] .name.ToString ( ) ; listBoxScripts.ValueMember = `` Key '' ; listBoxScripts.DataSource = ketchup ; } ... }
C # Can I display an Attribute of an Object in a Dictionary as ListControl.DisplayMember ?
C_sharp : I have a project where I am using C # 7 features . It builds fine locally , but when I build in Visual Studio Team Services , I get errors . All the errors point to this one project and they all look related to C # 7 : The project targets.NET 4.6.1 and references Microsoft.CodeDom.Providers.DotNetCompilerPlatform 1.0.3 and Micosoft.Net.Compilers 2.0.1.How can I get the project to build on VSTS ? <code> Identifier expected Invalid expression term 'int ' Syntax error , ' , ' expected Syntax error , ' > ' expected ) expected ; expected
Deploying C # 7 code to VSTS
C_sharp : I am calling a function which returns a string containing XML data . How this function works is not important but the resulting xml can be different depending on the success of the function.Basically the function will return either the expect XML or an error formatted XML . Below are basic samples of what the two results might look like ... On Success : On Error : The way my system is set up is that I can convert an xml string to a class with a simple converter function but this requires my to know the class type . On success , I will know it is SpecificResult and I can convert . But I want to check to first if an error occured.The ideal end result would allow something similar to this ... So the question is , what is the best way to implement the IsError function ? I have thought of a couple of options but not sure if I like any of them really ... check if xml string contains `` < ErrorResult > '' try to convert xml to ErrorResult class and check for failuse XDocument or similar built in functions to parse the tree and search for ErrorResult node <code> < SpecificResult > < Something > data < /Something > < /SpecificResult > < ErrorResult > < ErrorCode > 1 < /ErrorCode > < ErrorMessage > An Error < /ErrorMessage > < /ErrorResult > string xml = GetXML ( ) ; if ( ! IsError ( xml ) ) { //convert to known type and process }
Checking XML for expected structure
C_sharp : I 'm trying to write a generic method that supplies parameters and calls a function , like this : The last line fails to compile with CS0411 . Is there any workaround to get type inference to work here ? Use case : using AutoFixture to generate function call parameters . <code> class MyClass { public int Method ( float arg ) = > 0 ; } TResult Call < T1 , TResult > ( Func < T1 , TResult > func ) = > func ( default ( T1 ) ) ; void Main ( ) { var m = new MyClass ( ) ; var r1 = Call < float , int > ( m.Method ) ; var r2 = Call ( m.Method ) ; // CS0411 }
C # method group type inference