text
stringlengths
46
37.3k
title
stringlengths
12
162
C_sharp : I have a collection that I first need to filter and then select one out of it , but how the collection should be processed is different depending on some parameters . So I went with 2 delegates , but somehow I should combine them : I tried something like this but it fails because the delegates are n't of matching types : Question : Is it possible to create a new delegate that invokes the first one and uses the return value as input parameter for the second one ? Without the ref parameter I got it to work with lambdas , but of course I ca n't use out or ref then.Compilable example : <code> delegate IEnumerable < T > FilterDelegate ( IEnumerable < T > collection ) ; delegate T SelectorDelegate ( IEnumerable < T > collection , ref T previous ) ; //Combine above two to this one : delegate T GetItemDelegate ( IEnumerable < T > collection , ref T previous ) ; static GetItemDelegate CreateDelegate ( FilterDelegate filter , SelectorDelegate select ) { return Delegate.Combine ( filter , select ) as GetItemDelegate ; } namespace DelegateTest { interface INumericValue { int Number { get ; } } class Test : INumericValue { public Test ( int i ) { Number = i ; } public int Number { get ; } } class Program { delegate IEnumerable < T > FilterDelegate < T > ( IEnumerable < T > collection ) where T : class , INumericValue ; delegate T SelectDelegate < T > ( IEnumerable < T > collection , ref T previous ) where T : class , INumericValue ; delegate T CombinedDelegate < T > ( IEnumerable < T > collection , ref T previous ) where T : class , INumericValue ; static void Main ( ) { Test previous = new Test ( 6 ) ; List < Test > collection = new List < Test > ( ) ; FilterDelegate < Test > filter = Filter ; SelectDelegate < Test > select = Select ; CombinedDelegate < Test > combined = Delegate.Combine ( filter , select ) as CombinedDelegate < Test > ; for ( int i = 0 ; i < 10 ; i++ ) collection.Add ( new Test ( i ) ) ; //Expected result Test with Number = 7 Test result = combined ( collection , ref previous ) ; } static IEnumerable < T > Filter < T > ( IEnumerable < T > collection ) where T : class , INumericValue { return collection.Where ( c = > c.Number > 3 ) ; } static T Select < T > ( IEnumerable < T > collection , ref T previous ) where T : class , INumericValue { var previousNumber = previous.Number ; return previous = collection.FirstOrDefault ( c = > c.Number > previousNumber ) ; } } }
Is it possible to combine delegates of different types ( use return value as parameter ) ?
C_sharp : I have an immutable class that I want to write to and read from a CSV file . The issue is I am getting an exception when reading the CSV despite having mapped the object and set up a configuration that should allow this to work.To do this I am using CsvHelper . The immutable class looks like the following.I have no issue writing this to a CSV file , but when I try to read it from a file , I get the following exception . No members are mapped for type 'CsvTest.Program+ImmutableTest'However , I have mapped the members for this class in the map class below.I have also tried to configure the reader to use the constructor to build the object by using the following configuration.No of this seems to be working . Where am I going wrong ? Complete MCVE .NET Framework Console ExampleInstall the packagesSample console program <code> public class ImmutableTest { public Guid Id { get ; } public string Name { get ; } public ImmutableTest ( string name ) : this ( Guid.NewGuid ( ) , name ) { } public ImmutableTest ( Guid id , string name ) { Id = id ; Name = name ; } } public sealed class ImmutableTestMap : ClassMap < ImmutableTest > { public ImmutableTestMap ( ) { Map ( immutableTest = > immutableTest.Id ) .Index ( 0 ) .Name ( nameof ( ImmutableTest.Id ) .ToUpper ( ) ) ; Map ( immutableTest = > immutableTest.Name ) .Index ( 1 ) .Name ( nameof ( ImmutableTest.Name ) ) ; } } Configuration config = new Configuration { IgnoreBlankLines = true } ; config.RegisterClassMap < ImmutableTestMap > ( ) ; config.ShouldUseConstructorParameters = type = > true ; config.GetConstructor = type = > type.GetConstructors ( ) .MaxBy ( constructor = > constructor.GetParameters ( ) .Length ) .FirstOrDefault ( ) ; Install-Package CsvHelperInstall-Package morelinq using System ; using System.IO ; using CsvHelper ; using CsvHelper.Configuration ; using MoreLinq ; namespace CsvTest { class Program { static void Main ( ) { Configuration config = new Configuration { IgnoreBlankLines = true } ; config.RegisterClassMap < ImmutableTestMap > ( ) ; config.ShouldUseConstructorParameters = type = > true ; config.GetConstructor = type = > type.GetConstructors ( ) .MaxBy ( constructor = > constructor.GetParameters ( ) .Length ) .FirstOrDefault ( ) ; const string filePath = `` Test.csv '' ; using ( FileStream file = new FileStream ( filePath , FileMode.Create ) ) using ( StreamWriter fileWriter = new StreamWriter ( file ) ) using ( CsvSerializer csvSerializer = new CsvSerializer ( fileWriter , config ) ) using ( CsvWriter csvWriter = new CsvWriter ( csvSerializer ) ) { csvWriter.WriteHeader < ImmutableTest > ( ) ; csvWriter.NextRecord ( ) ; csvWriter.WriteRecord ( new ImmutableTest ( `` Test 1 '' ) ) ; csvWriter.NextRecord ( ) ; csvWriter.WriteRecord ( new ImmutableTest ( `` Test 2 '' ) ) ; csvWriter.NextRecord ( ) ; } using ( FileStream file = new FileStream ( filePath , FileMode.Open ) ) using ( StreamReader fileReader = new StreamReader ( file ) ) using ( CsvReader csvReader = new CsvReader ( fileReader , config ) ) { foreach ( ImmutableTest record in csvReader.GetRecords < ImmutableTest > ( ) ) { Console.WriteLine ( record.Id ) ; Console.WriteLine ( record.Name ) ; Console.WriteLine ( ) ; } } } public sealed class ImmutableTestMap : ClassMap < ImmutableTest > { public ImmutableTestMap ( ) { Map ( immutableTest = > immutableTest.Id ) .Index ( 0 ) .Name ( nameof ( ImmutableTest.Id ) .ToUpper ( ) ) ; Map ( immutableTest = > immutableTest.Name ) .Index ( 1 ) .Name ( nameof ( ImmutableTest.Name ) ) ; } } public class ImmutableTest { public Guid Id { get ; } public string Name { get ; } public ImmutableTest ( string name ) : this ( Guid.NewGuid ( ) , name ) { } public ImmutableTest ( Guid id , string name ) { Id = id ; Name = name ; } } } }
CsvHelper and immutable types
C_sharp : I have an interface and a typed factory interface : I Then have an implementation of another interface IDependencyOwner : IDisposable which is implementend by : The DependencyOwner is held a dependency for yet another object , and there can be many implementations of DependencyOwner , which are resolved with the CollectionResolver Sub Resolver . but I do n't believe that it is relevant to this problem . Its Constructor looks like : public TopLevel ( IDependencyOwner [ ] dependencies ) Container Registration looks like this : Everything with the code actually running is fine . The problem comes when it is time to close the program.The ITransientItemFactory is getting disposed before DependencyOwner 's Dispose method is even called ( I have verified this by putting a breakpoint on the very first line of the dispose method and then then checking my log to see that the error is already present ) . This causes any workItems that were in the middle of processing to fail , and the program crashes rather than ending gracefully.The exception I get is : System.ObjectDisposedException : The factory was disposed and can no longer be used . Object name : 'this'.Why is Windsor not honoring this dependency ? EDIT : I stumbled on this trick here and have been able to confirm that the factory does appear in the dependency graph as a dependency of DependencyOwner.EDIT 2 : I have just implemented the factory myself and removed the typed factory . This solved my problem ( As the dependency was honored ) , but I would rather not do this if I can avoid it . Just for illustrative purposes , the registration in this case becomes : <code> public interface ITransientItem : IDisposable { void DoWork ( WorkItem item ) ; } public interface ITransientItemFactory : IDisposable { ITransientItem Create ( ) ; void Destroy ( ITransientItem item ) ; } public class DependencyOwner : IDependencyOwner { private ITransientItemFactory _factory ; public DependencyOwner ( ITransientItemFactory factory ) { _factory = factory ; } public void PostWork ( WorkItem workItem ) { ITransientItem item = _factory.Create ( ) ; item.DoWork ( workItem ) ; //this is done on a seperate thread _factory.Destroy ( item ) ; } public void Dispose ( ) { //first wait for running items to dispose //then do disposal stuff } } WindsorContainer container = new WindsorContainer ( ) ; container.AddFacility ( new TypedFactoryFacility ( ) ) ; container.Kernel.Resolver.AddSubResolver ( new CollectionResolver ( container.Kernel ) ) ; container.Register ( Component.For < TopLevel > ( ) ) ; container.Register ( Component.For < IDependencyOwner > ( ) .ImplementedBy < DependencyOwner > ( ) ; //there will be more IDependencyOwner Implementations in the future container.Register ( Component.For < ITransientItem > ( ) .ImplementedBy < TransientItem > ( ) .LifeStyle.Transient ) ; container.Register ( Component.For < ITransientItemFactory > ( ) .AsFactory ( ) ) ; TopLevel top = container.Resolve < TopLevel > ( ) ; WindsorContainer container = new WindsorContainer ( ) ; //container.AddFacility ( new TypedFactoryFacility ( ) ) ; container.Kernel.Resolver.AddSubResolver ( new CollectionResolver ( container.Kernel ) ) ; container.Register ( Component.For < TopLevel > ( ) ) ; container.Register ( Component.For < IDependencyOwner > ( ) .ImplementedBy < DependencyOwner > ( ) ; //there will be more IDependencyOwner Implementations in the future //No reason to register it anymore , it will never be instantiated by the container //container.Register ( Component.For < ITransientItem > ( ) .ImplementedBy < TransientItem > ( ) //.LifeStyle.Transient ) ; //container.Register ( Component.For < ITransientItemFactory > ( ) .AsFactory ( ) ) ; container.Register ( Component.For < ITransientItemFactory > ( ) .ImplementedBy < FactoryImplementation > ( ) ) ; TopLevel top = container.Resolve < TopLevel > ( ) ;
TypedFactory Disposes Before Component Using it As a Dependency
C_sharp : I 'm a new programmer , so please excuse any dumbness of this question , how the following code is encapsulating private data ? -I mean , with no restriction logic or filtering logic in the properties , how is the above code different from the folowing one -Is the first code providing any encapsulation at all ? <code> public class SomeClass { private int age ; public int Age { get { return age ; } set { age = value ; } } public SomeClass ( int age ) { this.age = age ; } } public class SomeClass { public int age ; public SomeClass ( int age ) { this.age = age ; } }
Where 's the Encapsulation ?
C_sharp : I 'm new to C # and have run into a problem with the following code ( I have the target framework as 4.5 and I 've added a reference to System.Numerics ) : When the release build is started with debugging ( F5 in Visual Studio - and a break-point at the end of program so I can see the output ) , I get the following output : However , when the release build is started without debugging ( Ctrl-F5 ) , I get the following : Strangely if I add a Console.ReadLine ( ) at the end of the program it works as expected ! Any ideas what is causing this ? Thanks . <code> using System ; using System.Numerics ; namespace Test { class Program { static BigInteger Gcd ( BigInteger x , BigInteger y ) { Console.WriteLine ( `` GCD { 0 } , { 1 } '' , x , y ) ; if ( x < y ) return Gcd ( y , x ) ; if ( x % y == 0 ) return y ; return Gcd ( y , x % y ) ; } static void Main ( string [ ] args ) { BigInteger a = 13394673 ; BigInteger b = 53578691 ; Gcd ( a , b ) ; } } } GCD 13394673 , 53578691GCD 53578691 , 13394673GCD 13394673 , 13394672GCD 13394672 , 1 GCD 13394673 , 53578691GCD 53578691 , 53578691
C # 64 bit release build started without debugging behaves differently to when started with debugging ( BigInteger )
C_sharp : I noticed something strange and there is a possibility I am wrong.I have an interface IA and class A : In other class I have this : But I get compilation error.But if I change it to : Everything is fine.Why is it ? <code> interface IA { ... . } class A : IA { ... . } private IList < A > AList ; public IList < IA > { get { return AList ; } } public IList < IA > { get { return AList.ToArray ( ) ; } }
list.ToArray vs list
C_sharp : I 've run into this several times , so would like to use a real example and get ideas on how more experienced C # developers handle this.I 'm writing a .NET wrapper around the unmanaged MediaInfo library , which gathers various data about media files ( movies , images ... ) .MediaInfo has many functions , each applying to different types of files . For example , `` PixelAspectRatio '' applies to images and video but not to audio , subtitles , or others.A subset of the functionality I 'd like to wrap is below : As you can see , the start of a not-too-bad class mapping would be one class for the functionality specific to each stream type and a base class with functionality common to all types.Then this path gets a little less obvious . There are many functions common to { general , video , audio , text , and image } stream types . Okay , so I guess I can make a class with a smelly name like `` GeneralVideoAudioTextImage '' , and then another named GeneralVideoAudioText ( which inherits from GeneralVideoAudioTextImage ) for the functionality common to those things , but not `` Image '' streams . This would awkwardly follow the `` is a '' rule of class hierarchies , I guess.This is already not looking elegant , but then there are those occasional cases like `` Width '' which do not fit into any group which is cleanly a subset of another group . Those cases can simply duplicate functionality where necessary -- implement in Video , Text , and Image individually , but that would obviously violate DRY.A common first approach would be MI , which C # does not support . The usual answer to that seems to be `` use MI with interfaces , '' but I ca n't find entirely see how that can follow DRY . Perhaps my failing.Class hierarchies have been discussed on SO before , as have alternatives to MI ( extension methods , etc . ) but none of those solutions seemed a good fit . For example , extension methods seem better used for classes whose source you can not edit , like the String class , and are harder to locate because they are not really tied with the class , though they may work.I have n't found a question asked about a situation like this , though that 's probably a failure of my use of the search tool.An example of a MediaInfo feature , wrapped , might be : My question is : How have you handled situations like this , systems which are kind-of-hierarchical-but-not-quite ? Have you found a reasonably elegant strategy , or just accepted that not every simple problem has one ? <code> General Video Audio Text Image Chapters Menu ( Name of function ) x x x x x x x Formatx x x x x x x Titlex x x x x x x UniqueIDx x x x x x CodecIDx x x x x x CodecID/Hint x x x x x Languagex x x x x Encoded_Datex x x x x Encoded_Libraryx x x x x InternetMediaTypex x x x x StreamSize x x x x BitDepth x x x x Compression_Mode x x x x Compression_Ratiox x x x x Delayx x x x x Duration x x x BitRate x x x BitRate_Mode x x x ChannelLayout x x x FrameCount x x x FrameRate x x x MuxingMode x x x MuxingMode x x x Source_Duration x x x Height x x x Width x x PixelAspectRatio x SamplingRatex Albumx AudioCountx ChaptersCountx EncodedByx Groupingx ImageCountx OverallBitRatex OverallBitRate_Maximumx OverallBitRate_Minimumx OverallBitRate_Nominalx TextCountx VideoCount int _width = int.MinValue ; /// < summary > Width in pixels. < /summary > public int width { get { if ( _width == int.MinValue ) _width = miGetInt ( `` Width '' ) ; return _width ; } } // ... ( Elsewhere , in another file ) ... /// < summary > Returns a MediaInfo value as an int , 0 if error. < /summary > /// < param name= '' parameter '' > The MediaInfo parameter. < /param > public int miGetInt ( string parameter ) { int parsedValue ; string miResult = mediaInfo.Get ( streamKind , id , parameter ) ; int.TryParse ( miResult , out parsedValue ) ; return parsedValue ; }
Class design for system which is hierarchical , but not neatly so
C_sharp : Our application can share code . For example user is sharing the html code as followswhich is not in a perfect format ... . Now i need to achieve the ( auto ) code formatting ... i.e . after auto code format click , it should look like So , is there ready made plugin available or is there any way ( s ) to achieve it either via jQuery or C # ? <code> < div id= '' nav-vert-one '' > < ul > { { for GroupCollection } } < li > < a href= '' # '' title= '' { { : Name } } '' onclick= '' test ( ) '' > { { : Name } } < /a > ( ' { { : GroupId } } ' ) '' > < /li > { { /for } } < /ul > < div id= '' nav-vert-one '' > < ul > { { for GroupCollection } } < li > < a href= '' # '' title= '' { { : Name } } '' onclick= '' test ( ) '' > { { : Name } } < /a > ( ' { { : GroupId } } ' ) '' > < /li > { { /for } } < /ul >
How to achieve ( auto ) code format selection of any html code via jQuery / C # ? ( Any solution )
C_sharp : I often find I want to write code something like this in C # , but I am uncomfortable with the identifier names : Here we have four different things called `` engine '' : Engine the class . Engine seems like a good , natural name.Engine the public property . Seems silly to call it MyEngine or TheCarsEngine.engine the private field backing the property . Some naming schemes will recommend m_engine or _engine , but others say that all prefixes should be avoided.engine the parameter name on the constructor . I 've seen naming schemes that recommend prefixing an underscore on all parameters , e.g. , _engine . I really dislike this , since the parameter is visible to callers via Intellisense.The particular things I do n't like about the code as written are that : If you change the parameter name in the constructor but miss a use of it in the constructor body , you get a subtle bug that the compiler probably wo n't be able to spot.Intellisense has a bad habit of autocompleting the wrong thing for you , and sometimes you wo n't notice it 's changed the case . You will again get a subtle bug if the constructor body accidentally ends up this.engine = Engine ; It seems that each name is appropriate in isolation , but together they are bad . Something has to yield , but what ? I prefer to change the private field , since it 's not visible to users , so I 'll usually end up with m_engine , which solves some problems , but introduces a prefix and does n't stop Intellisense from changing engine to Engine.How would you rename these four items ? Why ? ( Note : I realise the property in this example could be an automatic property . I just did n't want to make the example overcomplicated . ) See also : Am I immoral for using a variable name that differs from its type only by case ? <code> public class Car { private Engine engine ; public Engine Engine { get { return engine ; } set { engine = value ; } } public Car ( Engine engine ) { this.engine = engine ; } }
How would you name these related Property , Class , Parameter and Field in .NET ?
C_sharp : I have created an extension function , which takes the string as input and check for the value and based on the Generic Type , cast it to the destination type and return it , it 's working well.Now the problem is if i pass the input value as empty it should return null , for nullable types , but it simply throws exception.For e.g . : if i want to cast it to datetime , it throws below exception : Below is my code : and here how i am accessing it : For above case i want to return null . <code> String was not recognized as a valid DateTime public static class Extension { public static T ToNull < T > ( this string value ) { var stringType = `` System.Nullable ` 1 [ [ System . { 0 } , mscorlib , Version=2.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 ] ] '' ; if ( typeof ( T ) == typeof ( String ) ) stringType = string.Format ( stringType , `` String '' ) ; if ( typeof ( T ) == typeof ( Int32 ? ) || typeof ( T ) == typeof ( Int32 ) ) stringType = string.Format ( stringType , `` Int32 '' ) ; if ( typeof ( T ) == typeof ( DateTime ? ) || typeof ( T ) == typeof ( DateTime ) ) stringType = string.Format ( stringType , `` DateTime '' ) ; if ( typeof ( T ) == typeof ( Int64 ? ) || typeof ( T ) == typeof ( Int64 ) ) stringType = string.Format ( stringType , `` Int64 '' ) ; Type originalType = Type.GetType ( stringType ) ; var underlyingType = Nullable.GetUnderlyingType ( originalType ) ; return ( T ) Convert.ChangeType ( value , underlyingType ? ? originalType ) ; } } string s = `` '' ; DateTime ? t = s.ToNull < DateTime ? > ( ) ; Console.WriteLine ( t ) ;
Returning null for generic type extension in c #
C_sharp : I 've been reading Tim McCarthy 's awesome book on DDD in .NET . In his example application though , his underlying data access is using SqlCE and he 's handcrafting the SQL inline.I 've been playing with some patterns for leveraging Entity Framework but I 've gotten stuck on how exactly to map the IRepository linq queries to the underlying data access layer.I have a concrete repository implementation called.In my EF Model , I 'm using POCO Entities but even so there 's going to be no native mapping between my DomainEntity.Customer & my DataAccessLayer.Customer objects.so I ca n't just pass Expression < Func < DomainEntities.Customer , bool > > predicate as the parameter for an EFContext.Customers.Where ( ... ) ; Is there an easy way to map an Expression < Func < T , bool > > predicate = > Expression < Func < TOTHER , bool > > predicate Or am I going about this all wrong ? Any suggestions / pointers appreciated . <code> public EFCustomerRepository : IRepository < DomainEntities.Customer > { IEnumerable < DomainEntities.Customer > GetAll ( Expression < Func < DomainEntities.Customer , bool > > predicate ) { //Code to access the EF Datacontext goes here ... } }
Is there a suggested pattern for using LINQ between the Model & DataAccess Layers in a DDD based Layered Architecture
C_sharp : I have the following class as a DataSource for a ListBox : The problem is , this by default will use the Value just as a regular character added to a string , for example if I define this class for Tab like this : The string representation will be : But I need it to beHow to do this ? ! <code> class SeparatorChars { /// < summary > /// Text to describe character /// < /summary > public string Text { get ; set ; } /// < summary > /// Char value of the character /// < /summary > public char Value { get ; set ; } /// < summary > /// Represent object as string /// < /summary > /// < returns > String representing object < /returns > public override string ToString ( ) { return Text + `` ' '' + Value + `` ' '' ; } } var TabSeparator = new SeparatorChars { Text = `` Tab '' , Value = '\t ' } Tab ' ' Tab '\t '
Representing a Char with equivalent string
C_sharp : Result : `` Derived : :Foo ( object o ) '' WHY ? ? ? <code> using System ; namespace ConsoleApplication1 { class Program { static void Main ( string [ ] args ) { var a = new Derived ( ) ; int x = 123 ; a.Foo ( x ) ; } } public class Base { public virtual void Foo ( int x ) { Console.WriteLine ( `` Base : :Foo '' ) ; } } public class Derived : Base { public override void Foo ( int x ) { Console.WriteLine ( `` Derived : :Foo ( int x ) '' ) ; } public void Foo ( object o ) { Console.WriteLine ( `` Derived : :Foo ( object o ) '' ) ; } } }
Why this method called ?
C_sharp : While working on a project I ran into the following piece of code , which raised a performance flag.I decided to run a couple of quick tests comparing the original loop to the following loop : and threw this loop in too to see what happens : I also populated the original list 3 different ways : 50-50 ( so 50 % of values where `` Not Reviewed '' and the rest other ) , 10-90 and 90-10 . These are my results , the first and last loopsare mostly the same but the second one is much faster , especially on 10-90 case . Why exactly ? I always thought Lambda had good performance.EDITThe count++ is not actually what 's inside the loop , I just added that here for demonstration purposes , I guess I should 've used `` //do something here '' EDIT 2Results running each one 1000 times : <code> foreach ( var sample in List.Where ( x = > ! x.Value.Equals ( `` Not Reviewed '' ) ) ) { //do other work here count++ ; } foreach ( var sample in List ) { if ( ! sample.Value.Equals ( `` Not Reviewed '' ) ) { //do other work here count++ ; } } var tempList = List.Where ( x = > ! x.Value.Equals ( `` Not Reviewed '' ) ) ; foreach ( var sample in tempList ) { //do other work here count++ ; }
foreach loop List performance difference
C_sharp : The premise of my question , in plain english : A library named Foo depends on a library named BarA class within Foo extends a class within BarFoo defines properties/methods that simply pass-through to BarAn application , FooBar , depends only on FooConsider the following sample : Foo is defined as followsBar is defined as followsThe part that is completely stumping me : Without a reference to the Bar libraryFooBar can retrieve the ID that is provided by Bar ( or at least it compiles ) FooBar can not request Foo to do work that is ultimately accomplished by BarThe compiler error associated with foo.DoWorkOnBar ( ) ; is The type 'Bar ' is defined in an assembly that is not referenced . You must add a reference to assembly 'Bar , Version 1.0.0.0 , Culture=Neutral , PublicKeyToken=null ' .Why does there appear to be a disparity in the compiler ? I would have assumed that neither of these operations would compile without FooBar adding a reference to Bar . <code> class Program { static void Main ( string [ ] args ) { Foo foo = Foo.Instance ; int id = foo.Id ; // Compiler is happy foo.DoWorkOnBar ( ) ; // Compiler is not happy } } public class Foo : Bar { public new static Foo Instance { get = > ( Foo ) Bar.Instance ; } public new int Id { get = > Bar.Id ; } public void DoWorkOnBar ( ) { Instance.DoWork ( ) ; } } public class Bar { public static Bar Instance { get = > new Bar ( ) ; } public static int Id { get = > 5 ; } public void DoWork ( ) { } }
Why can the C # compiler `` see '' static properties , but not instance methods , of a class in a DLL that is not referenced ?
C_sharp : I 'm using a list to store a pair of hexadecimal values ( eg . in the list AD38F2D8 , displayed as : Value_A : AD 38 F2 D8 ) .My question is should I use a Dictionary < string , string > or should I use Dictionary < string , NewCustomObject > to store the hexadecimal string as a pair of strings . ( Value : [ AD , 38 , F2 , D8 ] ) instead of ( Value : AD38F2D8 ) .It probably wo n't make to much of a difference between the two.With Dictionary < string , string > I would just store each hex string in the dictionary , and then split them up in their respective pairs when I need them . if I use the Dictionary < string , NewCustomObject > I would end up first splitting the hex strings in their respective pairs and then store them in the dictionary.My question is which should I use ? Or should I just keep using lists ? It 's not entirely necessary for me to use Dictionary < string , string > as I would still know which index what string is on , just that it would look nicer.List example : Dictionary < string , string > example : Dictionary < string , NewCustomObject > example : NOTE : the Index value in each dictionary example is just to show the corespondence to the others , I know a dictionary does not have Index values but uses keys instead . it 's just makes it easier to look at this example.I came across the last Dictionary string here : C # Dictionary with two Values per Key ? I was searching for it as I have used that way several times while writing python code . by storing a list of strings within a dictionary.Thanks in advance for any help ! EDITEach string in either the list or dictionary , would be split in their respective bytes . EG.Byte 0 would hold the Index Byte 1 would hold the ReferenceByte 2 the FlagsByte 3 to 6 : The Memb_Number_IDTherefore , if I split them up before possibly putting these in the dictionary I do n't have to do it before I use them in their respective place as I would have to split them up to calculate the index , reference and flags.The database was given to me in this format , I am forced to work with it the way it currently is , so i can not change it . and can only adapt my code to it.above example would be outputted as : <code> Index = 0 , Value = 3D95FF08Index = 1 , Value = 8D932A08 Index = 0 , Key = First , Value = 3D95FF08Index = 1 , Key = Second , Value = 8D932A08 Index = 0 , Key = First , Value = 3D , 95 , FF , 08Index = 1 , Key = Second , Value = 8D , 93 , 2A , 08 BYTE 0 1 2 3 to 6 ... ..HEX AD 12 01 0000859D ... .. Index Reference Link Flags Memb_Number_ID173 18 +A John ( ID : 34205 )
C # dictionary or just keep using lists ?
C_sharp : I have an extension for ActionResult that adds a toast to TempData when returning a page : and this is InformMessageResult : This works well with and the like , but fails withand the debugger highlightssaying InnerResult not set to an instance of an object.Is there a way I can make this work with Return Page ( ) ? Edit for additional info : I tested what was being sent in as the `` InnerResult '' and it looks like with Return Page ( ) , everything is null ( by design , I 'd say , as I do nothing to it before that point ) : with RedirectToPage ( ) : With Page ( ) : <code> public static IActionResult WithMessage ( this ActionResult result , InformMessage msg ) { return new InformMessageResult ( result , msg ) ; } public class InformMessageResult : ActionResult { public ActionResult InnerResult { get ; set ; } public InformMessage InformMessage { get ; set ; } public InformMessageResult ( ActionResult innerResult , InformMessage informMsg ) { InnerResult = innerResult ; InformMessage = informMsg ; } public override async Task ExecuteResultAsync ( ActionContext context ) { ITempDataDictionaryFactory factory = context.HttpContext.RequestServices.GetService ( typeof ( ITempDataDictionaryFactory ) ) as ITempDataDictionaryFactory ; ITempDataDictionary tempData = factory.GetTempData ( context.HttpContext ) ; tempData.Put ( `` InformMessage '' , InformMessage ) ; await InnerResult.ExecuteResultAsync ( context ) ; } } return RedirectToPage ( etc ) .WithMessage ( etc ) return Page ( ) .WithMessage ( etc ) await InnerResult.ExecuteResultAsync ( context ) ;
ActionResult extension does n't work with Page ( ) ActionResult method
C_sharp : Let 's say we have this class : If I add an object of this type to a Hashtable , then I can find the object using the identical string.But if the Hashtable contains the string not the object , it fails to find it when I pass the object.I 've tried overriding operator== and it made no difference.Is it possible to use implicit casting in a Hashtable in this way ? <code> public class Moo { string _value ; public Moo ( string value ) { this._value = value ; } public static implicit operator string ( Moo x ) { return x._value ; } public static implicit operator Moo ( string x ) { return new Moo ( x ) ; } public override bool Equals ( object obj ) { if ( obj is string ) return this._value == obj.ToString ( ) ; else if ( obj is Moo ) return this._value == ( ( Moo ) obj ) ._value ; return base.Equals ( obj ) ; } public override int GetHashCode ( ) { return _value.GetHashCode ( ) ; } } Moo moo = new Moo ( `` abc '' ) ; bool result1 = moo == `` abc '' ; //truebool result1a = moo.Equals ( `` abc '' ) ; //truebool result2 = `` abc '' == moo ; //truebool result2a = `` abc '' .Equals ( moo ) ; //truebool result2b = ( ( object ) '' abc '' ) .Equals ( moo ) ; //falseHashtable hash = new Hashtable ( ) ; hash [ moo ] = 100 ; object result3 = hash [ moo ] ; //100object result4 = hash [ `` abc '' ] ; //100hash = new Hashtable ( ) ; hash [ `` abc '' ] = 100 ; object result5 = hash [ moo ] ; //null ! ! ! ! object result6 = hash [ `` abc '' ] ; //100
Implicit casting of an object to string , for use in a Hashtable
C_sharp : I have created a little windows service which should delete all occurrences of a certain file name in certain folders.All this code runs in the elapsed-handler of the timer ( intervall=10s ) .When the service is running I can recognize a CPU increase up to 20 % used by that service , so I examined my code , put some trace commands in it and found out that executing the handler took about 3-4 seconds for nothing.I narrowed it down to the following piece of code : allReporterFiles.Count ( ) .It 's calling the method Count ( ) of this IEnumerable and this call takes 3-4 seconds.My project is setup for .NET 4.7.2 . Is this a framework bug or what ? <code> var files1 = Directory.EnumerateFiles ( dirSwReporter , swReporterFileName , SearchOption.AllDirectories ) ; var files2 = Directory.EnumerateFiles ( dirSwReporter2 , swReporterFileName , SearchOption.AllDirectories ) ; var allReporterFiles = files1.Union ( files2 ) ; var sw = Stopwatch.StartNew ( ) ; var fileCount = allReporterFiles.Count ( ) ; // < -- - takes ~3.5 seconds sw.Stop ( ) ; Trace.WriteLine ( $ '' KillChromeSoftwareReporterTool completed in : { sw.Elapsed.TotalMilliseconds } ms or { sw.Elapsed.TotalSeconds } sec '' ) ;
Call to IEnumerable.Count ( ) takes multiple seconds
C_sharp : I want to check if an icon exists in the systray ; as in , if `` X '' application has displayed their systray icon in the systray area.I 've Googled for information about how to do this but I did n't find anything . UPDATE : This what I 've tried in VB.NET translating the C # examples of the url gived by Robert comment , but I do n't know how to continue it . <code> Imports System.Runtime.InteropServicesPublic Class Form1 Public Declare Function FindWindow Lib `` user32.dll '' Alias `` FindWindowA '' ( ByVal lpClassName As String , ByVal lpWindowName As String ) As Long Public Declare Function FindWindowEx Lib `` user32.dll '' Alias `` FindWindowExA '' ( ByVal hWndParent As IntPtr , ByVal hWndChildAfter As IntPtr , ByVal lpClassName As String , ByVal lpWindowName As String ) As IntPtr Public Shared Function WindowHandle ( sTitle As String ) As Long Return FindWindow ( vbNullString , sTitle ) End Function Private Shared Function GetSystemTrayHandle ( ) As IntPtr Dim hWndTray As IntPtr = FindWindow ( `` Shell_TrayWnd '' , Nothing ) If hWndTray < > IntPtr.Zero Then hWndTray = FindWindowEx ( hWndTray , IntPtr.Zero , `` TrayNotifyWnd '' , Nothing ) If hWndTray < > IntPtr.Zero Then hWndTray = FindWindowEx ( hWndTray , IntPtr.Zero , `` SysPager '' , Nothing ) If hWndTray < > IntPtr.Zero Then hWndTray = FindWindowEx ( hWndTray , IntPtr.Zero , `` ToolbarWindow32 '' , Nothing ) Return hWndTray End If End If End If Return IntPtr.Zero End Function Private Sub Button1_Click ( sender As Object , e As EventArgs ) Handles Button1.Click MsgBox ( WindowHandle ( `` Steam '' ) ) ' 6687230 MsgBox ( GetSystemTrayHandle ( ) ) ' 62789 End SubEnd Class
Icon exists in systray ?
C_sharp : I have an application which saves documents ( think word documents ) in an Xml based format - Currently C # classes generated from xsd files are used for reading / writing the document format and all was well until recently when I had to make a change the format of the document . My concern is with backwards compatability as future versions of my application need to be able to read documents saved by all previous versions and ideally I also want older versions of my app to be able to gracefully handle reading documents saved by future versions of my app.For example , supposing I change the schema of my document to add an ( optional ) extra element somewhere , then older versions of my application will simply ignore the extra elemnt and there will be no problems : However if a breaking change is made ( an attribute is changed into an element for example , or a collection of elements ) , then past versions of my app should either ignore this element if it is optional , or inform the user that they are attempting to read a document saved with a newer version of my app otherwise . Also this is currently causing me headaches as all future versions of my app need entirely separate code is needed for reading the two different documents.An example of such a change would be the following xml : Changing to : In order to prevent support headaches in the future I wanted to come up with a decent strategy for handling changes I might make in the future , so that versions of my app that I release now are going to be able to cope with these changes in the future : Should the `` version number '' of the document be stored in the document itself , and if so what versioning strategy should be used ? Should the document version match the .exe assembly version , or should a more complex strategy be used , ( for example major revision changed indicate breaking changes , wheras minor revision increments indicate non-breaking changes - for example extra optional elements ) What method should I use to read the document itself and how do I avoid replicating massive amounts of code for different versions of documents ? Although XPath is obviously most flexible , it is a lot more work to implement than simply generating classes with xsd.On the other hand if DOM parsing is used then a new copy of the document xsd would be needed in source control for each breaking change , causing problems if fixes ever need to be applied to older schemas ( old versions of the app are still supported ) .Also , I 've worked all of this very loosly on the assumption that all changes I make can be split into these two categories of `` beaking changes '' and `` nonbreaking changes '' , but I 'm not entirely convinced that this is a safe assumption to make.Note that I use the term `` document '' very loosely - the contents dont resemble a document at all ! Thanks for any advice you can offer me . <code> < doc > < ! -- Existing document -- > < myElement > Hello World ! < /myElement > < /doc > < doc > < ! -- Existing document -- > < someElement contents= '' 12 '' / > < /doc > < doc > < ! -- Existing document -- > < someElement > < contents > 12 < /contents > < contents > 13 < /contents > < /someElement > < /doc >
How should I manage different incompatible formts of Xml based documents
C_sharp : Let 's imagine we have an animation that changes a Rectangle 's width from 50 to 150 when user moves the cursor over it and back from 150 to 50 when user moves the cursor away . Let the duration of each animation be 1 second.Everything is OK if user moves the cursor over the rectangle , then waits for 1 second for animation to finish , and then moves the cursor away from the rectangle . Two animations take 2 seconds totally and their speed is exactly what we are expecting to be.But if user moves the cursor away before the first animation ( 50 - > 150 ) is finished , the second animation 's duration will be 1 second but the speed of it will be very slow . I mean , the second animation will animate the rectangle 's width not from 150 to 50 but from let 's say 120 to 50 or from 70 to 50 if you take cursor away very fast . But for the same 1 second ! So what I want to understand is how to make the duration of the `` backwards '' animation to be dynamic . Dynamic based on at what point the first animation was stopped . Or , if I specify From and To values to 150 and 50 , Duration to 1 seconds and rectangle width will be 100 – WPF would calculate by itself that animation is 50 % done.I was testing different ways to use animation like Triggers , EventTrigger in style , and VisualStateGroups but no success.Here is a XAML sample that shows my problem . If you want to see by yourself what I am talking about , move the cursor over the rectangle , wait for 1-2 seconds ( first animation is finished ) then move the cursor away . After that , move the cursor over the rectangle for like 0.25 seconds and move it away . You will see that the rectangle 's width changes very slowly.Also , I would like to explain what calculation I am expecting to see.So let 's imagine another animation that goes from 100 to 1100 and has a duration of 2 seconds . If we stop it at the point of 300 , it must start to go back to 100 but not for 2 seconds but for : If we stop at 900 , duration will be : And if we let animation finish normally it will be : <code> < Rectangle Width= '' 50 '' Height= '' 100 '' HorizontalAlignment= '' Left '' Fill= '' Black '' > < Rectangle.Triggers > < EventTrigger RoutedEvent= '' MouseEnter '' > < BeginStoryboard > < Storyboard > < DoubleAnimation Storyboard.TargetProperty= '' Width '' To= '' 150 '' Duration= '' 0:0:1 '' / > < /Storyboard > < /BeginStoryboard > < /EventTrigger > < EventTrigger RoutedEvent= '' MouseLeave '' > < BeginStoryboard > < Storyboard > < DoubleAnimation Storyboard.TargetProperty= '' Width '' / > < /Storyboard > < /BeginStoryboard > < /EventTrigger > < /Rectangle.Triggers > ( ( 300 - 100 ) / ( 1100 - 100 ) ) * 2s = 0.4s ( ( 900 - 100 ) / ( 1100 - 100 ) ) * 2s = 1.6s ( ( 1100 - 100 ) / ( 1100 - 100 ) ) * 2s = 2s
How to make the duration of an animation dynamic ?
C_sharp : I follow the naming convention of MethodName_Condition_ExpectedBehaviourwhen it comes to naming my unit-tests that test specific methods.for example : But when I need to rename the method under test , tools like ReSharper does not offer me to rename those tests.Is there a way to prevent such cases to appear after renaming ? Like changing ReSharper settings or following a better unit-test naming convention etc . ? <code> [ TestMethod ] public void GetCity_TakesParidId_ReturnsParis ( ) { ... }
Is there a way to protect Unit test names that follows MethodName_Condition_ExpectedBehaviour pattern against refactoring ?
C_sharp : Does an IEnumerable have to use Yield to be deferred ? Here is test code which has helped me understand deferred execution and yield . <code> //immediate execution public IEnumerable Power ( int number , int howManyToShow ) { var result = new int [ howManyToShow ] ; result [ 0 ] = number ; for ( int i = 1 ; i < howManyToShow ; i++ ) result [ i ] = result [ i - 1 ] * number ; return result ; } //deferred but eager public IEnumerable PowerYieldEager ( int number , int howManyToShow ) { var result = new int [ howManyToShow ] ; result [ 0 ] = number ; for ( int i = 1 ; i < howManyToShow ; i++ ) result [ i ] = result [ i - 1 ] * number ; foreach ( var value in result ) yield return value ; } //deferred and lazy public IEnumerable PowerYieldLazy ( int number , int howManyToShow ) { int counter = 0 ; int result = 1 ; while ( counter++ < howManyToShow ) { result = result * number ; yield return result ; } } [ Test ] public void Power_WhenPass2AndWant8Numbers_ReturnAnEnumerable ( ) { IEnumerable listOfInts = Power ( 2 , 8 ) ; foreach ( int i in listOfInts ) Console.Write ( `` { 0 } `` , i ) ; } [ Test ] public void PowerYieldEager_WhenPass2AndWant8Numbers_ReturnAnEnumerableOfInts ( ) { //deferred but eager execution IEnumerable listOfInts = PowerYieldEager ( 2 , 8 ) ; foreach ( int i in listOfInts ) Console.Write ( `` { 0 } `` , i ) ; } [ Test ] public void PowerYield_WhenPass2AndWant8Numbers_ReturnAnEnumerableOfIntsOneAtATime ( ) { //deferred and lazy execution IEnumerable listOfInts = PowerYieldLazy ( 2 , 8 ) ; foreach ( int i in listOfInts ) Console.Write ( `` { 0 } `` , i ) ; }
Does an IEnumerable have to use Yield to be deferred
C_sharp : I read this article about Task.ConfigureAwait which can help to prevent deadlocks in async code.Looking at this code : ( I know I should n't do .Result , But it 's a part of the question ) This will result a deadlock because : The .Result - operation will then block the current thread ( i.e the UI thread ) while it waits for the async operation to complete.Once the network call is complete it will attempt to continue executing the response.StatusCode.ToString ( ) - method on the captured context . ( which is blocked - hence deadlock ) .One solution was to use : var response = await httpClient.GetAsync ( `` http : //www.google.com '' ) .ConfigureAwait ( false ) ; But other solution was to async all the way ( without blocking ) : Question : ( I 'm trying to understand how this code helps to solve the problem - via context POV ) .Does line # 3 and line # 10 captures different contexts ? Am I right regarding the way of flow as I think it is : line # 3 calls # 6 ( which calls # 10 ) and sees that it did n't finish yet , so it awaits ( captured context for # 3 = UI thread ) .Later on , line # 10 capture another context ( I will call it newContext ) after it finishes , it is back to `` newContext '' and then releases the UI context ( thread ) .Was I right ? Visualization : ( is this the right flow ? ) <code> private void Button_Click ( object sender , RoutedEventArgs e ) { string result = GetPageStatus ( ) .Result ; Textbox.Text = result ; } public async Task < string > GetPageStatus ( ) { using ( var httpClient = new HttpClient ( ) ) { var response = await httpClient.GetAsync ( `` http : //www.google.com '' ) ; return response.StatusCode.ToString ( ) ; } } /*1*/ private async void Button_Click ( object sender , RoutedEventArgs e ) /*2*/ { /*3*/ string result = await GetPageStatus ( ) ; /*4*/ Textbox.Text = result ; /*5*/ } /*6*/ public async Task < string > GetPageStatus ( ) /*7*/ { /*8*/ using ( var httpClient = new HttpClient ( ) ) /*9*/ { /*10*/ var response = await httpClient.GetAsync ( `` http : //www.google.com '' ) ; /*11*/ return response.StatusCode.ToString ( ) ; /*12*/ } /*13*/ }
await and deadlock prevention - clarification ?
C_sharp : this code that adds registers new EventHandler ( s ) for an event named as NewMail ( the eventargs class is named NewMailEventArgs . ( source : CLR via C # , chapter 11 Events ) What I do n't understand is the do part , first we are assigning newMail to prevHandler , then newMail is changed ( in CompareExchange ) to newHandler ? Then we are checking if newMail ! = prevHandler ? I am really kinda confused . Can any one help me understand what exactly is going on in here , specially in the do loop ? <code> // A PUBLIC add_xxx method ( xxx is the event name ) // Allows methods to register interest in the event.public void add_NewMail ( EventHandler < NewMailEventArgs > value ) { // The loop and the call to CompareExchange is all just a fancy way // of adding a delegate to the event in a thread-safe way . EventHandler < NewMailEventArgs > prevHandler ; EventHandler < NewMailEventArgs > newMail = this.NewMail ; do { prevHandler = newMail ; EventHandler < NewMailEventArgs > newHandler = ( EventHandler < NewMailEventArgs > ) Delegate.Combine ( prevHandler , value ) ; newMail = Interlocked.CompareExchange < EventHandler < NewMailEventArgs > > ( ref this.NewMail , newHandler , prevHandler ) ; } while ( newMail ! = prevHandler ) ; }
EventHandler : What is going on in this code ?
C_sharp : I am creating a AppDomain using the below codeBut _Domain.DynamicDirectory property does not exist . https : //msdn.microsoft.com/en-us/library/system.appdomain.dynamicdirectory ( v=vs.110 ) .aspx clearly says the AppDomainSetup.DynamicBase is used . What could be the reason executing in vstest.console.exe changes the behavior with App Domains . Is there a work around . <code> String pa = @ '' C : \Users\user\AppData\Local\Temp\2\db5fjamk.xnl '' ; System.IO.Directory.CreateDirectory ( pa ) ; AppDomainSetup setup = new AppDomainSetup ( ) ; setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory ; //f : \projectpath\out\debug-i386-unittest\UnitTestssetup.ApplicationName = string.Concat ( AppDomain.CurrentDomain.FriendlyName , DateTime.UtcNow.Ticks ) ; //UnitTestAdapter : Running test636559691791186101setup.DynamicBase = pa ; Evidence evidence = AppDomain.CurrentDomain.Evidence ; _Domain = AppDomain.CreateDomain ( setup.ApplicationName , evidence , setup ) ;
AppDomain.DynamicDirectory is not generated
C_sharp : Just thought I 'd see if somebody could explain why Anders decided that this is valid ... but this is not ... <code> if ( ... ) //single statementelse ///single statement try //single statementcatch //single statement
Single statement conditionals - why is the pattern not used for other code blocks ?
C_sharp : I have a legacy map viewer application using WinForms . It is sloooooow . ( The speed used to be acceptable , but Google Maps , Google Earth came along and users got spoiled . Now I am permitted to make if faster : ) After doing all the obvious speed improvements ( caching , parallel execution , not drawing what does not need to be drawn , etc ) , my profiler shows me that the real choking point is the coordinate transformations when converting points from map-space to screen-space.Normally a conversion code looks like this : The real implementation is trickier . Latitudes/longitues are represented as integers . To avoid loosing precision , they are multiplied up by 2^20 ( ~ 1 million ) . This is how a coordinate is represented.It is important that the possible scale factors are also explicitly bound to power of 2 . This allows us to replace the multiplication with a bitshift . So the real algorithm looks like this : ( UpperLeftPosition representents the upper-left corner of the screen in the map space . ) I am thinking now of offloading this calculation to the GPU . Can anyone show me an example how to do that ? We use .NET4.0 , but the code should preferably run on Windows XP , too . Furthermore , libraries under GPL we can not use . <code> public Point MapToScreen ( PointF input ) { // Note that North is negative ! var result = new Point ( ( int ) ( ( input.X - this.currentView.X ) * this.Scale ) , ( int ) ( ( input.Y - this.currentView.Y ) * this.Scale ) ) ; return result ; } public struct Position { public const int PrecisionCompensationPower = 20 ; public const int PrecisionCompensationScale = 1048576 ; // 2^20 public readonly int LatitudeInt ; // North is negative ! public readonly int LongitudeInt ; } public Point MapToScreen ( Position input ) { Point result = new Point ( ) ; result.X = ( input.LongitudeInt - this.UpperLeftPosition.LongitudeInt ) > > ( Position.PrecisionCompensationPower - this.ZoomLevel ) ; result.Y = ( input.LatitudeInt - this.UpperLeftPosition.LatitudeInt ) > > ( Position.PrecisionCompensationPower - this.ZoomLevel ) ; return result ; }
Offloading coordinate transformations to GPU
C_sharp : According to the MSDN : Because the Equals and GetHashCode methods on anonymous types are defined in terms of the Equals and GetHashcode of the properties , two instances of the same anonymous type are equal only if all their properties are equal.However , the following code demonstrates the compiler generated implementation for Equals ( ) is n't behaving as expected . : Am I missing something ? I am looking at the generated MSIL but do n't see an obvious error . Is there a way for MSIL level debugging ( besides WinDbg maybe ) ? Am I overlooking something ? I have tested .NET 3.5 ( VS 2008 SP1 compiler ) . For reference , here 's the generated Equals method : <code> DateTime start = new DateTime ( 2009,1,1 ) ; DateTime end = new DateTime ( 2010 , 12,31 ) ; // months since year 0 int startMonth = start.Date.Year * 12 + start.Date.Month - 1 ; int endMonth = end.Date.Year * 12 + end.Date.Month -1 ; // iterate through month-year pairs for ( int i = startMonth ; i < = endMonth ; i++ ) { var yearMonth = new { Year = ( int ) Math.Truncate ( i/12d ) , Month = ( i % 12 ) + 1 } ; if ( yearMonth.Year == 2009 & & yearMonth.Month == 2 ) Console.WriteLine ( `` BOOM '' ) ; if ( yearMonth == new { Year = 2009 , Month = 2 } ) Console.WriteLine ( `` I 'm never called ! `` ) ; Console.WriteLine ( yearMonth ) ; } public override bool Equals ( object value ) { var type = value as < > f__AnonymousType3 < < Year > j__TPar , < Month > j__TPar > ; return ( ( ( type ! = null ) & & EqualityComparer < < Year > j__TPar > .Default.Equals ( this. < Year > i__Field , type. < Year > i__Field ) ) & & EqualityComparer < < Month > j__TPar > .Default.Equals ( this. < Month > i__Field , type. < Month > i__Field ) ) ; }
`` == '' Operator Does n't Behave Like Compiler-generated Equals ( ) override for anonymous type
C_sharp : I am making a ListView inside my C # file . But instead of that I want to add the data I get from sqlite too the xaml file with data binding so I can still edit the layout with xaml . So every response from sqlite needs to be added as label ( < TextCell Text= '' { Binding Name } '' / > ) .My question : How can I bind the response from GetCategoryByMenuID to TextCell Text= '' { Binding Name } '' ? xaml page ( CategoriePage.xaml ) : Back-end / C # ( CategoriePage.xaml.cs ) : GetCategoryPage function : <code> < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < ContentPage xmlns= '' http : //xamarin.com/schemas/2014/forms '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2009/xaml '' x : Class= '' AmsterdamTheMapV3.CategoriePage '' > < ListView x : Name= '' listView '' > < ListView.ItemTemplate > < DataTemplate > < TextCell Text= '' { Binding Name } '' / > < /DataTemplate > < /ListView.ItemTemplate > < /ListView > < /ContentPage > namespace AmsterdamTheMapV3 { public partial class CategoriePage : ContentPage { public CategoriePage ( String txt ) { InitializeComponent ( ) ; var layout = new StackLayout { Padding = new Thickness ( 5 , 10 ) } ; int page = Int32.Parse ( txt ) ; this.Content = layout ; var categories = App.Database.GetCategoryByMenuID ( page ) ; var datatemplate = new DataTemplate ( ( ) = > { var nameLabel = new Label ( ) ; nameLabel.SetBinding ( Label.TextProperty , `` Name '' ) ; //nameLabel.SetBinding ( Label.idProperty , `` Name '' ) ; return new ViewCell { View = nameLabel } ; } ) ; var listView = new ListView { ItemsSource = categories , ItemTemplate = datatemplate } ; layout.Children.Add ( listView ) ; } } } public List < Categories > GetCategoryByMenuID ( int menuID ) { lock ( locker ) { return db.Table < Categories > ( ) .Where ( x = > x.Menu_ID == menuID ) .ToList ( ) ; } }
how can I bind a full response from SQLite ?
C_sharp : Here is some sample code I have basically written thousands of times in my life : And it seems to me C # should already have something that does this in just a line . Something like : But that does n't return the thing ( or an index to the thing , which would be fine ) , that returns the goodness-of-fit value.So maybe something like : But that 's doing a whole sort of the entire array and could be too slow.Does this exist ? <code> // find bestest thingyThing bestThing ; float bestGoodness = FLOAT_MIN ; foreach ( Thing x in arrayOfThings ) { float goodness = somefunction ( x.property , localvariable ) ; if ( goodness > bestGoodness ) { bestGoodness = goodness ; bestThing = x ; } } return bestThing ; return arrayOfThings.Max ( delegate ( x ) { return somefunction ( x.property , localvariable ) ; } ) ; var sortedByGoodness = from x in arrayOfThings orderby somefunction ( x.property , localvariable ) ascending select x ; return x.first ;
Return best fit item from collection in C # 3.5 in just a line or two
C_sharp : Is there a way to change C # object values all at once ... in one line ? So if I have a class Result with string msg and bool isPositive and I already call the constructor somewhere before like var result = new Result ( ) ; can I change values somehow by not entering : But doing something like what you can do while instantiating : I know I can do it by instantiating again a new object by : but that is not my question : ) <code> result.msg = `` xxxxxx '' ; result.bool = false ; result { msg = `` '' , bool = true } var result = new Result ( ) { msg = `` '' , bool = true }
C # initialized object values
C_sharp : I have 1 Table in Oracle SQL Developer which containts 1 column as Float.Data reader have should return Decimal for oracle float datatype as per the table given here : https : //docs.microsoft.com/en-us/dotnet/framework/data/adonet/oracle-data-type-mappingsBut the problem is datareader returns double as datatype for Float Column as shown below : But the problem is datareader returns double as datatype for NREAL as Float and NFLOAT1 as float and surprisinglydatareader returns Decimal for both the column as shown below : Code : I am using : Oracle.ManagedDataAccess.Client Is that a bug inside Oracle.ManagedDataAccess.Client library or I am doing something wrong ? Update : Based on comments I want to mention something : Although I might have reference to different source documentation not applicable to oracle library I am using , bt still I am getting decimal datatype for my other 2 columns i.e NREAL and NFLOAT1 so why this behaviour is not consistent ? <code> static void Test ( ) { using ( OracleConnection connection = new OracleConnection ( `` connection string '' ) { connection.Open ( ) ; using ( OracleCommand command = connection.CreateCommand ( ) ) { command.CommandText = `` select id , NFLOAT from Numeric_Table '' ; using ( OracleDataReader reader = command.ExecuteReader ( ) ) { for ( int i = 0 ; i < reader.FieldCount ; i++ ) { var columnName = reader.GetName ( i ) ; var dotNetType = reader.GetFieldType ( i ) ; var sqlType = reader.GetDataTypeName ( i ) ; } } } } }
DataReader returning incorrect .net datatype for database table float column
C_sharp : Good day , I need to make function that will iterate on Dictionary that stores variable name and variable ` s new value . After that , I need to update class variable with that value.It works but I want little improvement and I absolutely do n't know if it is possible . As you can see , that function can accept any class , not just one specific . If I have class like thisAnd I would use function this way , it would work.Problem is if I have class like this and I would like to update `` subfield '' ( field in field ) I was thinking that syntax could be something like this , but I have no idea how could I do it.To sum it up , I need to make function that will take class that is stored in another class . Function will iterate trough the dictionary and update fields of class and even her subfields . <code> void UpdateValues ( Type type , Dictionary < string , string > values ) { foreach ( var value in values ) { var fieldInfo = selected.GetComponent ( type ) .GetType ( ) .GetField ( value.Key ) ; if ( fieldInfo == null ) continue ; fieldInfo.SetValue ( selected.GetComponent ( type ) , value.Value ) ; } } class test { public string age ; } UpdateValues ( typeof ( test ) , new Dictionary < string , string > { { `` age '' , `` 17 '' } } ) ; class test { public string age ; } class test2 { public test data ; } UpdateValues ( typeof ( test2 ) , new Dictionary < string , string > { { `` data.age '' , `` 17 '' } } ) ;
FieldInfo update subfield of field
C_sharp : I encountered a behavior in VB.NET today regarding boxing and reference comparison that I did not expect . To illustrate I wrote a simple program which tries to atomically update a variable of any type.Here is a program in C # ( https : //dotnetfiddle.net/VsMBrg ) : The output of this program is : This is as expected and everything seems to work fine.Here is the same program in VB.NET ( https : //dotnetfiddle.net/lasxT2 ) : Here the output is : Here the last statement is false which means that the set did not work.Am I doing something wrong here or is the problem in the VB.NET ? ( Note : Ignore the Volatile reads/writes , this example has no threads so it is not affected by threading ) Edit : If I change the T to integer then everything works OK : ( dotnetfiddle.net/X6uLZs ) . Also if I change T to a custom class it also works OK : dotnetfiddle.net/LnOOme <code> using System ; public static class Program { private static object o3 ; public static void Main ( ) { Console.WriteLine ( `` Hello World '' ) ; Test < DateTimeOffset ? > value = new Test < DateTimeOffset ? > ( ) ; Console.WriteLine ( value.Value == null ) ; DateTimeOffset dt1 = new DateTimeOffset ( 2017 , 1 , 1 , 1 , 1 , 1 , TimeSpan.Zero ) ; DateTimeOffset dt2 = new DateTimeOffset ( 2017 , 1 , 2 , 1 , 1 , 1 , TimeSpan.Zero ) ; Console.WriteLine ( value.TrySetValue ( null , dt1 ) ) ; Console.WriteLine ( value.Value == dt1 ) ; // this should fail Console.WriteLine ( value.TrySetValue ( null , dt2 ) ) ; Console.WriteLine ( value.Value == dt1 ) ; // this should succeed Console.WriteLine ( value.TrySetValue ( dt1 , dt2 ) ) ; } } public class Test < T > { public T Value { get { return ( T ) System.Threading.Volatile.Read ( ref _value ) ; } } private object _value ; public bool TrySetValue ( T oldValue , T newValue ) { object curValObj = System.Threading.Volatile.Read ( ref _value ) ; if ( ! object.Equals ( ( T ) curValObj , oldValue ) ) return false ; object newValObj = ( object ) newValue ; return object.ReferenceEquals ( System.Threading.Interlocked.CompareExchange ( ref _value , newValObj , curValObj ) , curValObj ) ; } } Hello WorldTrueTrueTrueFalseTrueTrue Imports SystemPublic Module Module1 private o3 as object Public Sub Main ( ) Console.WriteLine ( `` Hello World '' ) Dim value As New Test ( Of DateTimeOffset ? ) Console.WriteLine ( value.Value is nothing ) Dim dt1 As New DateTimeOffset ( 2017 , 1 , 1 , 1 , 1 , 1 , TimeSpan.Zero ) Dim dt2 As New DateTimeOffset ( 2017 , 1 , 2 , 1 , 1 , 1 , TimeSpan.Zero ) Console.WriteLine ( value.TrySetValue ( Nothing , dt1 ) ) Console.WriteLine ( value.Value = dt1 ) ' This should fail Console.WriteLine ( value.TrySetValue ( Nothing , dt2 ) ) Console.WriteLine ( value.Value = dt1 ) ' This should succeed Console.WriteLine ( value.TrySetValue ( dt1 , dt2 ) ) End SubEnd Modulepublic class Test ( Of T ) Public readonly Property Value As T Get Return CType ( Threading.Volatile.Read ( _value ) , T ) End Get End Property Private _value As Object Public Function TrySetValue ( oldValue As T , newValue As T ) As Boolean Dim curValObj As Object = Threading.Volatile.Read ( _value ) If Not Object.Equals ( CType ( curValObj , T ) , oldValue ) Then Return False Dim newValObj = CObj ( newValue ) Return Object.ReferenceEquals ( Threading.Interlocked.CompareExchange ( _value , newValObj , curValObj ) , curValObj ) End Functionend class Hello WorldTrueTrueTrueFalseTrueFalse
Difference in object boxing / comparing references between C # and VB.Net
C_sharp : As per this msdn documentationIf the current instance is a reference type , the Equals ( Object ) method tests for reference equality , and a call to the Equals ( Object ) method is equivalent to a call to the ReferenceEquals method.then why does following code results in two different result of method calls Equals method returning True and ReferenceEquals method returning false , even though the obj and obj1 is reference type as IsClass property returns true.Output : obj.IsClass : Trueobject.ReferenceEquals ( obj , obj1 ) : Falseobj.Equals ( obj1 ) : True <code> using System ; public class Program { public static void Main ( ) { var obj = new { a = 1 , b = 1 } ; var obj1 = new { a = 1 , b = 1 } ; Console.WriteLine ( `` obj.IsClass : `` + obj.GetType ( ) .IsClass ) ; Console.WriteLine ( `` object.ReferenceEquals ( obj , obj1 ) : `` + object.ReferenceEquals ( obj , obj1 ) ) ; Console.WriteLine ( `` obj.Equals ( obj1 ) : `` + obj.Equals ( obj1 ) ) ; } }
Why do the results of the Equals and ReferenceEquals methods differ even though variables are reference types ?
C_sharp : I 'm trying to create a small code generator using Roslyn or as it is called now .NET Compiler Platform , prevously I worked with codedom , which was cumbersome but MSDN got a reference , now Roslyn has little documentation and all documentation is focused on code analysis instead of code generation.So my question is simple : How can I create something like : using the Compiler Platform classes ? I 've found something like FieldDeclarationSyntax and ExpressionSyntax , but all samples I 've found generate things like Myclass myvariable = new Myclass ( ) ; And there is nothing telling me something so simple as how to produce thestring type declaration.any clue will be great.Thank you in advance <code> private const string MyString = `` This is my string '' ;
Howto create a const declaration using .NET Compiler Platform
C_sharp : Is there any difference between accessing a property that has a backing fieldversus an auto-property ? The reason I 'm asking is that when letting ReSharper convert a property into an auto property it seems to scan my entire solution , or at least all aspx-files . I ca n't see any reason why there should be any difference between the two from outside the class . Is there ? <code> private int _id ; public int Id { get { return _id ; } set { _id = value ; } } public int Id { get ; set ; }
Why does ReSharper need to scan all files when converting a property to an auto property ?
C_sharp : there are several threads on value-ranges in enums ( not possible ) .But I have the following problem and search the best solution , where none of the provided once really satisfied me.A specification of a protocol says that byte [ x ] of a message , the messagetype , has the following possible values ( fantasy values ) : So there are only 3 different logical options , which would best be dealt with in an enum . But one of the n logical options has m different numerical counterparts , which is impossible to be dealt with in an enum.Now what is the best ( cleanest ) solution for such a problem ? I could build a classI could also create a class without an enum , but with static members.Either way there is one Problem : If someone tries to dispatch a packet , he might use But messageByte [ x ] could be anything between 0x02 and 0xFF , so `` hitting '' the value specified in the enum would be pure luck . On the other side I want the enum ( or static member ) to be public for easy message-building . Can I somehow enforce the use of my getLogicalValue ( ) -Function ? Is there a more elegant solution ? All I want is an easy and well-structured way to link logical values to numerical values in a n : m relation . Especially as the given protocol has many such cases and I would like to keep my code neat.Thanks for your help and time : ) Janis <code> 0x00 = get0x01 = set 0x02 to 0xFF = identify class MessageType { public enum MessageTypeEnum { get = 0x00 , set = 0x01 , identify = 0x02 } public static MessageTypeEnum getLogicalValue ( byte numericalValue ) { if ( numericalValue < 0x02 ) return ( MessageTypeEnum ( numericalValue ) ) ; else return MessageTypeEnum.identify ; } } if ( messageBytes [ x ] == ( byte ) MessageTypeEnum.identify ) { // do stuff }
C # alternative to enums for a n : m-relation
C_sharp : Ok , so I 'm a bit confused as to what is going on with the following data.We have the following Structure in our application : Portal.Web - An MVC 3 Web App which basically contains all theviews , scripts , css and HTML helper extension methodsPortal.Core - A Class Library which is basically our Business Objects , we have all of our models contained within this project.Portal.Data - Another Class Library which contains our NHibernate config and our DTO classes.Here 's our usage : In the controller we call the model located in Portal.Core , which populates by calling Portal.Data , so basically Web can never see data.Here 's the catch : In the controller , say for example I try and instantiate a new DTO object called Client like so : It wo n't work , which is expected it has no idea what Client is and even specifying a using wo n't cut it . That 's fine.BUT if I try and do that exact same line in the View , Resharper adds the using to the view and then no complaints , the project runs and we can use DTO classes in our views.So the question is , why is this ? I 'm trying to stop our juniors from using DTO classes in Views , so I 've purposely removed the reference to the Data project in Web , but they can still use the classes . Can someone shed some light ? <code> var client = new Client ( ) ;
Can MVC Views access all projects even though they are n't referenced by the project where the views are ?
C_sharp : I 'm trying to set the image on a TableCell.This is my code : This works perfect while testing on an emulator , but when I try to debug this on my iPhone 5 , I get this error : The error happens on the line where I load the image : <code> public override UITableViewCell GetCell ( UITableView tableView , MonoTouch.Foundation.NSIndexPath indexPath ) { UITableViewCell cell = tableView.DequeueReusableCell ( cellIdentifier ) ; Parking parking = ( tableItems.ToArray ( ) [ indexPath.Row ] as Parking ) ; if ( cell == null ) { cell = new UITableViewCell ( UITableViewCellStyle.Subtitle , cellIdentifier ) ; } cell.TextLabel.Text = parking.Name ; UIImage img = UIImage.FromBundle ( `` occupied '' ) ; cell.ImageView.Image = img ; cell.DetailTextLabel.Text = parking.GenerateSubtitle ( ) ; cell.Accessory = UITableViewCellAccessory.DisclosureIndicator ; return cell ; } System.InvalidCastException : Can not cast from source type to destination type . at MonoTouch.UIKit.UIImage.FromBundle ( System.String name ) [ 0x0001e ] in /Developer/MonoTouch/Source/monotouch/src/UIKit/UIImage.g.cs:198 at parko_iphone.MainTableSource.GetCell ( MonoTouch.UIKit.UITableView tableView , MonoTouch.Foundation.NSIndexPath indexPath ) [ 0x0004c ] in /Users/gertpoppe/projects/parko_iphone/parko_iphone/CustomComponents/MainTableSource.cs:34 at at ( wrapper managed-to-native ) MonoTouch.ObjCRuntime.Messaging : void_objc_msgSend ( intptr , intptr ) at MonoTouch.UIKit.UIWindow.MakeKeyAndVisible ( ) [ 0x00008 ] in /Developer/MonoTouch/Source/monotouch/src/UIKit/UIWindow.g.cs:129 at parko_iphone.AppDelegate.FinishedLaunching ( MonoTouch.UIKit.UIApplication app , MonoTouch.Foundation.NSDictionary options ) [ 0x0002e ] in /Users/gertpoppe/projects/parko_iphone/parko_iphone/AppDelegate.cs:35 at at ( wrapper managed-to-native ) MonoTouch.UIKit.UIApplication : UIApplicationMain ( int , string [ ] , intptr , intptr ) at MonoTouch.UIKit.UIApplication.Main ( System.String [ ] args , System.String principalClassName , System.String delegateClassName ) [ 0x0004c ] in /Developer/MonoTouch/Source/monotouch/src/UIKit/UIApplication.cs:38 at parko_iphone.Application.Main ( System.String [ ] args ) [ 0x00008 ] in /Users/gertpoppe/projects/parko_iphone/parko_iphone/Main.cs:16 UIImage img = UIImage.FromBundle ( `` occupied '' ) ;
Error on loading image when testing on iPhone 5
C_sharp : I always thought base.Something was equivalent to ( ( Parent ) this ) .Something , but apparently that 's not the case . I thought that overriding methods eliminated the possibility of the original virtual method being called.Why is the third output different ? <code> void Main ( ) { Child child = new Child ( ) ; child.Method ( ) ; //output `` Child here ! '' ( ( Parent ) child ) .Method ( ) ; //output `` Child here ! '' child.BaseMethod ( ) ; //output `` Parent here ! `` } class Parent { public virtual void Method ( ) { Console.WriteLine ( `` Parent here ! `` ) ; } } class Child : Parent { public override void Method ( ) { Console.WriteLine ( `` Child here ! `` ) ; } public void BaseMethod ( ) { base.Method ( ) ; } }
Virtual base members not seeing overrides ?
C_sharp : I have read in Jon 's Skeet online page about how to create a thread safe Singleton in C # http : //csharpindepth.com/Articles/General/Singleton.aspxin the paragraph below this code it says : As hinted at before , the above is not thread-safe . Two different threads could both have evaluated the test if ( instance==null ) and found it to be true , then both create instances , which violates the singleton pattern . Note that in fact the instance may already have been created before the expression is evaluated , but the memory model does n't guarantee that the new value of instance will be seen by other threads unless suitable memory barriers have been passed.Can you please explain why does n't the memory model does not guarantee that the new value of instance will be seen by other threads ? the static variable is located on the heap , but why it is not shared with other threads immediately ? do we need to wait for the context switch so the other thread will know the instance is not null anymore ? <code> // Bad code ! Do not use ! public sealed class Singleton { private static Singleton instance=null ; private Singleton ( ) { } public static Singleton Instance { get { if ( instance==null ) { instance = new Singleton ( ) ; } return instance ; } } }
Thread safe Singleton : why the memory model does not guarantee that the new instance will be seen by other threads ?
C_sharp : Given a generic type T in C # , I wonder how to acquire type Q , which is equal to T ? for non-nullable T , and T for already nullable T.The question arose from real code . I want to unify access to parameters passed through query string in my ASP.NET application . And I want to specify a default value of the same type , but ensure null can be passed as a default value.Currently I 'm forced having two overloads of the FetchValue - one without default value , and one with it : It works fine , but I wonder whether it is possible to merge both functions like this.In C++ I would use type-traits , like PromoteNullable < T > : :type with two specializations of PromoteNullable for both nullable and non-nullable types . But what about C # ? <code> public static T FetchValue < T > ( string name , < T ? for non-nullable , T otherwise > default_value = null ) // How to write this ? { var page = HttpContext.Current.Handler as Page ; string str = page.Request.QueryString [ name ] ; if ( str == null ) { if ( default_value == null ) { throw new HttpRequestValidationException ( `` A `` + name + `` must be specified . `` ) ; } else { return default_value ; } } return ( T ) Convert.ChangeType ( str , typeof ( T ) ) ; } public static T FetchValue < T > ( string name ) ; public static T FetchValue < T > ( string name , T default_value ) ;
`` Promote '' generic type to Nullable in C # ?
C_sharp : When button1 is clicked , the below code is executed which will run a PowerShell script to get the current SQL Server Instances . However when this is run , the result set ( results variable ) has a count of 0 rows from the PowerShell output . When I run the same code in native PowerShell it displays 3 rows with the instance names.Can anyone advise if I am missing something ? <code> private void button1_Click ( object sender , EventArgs e ) { //If the logPath exists , delete the file string logPath = `` Output.Log '' ; if ( File.Exists ( logPath ) ) { File.Delete ( logPath ) ; } string [ ] Servers = richTextBox1.Text.Split ( '\n ' ) ; //Pass each server name from the listview to the 'Server ' variable foreach ( string Server in Servers ) { //PowerShell Script string PSScript = @ '' param ( [ Parameter ( Mandatory = $ true , ValueFromPipeline = $ true ) ] [ string ] $ server ) Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned -Force ; Import-Module SQLServer ; Try { Set-Location SQLServer : \\SQL\\ $ server -ErrorAction Stop ; Get-ChildItem | Select-Object -ExpandProperty Name ; } Catch { echo 'No SQL Server Instances ' ; } `` ; //Create PowerShell Instance PowerShell psInstance = PowerShell.Create ( ) ; //Add PowerShell Script psInstance.AddScript ( PSScript ) ; //Pass the Server variable in to the $ server parameter within the PS script psInstance.AddParameter ( `` server '' , Server ) ; //Execute Script Collection < PSObject > results = new Collection < PSObject > ( ) ; try { results = psInstance.Invoke ( ) ; } catch ( Exception ex ) { results.Add ( new PSObject ( ( Object ) ex.Message ) ) ; } //Loop through each of the results in the PowerShell window foreach ( PSObject result in results ) { File.AppendAllText ( logPath , result + Environment.NewLine ) ; // listBox1.Items.Add ( result ) ; } psInstance.Dispose ( ) ; } }
Powershell resultset not being picked up in C #
C_sharp : I am trying to build a simple leave request application in windows workflow foundation 4.5 , it throws the following exception as the workflow tries to complete without waiting for approveRequest activity . Two SendParameters objects with same ServiceContractName and OperationName 'ApplyLeave ' have different parameter names.Can you please suggest me what is missing ? } and hosted as mentioned below <code> using System ; using System.ServiceModel.Activities ; using System.Activities ; using System.ServiceModel ; using System.Activities.Statements ; namespace DemoWF { public class _25_LeaveRequest { public WorkflowService GetInstance ( ) { WorkflowService service ; Variable < int > empID = new Variable < int > { Name = `` empID '' } ; Variable < int > requestID = new Variable < int > { Name = `` requestID '' } ; Receive receiveLeaveRequest = new Receive { ServiceContractName = `` ILeaveRequestService '' , OperationName = `` ApplyLeave '' , CanCreateInstance = true , Content = new ReceiveParametersContent { Parameters = { { `` empID '' , new OutArgument < int > ( empID ) } } } } ; SendReply replyLeaveRequestID = new SendReply { Request = receiveLeaveRequest , Content = new SendParametersContent { Parameters = { { `` requestID '' , new InArgument < int > ( requestID ) } , } , } , } ; Receive approveRequest = new Receive { ServiceContractName = `` ILeaveRequestService '' , OperationName = `` ApproveLeave '' , CanCreateInstance = true , Content = new ReceiveParametersContent { Parameters = { { `` requestID '' , new OutArgument < int > ( requestID ) } } } } ; SendReply sendApproval = new SendReply { Request = receiveLeaveRequest , Content = new SendParametersContent { Parameters = { { `` approved '' , new InArgument < int > ( 0 ) } , } , } , } ; Sequence workflow = new Sequence ( ) { Variables = { empID , requestID } , Activities = { new WriteLine { Text= '' WF service is starting ... '' } , receiveLeaveRequest , new WriteLine { Text=new InArgument < string > ( aec= > `` Emp ID= '' +empID.Get ( aec ) .ToString ( ) ) } , new Assign < int > { Value=new InArgument < int > ( 5 ) , To=new OutArgument < int > ( requestID ) } , new WriteLine { Text=new InArgument < string > ( aec= > `` Request ID= '' +requestID.Get ( aec ) .ToString ( ) ) } , replyLeaveRequestID , approveRequest , new WriteLine { Text= '' Approved '' } , sendApproval } , } ; service = new WorkflowService { Name = `` AddService '' , Body = workflow } ; return service ; } } namespace DemoWF { class Program { static void Main ( string [ ] args ) { LeaveRequest ( ) ; } private static void LeaveRequest ( ) { _25_LeaveRequest receiveAndReplyWorkflow = new _25_LeaveRequest ( ) ; WorkflowService wfService = receiveAndReplyWorkflow.GetInstance ( ) ; Uri address = new Uri ( `` http : //localhost:8000/WFServices '' ) ; WorkflowServiceHost host = new WorkflowServiceHost ( wfService , address ) ; try { Console.WriteLine ( `` Opening Service ... '' ) ; host.Open ( ) ; Console.WriteLine ( `` WF service is listening on `` + address.ToString ( ) + `` , press any key to close '' ) ; Console.ReadLine ( ) ; } catch ( Exception e ) { Console.WriteLine ( `` some thing bad happened '' + e.StackTrace ) ; } finally { host.Close ( ) ; } } } }
Human based task in windows workflow foundation
C_sharp : I have a stylesheet in my application ~/Content/theme/style.css . It is referenced in my application using standard bundling as such : Now , I have used a Sass compiler ( Libsass ) to allow me to change the output style.css file to a customised user output file as required.So basically I do something like this.and then I save like this.However intermittently I receive the following dreaded access error : `` The process can not access the file C : ... .\style.css '' because it is being used by another process . '' ( Note : This occurs at the File.WriteAllText line ) This does n't make sense because I do not open any streams to the file and perform what I assume to be a single atomic operation using File.WriteAllText.Now I have also noticed that this error is particularly likely when I use two different browsers to modify this file consecutively.My assumption is that one of two things is happening . Either : a . The bundling packager is somehow locking the file because it has been modified while it updates the bundles and not releasing the lock or b . Because two different connections access the file somehow a lock persists across them.So , has anyone run into anything similar ? Any suggestions on how I might be able to fix this issue ? PS : I have tried using HttpRuntime.UnloadAppDomain ( ) ; as a hacky way to try and release any locks on the file but this does n't seem to be helping . <code> bundles.Add ( new StyleBundle ( `` ~/Content/css '' ) .Include ( `` ~/Content/font-awesome/font-awesome.css '' , `` ~/Content/theme/style.css '' ) ) ; CompilationResult compileResult = SassCompiler.CompileFile ( Server.MapPath ( Path.Combine ( WebConfigSettings.RootSassPath , `` style.scss '' ) , options : new CompilationOptions { SourceMap = true , SourceMapFileUrls = true } ) ; string outputPath = Server.MapPath ( WebConfigSettings.ThemeOutputPath ) ; if ( System.IO.File.Exists ( outputPath ) ) System.IO.File.Copy ( outputPath , string.Format ( `` { 0 } .bak '' , outputPath ) , true ) ; System.IO.File.WriteAllText ( Server.MapPath ( WebConfigSettings.ThemeOutputPath ) , compileResult.CompiledContent ) ;
Overwriting ASP.NET MVC active stylesheet bundle
C_sharp : I am annoyed because I would like to call a generic method from a another generic method..Here is my code : So in fact when I call ToList who is an extension to DataTable class ( learned Here ) The compiler says that Y is not a non-abstract Type and he ca n't use it for .ToList < > generic method..What am I doing wrong ? Thanks for reading.. <code> public List < Y > GetList < Y > ( string aTableName , bool aWithNoChoice ) { this.TableName = aTableName ; this.WithNoChoice = aWithNoChoice ; DataTable dt = ReturnResults.ReturnDataTable ( `` spp_GetSpecificParametersList '' , this ) ; //extension de la classe datatable List < Y > resultList = ( List < Y > ) dt.ToList < Y > ( ) ; return resultList ; }
Call a generic method with a generic method
C_sharp : I often work with classes that represent entities produced from a factory . To enable easy testing of my factories easily I usually implement IEquatable < T > , whilst also overriding GetHashCode and Equals ( as suggested by the MSDN ) .For example ; take the following entity class which is simplified for example purposes . Typically my classes have a bunch more properties . Occasionally there is a also collection , which in the Equals method I check using SequenceEqual.This means I can then do simple unit tests like so ( assuming the constructor is tested elsewhere ) .However this raises a number of questions.GetHashCode is n't actually used but I 've spent time implementing it.I rarely actually want to use Equals in my actual application beyond testing . I spend more time writing more tests to ensure the Equals actually works correctly.I now have another three methods to maintain , e.g . add a property to the class , update methods.But , this does give me a very neat TestMethod.Is this an appropriate use of IEquatable , or should I take another approach ? <code> public class Product : IEquatable < Product > { public string Name { get ; private set ; } public Product ( string name ) { Name = name ; } public override bool Equals ( object obj ) { if ( obj == null ) { return false ; } Product product = obj as Product ; if ( product == null ) { return false ; } else { return Equals ( product ) ; } } public bool Equals ( Product other ) { return Name == other.Name ; } public override int GetHashCode ( ) { return Name.GetHashCode ( ) ; } } [ TestMethod ] public void TestFactory ( ) { Product expected = new Product ( `` James '' ) ; Product actual = ProductFactory.BuildJames ( ) ; Assert.AreEqual ( expected , actual ) ; }
Should I be using IEquatable to ease testing of factories ?
C_sharp : I have a task to create program that 'll match digits without numbers infront of them . For example : 6x^2+6x+6-57+8-9-90xI 'm trying to use Regex to capture all numbers with + or - before them - but without x afterwards . I 've tried but it seems to capture the '-90 ' from '-90x ' as well . <code> \ [ +- ] ( \d+ ) [ ^x ]
Regex - Capture only numbers that do n't have a letter next to them
C_sharp : I ran the following console application : in order to compare the time we need to iterate through the elements of a collection and if it was better to build this collection using a List or an IEnumerable . To my surprise , the result it was 00:00:00.0005504 for the List and 00:00:00.0016900 for the IEnumerable . I was expecting that the second way , IEnumerable , it would be faster because the values are created on the fly and we do n't have to add them each one of them one item at the time , like in the case of a List and then iterate through it . Could please someone explain me this difference ? Why we got this behavior and no the opposite one . Thanks in advance for any help ! <code> class Program { static void Main ( string [ ] args ) { int n = 10000 ; Stopwatch s = new Stopwatch ( ) ; s.Start ( ) ; List < int > numbers = GetListNumber ( n ) ; foreach ( var number in numbers ) { } s.Stop ( ) ; Console.WriteLine ( s.Elapsed ) ; Console.WriteLine ( ) ; s.Restart ( ) ; foreach ( var number in GetEnumerator ( n ) ) { } s.Stop ( ) ; Console.WriteLine ( s.Elapsed ) ; Console.ReadKey ( ) ; } static List < int > GetListNumber ( int n ) { List < int > numbers = new List < int > ( ) ; for ( int i = 0 ; i < n ; i++ ) numbers.Add ( i ) ; return numbers ; } static IEnumerable < int > GetEnumerator ( int n ) { for ( int i = 0 ; i < n ; i++ ) yield return i ; } }
List < T > vs IEnumerable < T >
C_sharp : Is it possible to execute code quick test in VS2010 ? For example I would like to test code below just selecting it in code editor and execute it by passing variables ? <code> public static int GetInt ( object value ) { int result ; Int32.TryParse ( GetString ( value ) , out result ) ; return result ; }
Quick test code option in VS2010
C_sharp : I 'm doing a code review and found a line where one of our developers is creating an object using an empty object initializer like this : I do n't know why he would instantiate this way rather than : Are there any downsides to object instantiation using empty object initializers ? Other than being stylistically inconsistent I want to know if there is a reason avoid this approach . Something tells me this smells but I want to be sure before I say anything . <code> List < Floorplan > floorplans = new List < Floorplan > { } ; List < Floorplan > floorplans = new List < Floorplan > ( ) ;
Are there any downsides to using an empty object initializer ?
C_sharp : Here is my code : I got a process by its id . That worked fineThen I tried to send something to its stdin . That threw an InvalidOperationException . Note : the exception occured when I tried to get the StandardInput , not when I tried to us WriteLine.I believe I know why I got the exception . The process was not started by my application , so I never had the chance to set RedirectStandardInput to true.My goal is to be able to use this app to send text to a python interactive console ( or another language ) . I still want to be able to enter text myself to the python prompt , but I also want to give my app control too.How do I do this ? <code> static void Main ( string [ ] args ) { if ( args.Length > 1 ) { int id ; if ( int.TryParse ( args [ 0 ] , out id ) ) { try { var p = Process.GetProcessById ( id ) ; p.StandardInput.WriteLine ( args [ 1 ] ) ; } catch ( ArgumentException ) { Console.WriteLine ( $ '' Could n't find process with id { id } '' ) ; } } else { Console.WriteLine ( $ '' Could n't find process with id { args [ 0 ] } '' ) ; } } }
Writeline to already running process
C_sharp : In C # 5 , the closure semantics of the foreach statement ( when the iteration variable is `` captured '' or `` closed over '' by anonymous functions ) was famously changed ( link to thread on that topic ) .Question : Was it the intention to change this for arrays of pointer types also ? The reason why I ask is that the `` expansion '' of a foreach statement has to be rewritten , for technical reasons ( we can not use the Current property of the System.Collections.IEnumerator since this property has declared type object which is incompatible with a pointer type ) as compared to foreach over other collections . The relevant section in the C # Language Specification , `` Pointer arrays '' , in version 5.0 , says that : is expanded to : We note that the declaration V v ; is outside all the for loops . So it would appear that the closure semantics are still the `` old '' C # 4 flavor , `` loop variable is reused , loop variable is `` outer '' with respect to the loop '' .To make it clear what I am talking about , consider this complete C # 5 program : So what is the correct output of the above program ? <code> foreach ( V v in x ) EMBEDDED-STATEMENT { T [ , ,… , ] a = x ; V v ; for ( int i0 = a.GetLowerBound ( 0 ) ; i0 < = a.GetUpperBound ( 0 ) ; i0++ ) for ( int i1 = a.GetLowerBound ( 1 ) ; i1 < = a.GetUpperBound ( 1 ) ; i1++ ) … for ( int in = a.GetLowerBound ( N ) ; iN < = a.GetUpperBound ( n ) ; iN++ ) { v = ( V ) a.GetValue ( i0 , i1 , … , iN ) ; EMBEDDED-STATEMENT } } using System ; using System.Collections.Generic ; static class Program { unsafe static void Main ( ) { char* zeroCharPointer = null ; char* [ ] arrayOfPointers = { zeroCharPointer , zeroCharPointer + 1 , zeroCharPointer + 2 , zeroCharPointer + 100 , } ; var list = new List < Action > ( ) ; // foreach through pointer array , capture each foreach variable 'pointer ' in a lambda foreach ( var pointer in arrayOfPointers ) list.Add ( ( ) = > Console.WriteLine ( `` Pointer address is { 0 : X2 } . `` , ( long ) pointer ) ) ; Console.WriteLine ( `` List complete '' ) ; // invoke those delegates foreach ( var act in list ) act ( ) ; } // Possible output : // // List complete // Pointer address is 00 . // Pointer address is 02 . // Pointer address is 04 . // Pointer address is C8 . // // Or : // // List complete // Pointer address is C8 . // Pointer address is C8 . // Pointer address is C8 . // Pointer address is C8 . }
Closure semantics for foreach over arrays of pointer types
C_sharp : On www.dofactory.com I found a real world example of the Factory Pattern . But the code generates a warning in ReSharper about a virtual member call in the constructor.The code causing the warning is the following : In the consuming code , you can then simply use : I do understand why it 's a bad idea to call a virtual member in the constructor ( as explained here ) .My question is how you can refactor this in order to still use the factory pattern , but without the virtual member call in the constructor.If I 'd just remove the call to CreatePages from the constructor , the consumer would have to explicitly call the CreatePages method : I much more prefer the situation where creating a new Resume is all that 's needed to actually create a Resume containing pages . <code> abstract class Document { private List < Page > _pages = new List < Page > ( ) ; // Constructor calls abstract Factory method public Document ( ) { this.CreatePages ( ) ; // < = this line is causing the warning } public List < Page > Pages { get { return _pages ; } } // Factory Method public abstract void CreatePages ( ) ; } class Resume : Document { // Factory Method implementation public override void CreatePages ( ) { Pages.Add ( new SkillsPage ( ) ) ; Pages.Add ( new EducationPage ( ) ) ; Pages.Add ( new ExperiencePage ( ) ) ; } } Document document = new Resume ( ) ; Document document = new Resume ( ) ; document.CreatePages ( ) ;
How to prevent Factory Method pattern causing warning about virtual member call in constructor ?
C_sharp : I have a small app with several forms , each of which saves their pane layout during the FormClosing event.Some forms need to remain on screen when the main form is minimized , so they 're opened ownerless with form.Show ( ) , as opposed to form.Show ( this ) .However this affects FormClosing behaviour - when the user exits using the red X , the FormClosing event does n't get fired for the ownerless forms.Application.Exit ( ) does work as needed , but cancelling the FormClosing event in the main form and calling Application.Exit ( ) instead causes FormClosing to be called twice on everything other than the ownerless forms.I could probably iterate OpenForms in the FormClosing event of the main form and save anything that needs saving , but that seems a bit of a hack . Is there a way to make X behave in the same way as Application.Exit ( ) ? The following code demonstrates the problem : <code> public partial class Form1 : Form { public Form1 ( ) { InitializeComponent ( ) ; this.Text = `` Main '' ; Form ownedForm = new Form { Text = `` Owned '' } ; ownedForm.FormClosing += ( s , e ) = > { System.Diagnostics.Debug.WriteLine ( `` FormClosing owned form '' ) ; } ; ownedForm.Show ( this ) ; Form ownerlessForm = new Form { Text = `` Ownerless '' } ; ownerlessForm.FormClosing += ( s , e ) = > { System.Diagnostics.Debug.WriteLine ( `` FormClosing ownerless form '' ) ; } ; ownerlessForm.Show ( ) ; this.FormClosing += ( s , e ) = > { System.Diagnostics.Debug.WriteLine ( `` FormClosing main form '' ) ; // fix below does n't work as needed ! //if ( e.CloseReason == CloseReason.UserClosing ) // { // e.Cancel = true ; // Application.Exit ( ) ; // } } ; } }
How to fire FormClosing for ownerless forms on red X exit ?
C_sharp : I have the following method that I ca n't figure out correct syntax to call : I 'm trying to call it like this : Edited : thx everyone , you guys helped turned on a light bulb in my head . here is what i did : not sure why i even an issue with this . it 's one of those days i guess..thx <code> public T GetAndProcessDependants < C > ( Func < object > aquire , Action < IEnumerable < C > , Func < C , object > > dependencyAction ) { } var obj = MyClass.GetAndProcessDependants < int > ( ( ) = > DateTime.Now , ( ( ) = > someList , ( id ) = > { return DoSomething ( x ) ; } ) } var obj = MyClass.GetAndProcessDependants < int > ( ( ) = > DateTime.Now , ( list , f ) = > { list = someList ; f = id = > { return DoSomething ( id ) ; } ; } ) ;
C # Action < > with Func < > parameter
C_sharp : I have a winforms TabControl and I am trying to cycle through all the controls contained in each tab . Is there a way to add and in a foreach loop or is n't it possible to evaluate more than one group of items ? For example this is what I 'd like to do : ORIs this possible , and if not , what is the next best thing ? Do I need to use a for loop ? <code> foreach ( Control c in tb_Invoices.Controls and tb_Statements.Controls ) { //do something } foreach ( Control c in tb_Invoices.Controls , tb_Statements.Controls ) { //do something }
Can I evaluate two groups of items with a foreach loop in C # winforms ?
C_sharp : Let 's take the following code : This will compile , and all is good . However , let 's now remove the this . prefix : In this case , I get a compiler error . I agree this is an error , however it 's the location of the error that confuses me . The error happens on the line : With the message : A local variable named 'bar ' can not be declared in this scope because it would give a different meaning to 'bar ' , which is already used in a 'parent or current ' scope to denote something elseFrom what I understand about the compiler , the declaration of bar gets hoisted to the top of the Method ( ) method . However , if that 's the case , the line : Should be considered ambiguous , as bar could be a reference to the instance field or to the not-yet-declared local variable.To me , it seems odd that removing this . can cause a compilation error on another line . In other words , declaring a local bar variable is perfectly valid , as long as no potentially ambiguous references to bar have been made previously in the scope ( note , if I comment out if ( ! String.IsNullOrEmpty ( bar ) ) then the error goes away ) .That all seems rather pedantic , so what 's your question ? : My question is why the compiler allows an ambiguous reference to a variable before it 's declared in the scope , but then flags the declaration itself as redundant . Should n't the ambiguous reference to bar in String.IsNullOrEmpty ( ) be a more precise location of the error ? In my example , it 's of course easy to spot , but when I ran across this issue in the wild , the reference was pages up and much harder to track down . <code> class Foo { string bar ; public void Method ( ) { if ( ! String.IsNullOrEmpty ( this.bar ) ) { string bar = `` Hello '' ; Console.Write ( bar ) ; } } } class Foo { string bar ; public void Method ( ) { if ( ! String.IsNullOrEmpty ( bar ) ) // < -- Removed `` this . '' { string bar = `` Hello '' ; Console.Write ( bar ) ; } } } string bar = `` Hello '' ; if ( ! String.IsNullOrEmpty ( bar ) )
Weird C # compiler issue with variable name ambiguity
C_sharp : Right now , I am using the following code to create a Shuffle extension : I am looking for a way more faster and efficient way to do this . Right now , using the Stopwatch class , it is taking about 20 seconds to shuffle 100,000,000 items . Does anyone have any ideas to make this faster ? <code> public static class SiteItemExtensions { public static void Shuffle < T > ( this IList < T > list ) { var rng = new Random ( ) ; int n = list.Count ; while ( n > 1 ) { n -- ; int k = rng.Next ( n + 1 ) ; T value = list [ k ] ; list [ k ] = list [ n ] ; list [ n ] = value ; } } }
Improving `` shuffle '' efficiency
C_sharp : I create 2 methods that print x and y 100 times . I want them to run concurrent and I expect the output to be xxxxyxyxyyyxyyxyx ... sthg like that.It does n't print anything . Am I missing some logic here ? <code> using System ; using System.Threading.Tasks ; namespace ConsoleApplication32 { internal class Program { public static async Task < int > Print1 ( ) { await Task.Run ( ( ) = > { for ( int i = 0 ; i < 100 ; i++ ) { Console.Write ( `` x '' ) ; } } ) ; return 1 ; } public static async Task < int > Print2 ( ) { await Task.Run ( ( ) = > { for ( int i = 0 ; i < 100 ; i++ ) { Console.Write ( `` y '' ) ; } } ) ; return 1 ; } public static void Run ( ) { Task < int > i = Print1 ( ) ; Task < int > k = Print2 ( ) ; } private static void Main ( string [ ] args ) { Run ( ) ; } } }
Why nothing is printed on the console ?
C_sharp : I just found that not only does this code compile , it seems to split the string on any whitespace.However it did n't show in the intellisense and it 's not on the MSDN page . Is this just an undocumented override ? And is it dangerous to use because of that ? <code> List < string > TableNames = Tables.Split ( ) .ToList ( ) ;
Is this an undocumented override of the Split method ?
C_sharp : Is there any way in a C # iterator block to provide a block of code which will be run when the foreach ends ( either naturally of by being broken out of ) , say to clean up resources ? The best I have come up with is to use the using construct , which is fine but does need an IDisposable class to do the clean up . For example : <code> public static IEnumerable < string > ReadLines ( this Stream stream ) { using ( StreamReader rdr = new StreamReader ( stream ) ) { string txt = rdr.ReadLine ( ) ; while ( txt ! = null ) { yield return txt ; txt = rdr.ReadLine ( ) ; } rdr.Close ( ) ; } }
'Finally ' Block in Iterators
C_sharp : In Australia , A client has been entering `` 1/5 '' as a shortcut for the first day of May . We have just moved from Windows Server 2008 to Windows Server 2012.Using the following code in LinqPad : On Windows Server 2008 : dd MMMM1/05/2016 12:00:00 AMOn Windows Server 2012 R2 : MMMM d5/01/2016 12:00:00 AMQuestions : Why has the MonthDayPattern changed ? Australians always have day first , then monthWhere can this be set in the Windows Server UI ? The UI only exposes the long and short formats , not the month and day formatHow can I fix the issue in my application with the least amount of changes , given that there could be DateTime.Parse happening all through the system ( Eg . Model Binding , Validation etc ) <code> Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo ( `` en-au '' , false ) ; System.Globalization.DateTimeFormatInfo.CurrentInfo.MonthDayPattern.Dump ( ) ; DateTime.Parse ( `` 1/5 '' ) .Dump ( ) ;
DateTimeFormatInfo.MonthDayPattern Has Changed in Windows Server 2012 - How Can I set it back ?
C_sharp : Is there a way to find out all function calls that will execute as part of a Program in C # world ? For example , given this : Can I say through FxCop or some other system get to know CallTrueFunction ? <code> static void Main ( string [ ] args ) { if ( true ) { CallTrueFunction ( ) ; } else { CallFalseFunction ( ) ; } }
.NET Static Analysis -- Guaranteed calls to functions in a program
C_sharp : Why does the following code produce an error ? Error : Operator ' < ' can not be applied to operands of type 'method group ' and 'System.Type'The code looks silly , because it 's extremly simplified from my real example . I just wonder why it does not work exactly . It works if I replace x.getType ( ) with List < string > , but I do n't now the type of x at runtime.For clarification : I do n't necessary look for a solution . I want to know what exactly is wrong with my code . <code> var listOfList = new List < List < string > > ( ) ; var tmp = listOfList.Select ( x = > x.OrderBy ( y = > y ) .Cast < x.GetType ( ) > ( ) ) ;
Why does Select ( x = > ... Cast < x.GetType ( ) > ( ) ) not work ?
C_sharp : Consider the following function : This function returns whether it was able to `` do stuff '' on destination based on input 's content.I 'd like to check if the memory regions `` wrapped '' by input and destination intersect , and if so , throw an exception , since this would corrupt input 's data . How can I do that ( without reflection or unsafe code ) ? I know I could write some xmldoc and warn the users that the parameters should not intersect , but that 's a poor man 's solution.Edit : for those asking for examples , Wazner 's examples are on point . <code> public static bool TryToDoStuff ( ReadOnlySpan < byte > input , Span < byte > destination ) { ... } // On arraysSpan < byte > firstArray = new byte [ 10 ] ; Span < byte > secondArray = new byte [ 10 ] ; Intersects < byte > ( firstArray.Slice ( 5 , 5 ) , firstArray.Slice ( 3 , 5 ) ) ; // Should throwIntersects < byte > ( firstArray.Slice ( 5 , 5 ) , secondArray.Slice ( 3 , 5 ) ) ; // Should not throw// And on stackallocated memorySpan < byte > firstStack = stackalloc byte [ 10 ] ; Span < byte > secondStack = stackalloc byte [ 10 ] ; Intersects < byte > ( firstStack.Slice ( 5 , 5 ) , firstStack.Slice ( 3 , 5 ) ) ; // Should throwIntersects < byte > ( firstStack.Slice ( 5 , 5 ) , secondStack.Slice ( 3 , 5 ) ) ; // Should not throw
How can I check if two Span < T > intersect ?
C_sharp : the following code sets the clipboard text on OSX . What is the equivalent to read the clipboard text ? <code> static class OsxClipboard { public static void SetText ( string text ) { var nsString = objc_getClass ( `` NSString '' ) ; var str = objc_msgSend ( objc_msgSend ( nsString , sel_registerName ( `` alloc '' ) ) , sel_registerName ( `` initWithUTF8String : '' ) , text ) ; var dataType = objc_msgSend ( objc_msgSend ( nsString , sel_registerName ( `` alloc '' ) ) , sel_registerName ( `` initWithUTF8String : '' ) , NSPasteboardTypeString ) ; var nsPasteboard = objc_getClass ( `` NSPasteboard '' ) ; var generalPasteboard = objc_msgSend ( nsPasteboard , sel_registerName ( `` generalPasteboard '' ) ) ; objc_msgSend ( generalPasteboard , sel_registerName ( `` clearContents '' ) ) ; objc_msgSend ( generalPasteboard , sel_registerName ( `` setString : forType : '' ) , str , dataType ) ; objc_msgSend ( str , sel_registerName ( `` release '' ) ) ; objc_msgSend ( dataType , sel_registerName ( `` release '' ) ) ; } [ DllImport ( `` /System/Library/Frameworks/AppKit.framework/AppKit '' ) ] static extern IntPtr objc_getClass ( string className ) ; [ DllImport ( `` /System/Library/Frameworks/AppKit.framework/AppKit '' ) ] static extern IntPtr objc_msgSend ( IntPtr receiver , IntPtr selector ) ; [ DllImport ( `` /System/Library/Frameworks/AppKit.framework/AppKit '' ) ] static extern IntPtr objc_msgSend ( IntPtr receiver , IntPtr selector , string arg1 ) ; [ DllImport ( `` /System/Library/Frameworks/AppKit.framework/AppKit '' ) ] static extern IntPtr objc_msgSend ( IntPtr receiver , IntPtr selector , IntPtr arg1 , IntPtr arg2 ) ; [ DllImport ( `` /System/Library/Frameworks/AppKit.framework/AppKit '' ) ] static extern IntPtr sel_registerName ( string selectorName ) ; const string NSPasteboardTypeString = `` public.utf8-plain-text '' ; }
How to get the clipboard text on OSX using DllImport with c # ?
C_sharp : I have this function I 'm creating 2 Persons class instances : I 'm calling the function with : my Question is : Who actually decide about the T1 type ? ( p ? p2 ? ) Because if the left one is Apple so he checks that the second one is Also an appleand if the second one is Orange - he should check that the first one is also an Orange.It seems weird to ask it becuase at compile time they will fail if not the same.Still - who decide about the type ? And second - If i change it to dynamic - on runtime- who will decide what the T1 type should be ? <code> public static T2 MyFunc < T1 , T2 > ( T1 a , T1 b , T2 c ) { return c ; } class Person { } Person p = new Person ( ) ; Person p2 = new Person ( ) ; MyClass.MyFunc ( p , p2 , 5 ) ;
Who actually last decide what is the Generic Type ?
C_sharp : Background : I have a `` Messenger '' class . It sends messages . But due to limitations , let 's say it can only send - at most - 5 messages at a time.I have a WPF application which queues messages as needed , and waits for the queued message to be handled before continuing . Due to the asynchronous nature of the application , any number of messages could be awaited at any given time.Current Implementation : To accomplish this , I 've implemented a Task < Result > SendMessage ( Message message ) API within my messaging class . Internal to the messaging class is a custom TaskScheduler ( the LimitedConcurrencyTaskScheduler from MSDN ) , with its concurrency level set to 5 . In this way , I would expect that no matter how many messages are queued , only 5 will be sent out at a time , and my client application will patiently wait until its respective message has been handled.Problem : When I await the SendMessage method , I can see via the debugger that the message was completed and the result returned , but my code never executes beyond the awaited method call ! Is there some special considerations that need to be made , when awaiting a Task which was scheduled using a different TaskScheduler ? Snipped Code : From my client/consuming function : From my messenger class : Update : The 'freeze ' does not actually appear to be caused by my custom TaskScheduler ; when I queue up the Task with the default TaskFactory , the same behavior occurs ! There must be something else happening at a more fundamental level , likely due to my own stupidity . <code> public async Task Frobulate ( ) { Message myMessage = new Message ( x , y , z ) ; await messenger.SendMessage ( myMessage ) ; //Code down here never executes ! } private TaskScheduler _messengerTaskScheduler = new LimitedConcurrencyLevelTaskScheduler ( 5 ) ; private TaskFactory _messengerTaskFactory = new TaskFactory ( _messengerScheduler ) ; public Task < Result > SendMessage ( Message message ) { //My debugger has verified that `` InternalSendMessage '' has completed , //but the caller 's continuation appears to never execute return _messengerTaskFactory.StartNew ( ( ) = > InternalSendMessage ( message ) ) ; }
'await ' does not return , when my Task is started from a custom TaskScheduler
C_sharp : I am working on a role playing game for fun and to practice design patterns . I would like players to be able to transform themselves into different animals . For example , a Druid might be able to shape shift into a cheetah . Right now I 'm planning on using the decorator pattern to do this but my question is - how do I make it so that when a druid is in the cheetah form , they can only access skills for the cheetah ? In other words , they should not be able to access their normal Druid skills.Using the decorator pattern it appears that even in the cheetah form my druid will be able to access their normal druid skills.now using the classesHmmmm ... now that I think about it , will myDruid be unable to us the Druid class spells/skills unless the class is down-casted ? But even if that 's the case , is there a better way to ensure that myDruid at this point is locked out from all Druid related spells/skills until it is cast back to a Druid ( since currently it 's in CheetahForm ) <code> class Druid : Character { // many cool druid skills and spells void LightHeal ( Character target ) { } } abstract class CharacterDecorator : Character { Character DecoratedCharacter ; } class CheetahForm : CharacterDecorator { Character DecoratedCharacter ; public CheetahForm ( Character decoratedCharacter ) { DecoratedCharacter= decoratedCharacter ; } // many cool cheetah related skills void CheetahRun ( ) { // let player move very fast } } Druid myDruid = new Druid ( ) ; myDruid.LightHeal ( myDruid ) ; // casting light heal here is finemyDruid = new CheetahForm ( myDruid ) ; myDruid.LightHeal ( myDruid ) ; // casting here should not be allowed
Design considerations for temporarily transforming a player into an animal in a role playing game
C_sharp : I have data stored in an XML document that describes a linked list ; all nodes except one follow another , so the data looks something like this : ... to give an ordering of 30 , 29 , 34 , 9 , 20 , 12 . I 'm using .NET 's LinkedList class to construct a linked list to reflect this data , but it 's awkward to construct because the values are out of sequence . What I really want to do is assume that the data is valid - there is exactly one first value , and all others have `` follows '' values that follow one other node in the list . Code like this would be good ( FindFirstForwards is a custom extension method I wrote to find the first linked list entry for which the given lambda returns true ) : The trouble is , if the car that this one follows has not yet been added to orderedCars , an exception is thrown because FindFirstForwards did n't find a car with the `` follows '' ID . What I really want to do is say `` add this to the linked list , assume it will follow some future entry with a certain ID even though that entry has n't yet been added , and carry on . '' Then at the end , check the integrity of the linked list to make sure each node points to another , and that there is one head node.Is there a concise way of doing this ? If not , what would be the most efficient ( and preferably , code-concise ) way of converting this XML into an in-memory linked list ? <code> < cars > < car id= '' 9 '' follows= '' 34 '' / > < car id= '' 12 '' follows= '' 20 '' / > < car id= '' 20 '' follows= '' 9 '' / > < car id= '' 29 '' follows= '' 30 '' / > < car id= '' 30 '' / > < car id= '' 34 '' follows= '' 29 '' / > < /cars > LinkedList < CarInstance > orderedCars = new LinkedList < CarInstance > ( ) ; XPathNodeIterator xmlIterator = _nav.Select ( `` /dflt : cars/dflt : car '' , _namespaceResolver ) ; while ( xmlIterator.MoveNext ( ) ) { if ( ! ( xmlIterator.Current.Select ( `` @ follows '' ) .Count > 0 ) ) { orderedCars.AddFirst ( new CarInstance { CarId = int.Parse ( xmlIterator.Current.GetAttribute ( `` id '' , _defaultNamespace ) ) } ) ; } else { orderedCars.AddAfter ( orderedCars.FindFirstForwards ( car = > car.CarId == int.Parse ( xmlIterator.Current.GetAttribute ( `` follows '' , _defaultNamespace ) ) ) , new CarInstance { CarId = int.Parse ( xmlIterator.Current.GetAttribute ( `` id '' , _defaultNamespace ) ) } ) ; } }
Most efficient way to construct a linked list from stored data ?
C_sharp : It appears that , in .NET , `` array of enum '' is not a strongly-typed concept . MyEnum [ ] is considered to implement not just IEnumerable < MyEnum > , but also IEnumerable < YourEnum > . ( I did n't believe it at first either . ) So when I go looking through a list for everything that implements IEnumerable < T > , I 'm getting the T [ ] s and the List < T > s and the iterator-generated IEnumerable < T > s , but I 'm also getting the SomethingElse [ ] s that I do not want.What 's the easiest way to find out whether a given Type ( as with IsAssignableFrom above ) or a given instance ( as with OfType < T > above ) really and truly implements , say , IEnumerable < DayOfWeek > ? I gave Mr. Skeet the green checkmark , but once I got his code into Visual Studio , ReSharper suggested a more concise version . Use whichever version you prefer . <code> // Returns true : typeof ( IEnumerable < DayOfWeek > ) .IsAssignableFrom ( typeof ( AttributeTargets [ ] ) ) // Outputs `` 3 '' : var listOfLists = new List < object > { new [ ] { AttributeTargets.All } , new [ ] { ConsoleColor.Blue } , new [ ] { PlatformID.Xbox , PlatformID.MacOSX } } ; Console.WriteLine ( listOfLists.OfType < IEnumerable < DayOfWeek > > ( ) .Count ( ) ) ; public static IEnumerable < IEnumerable < T > > OfSequenceType < T > ( this IEnumerable source ) where T : struct { return from sequence in source.OfType < IEnumerable < T > > ( ) let type = sequence.GetType ( ) where ! type.IsArray || type.GetElementType ( ) == typeof ( T ) select sequence ; }
Every array of enum implements IEnumerable < EveryOtherEnum > . How do I work around this ?
C_sharp : Does this make sense ? Having a simple classand then instantiating itThe using statement is there just to make sure Test is disposed.When will it be disposed if I just call <code> class Test { public Test ( ) { // Do whatever } } using ( new Test ( ) ) { // Nothing in here } new Test ( )
Using `` using '' statement to dispose
C_sharp : I am new to programming . I am studying chapter 14 of John Sharp 's Microsoft Visual C # Step by Step 9ed.And I do not understand a number of points.The author writes : ... it ( finalizer ) can run anytime after the last reference to an object has disappeared . So it is possible that the finalizer might actually be invoked by the garbage collector on its own thread while the Dispose method is being run , especially if the Dispose method has to do a significant amount of work.1 ) Here I have a first question , how is this possible ? After all , GC CLR destroys the object as correctly noticed when there are no more links to it . But if there are no references , how then can simultaneously still work the method of an object ( Dispose ( ) ) to which nothing else refers ? Yes , there are no links , but the method is not completed and GC CLR will try to delete the method object that still works ? Further , the author proposes to use lock ( this ) to circumvent this problem ( parallel calls to Dispose ( ) ) and clarifies that this can be detrimental to performance by immediately suggesting another strategy described earlier in the chapter.2 ) I understand how it works and why it is needed , but I have problems with mentioning exactly the parallel execution of this.Dispose ( true ) and this.Dispose ( false ) . Which in the proposed last solution will not allow GC CLR to call the this.Dispose ( false ) method in its thread in parallel through the destructor in the same way as before while this.Dispose ( true ) will still be executed previously launched explicitly ? At first glance , this is a GC.SuppressFinalize ( this ) construct , but it should work only after the end of this.Dispose ( true ) , and by condition it is executed long enough for GC CLR in its thread to start the deconstructor and this.Dispose ( false ) .As I understand it , nothing prevents and we get only a repeat of discarding unmanaged resources ( files , connections to databases , and so on ) , but we don ’ t get a repeat of discarding managed resources ( for example , a large multidimensional array ) . It turns out that it is permissible to repeatedly drop unmanaged resources and it is unacceptable to repeatedly discard managed resources ? And this is better than using the lock ( this ) construct ? <code> class Example : IDisposable { private Resource scarce ; // scarce resource to manage and dispose private bool disposed = false ; // flag to indicate whether the resource // has already been disposed ... ~Example ( ) { this.Dispose ( false ) ; } public virtual void Dispose ( ) { this.Dispose ( true ) ; GC.SuppressFinalize ( this ) ; } protected virtual void Dispose ( bool disposing ) { if ( ! this.disposed ) { if ( disposing ) { // release large , managed resource here ... } // release unmanaged resources here ... this.disposed = true ; } } //other methods }
C # IDisposable , Dispose ( ) , lock ( this )
C_sharp : I 'm working on a sample PRISM application and I want to use the MEF RegistrationBuilder to create all of my exports . The equivalent of using the ExportAttribute is as follows : However , modules use a different attribute , the ModuleExportAttribute , for example : I 'm not sure how to use the RegistrationBuilder class to create the module export instead of using the ModuleExportAttribute . Is this even possible since it is exported differently than a standard export ? <code> [ Export ( typeof ( IFooService ) ) ] public class FooService : IFooService { ... } Builder.ForTypesMatching ( typeof ( IFooService ) .IsAssignableFrom ( type ) ) .Export < IFooService > ( ) ; [ ModuleExport ( typeof ( ModuleA ) , DependsOnModuleNames = new string [ ] { `` ModuleB '' } ) ] public sealed class ModuleA : IModule { ... }
Is it possible to use MEF RegistrationBuilder to create a PRISM ModuleExport ?
C_sharp : Is there any downside of calling GC.SuppressFinalize ( object ) multiple times ? Protected Dispose ( bool ) method of the dispose pattern checks whether it is called before but there is no such check in the public Dispose ( ) method.Is it ok to call the Dispose ( ) method of a MyClass instance multiple times ? <code> public void Dispose ( ) { Dispose ( true ) ; GC.SuppressFinalize ( this ) ; } protected virtual void Dispose ( bool disposing ) { if ( _Disposed ) return ; if ( disposing ) { // Cleanup managed resources . } // Cleanup unmanaged resources . _Disposed = true ; } ~MyClass ( ) { Dispose ( false ) ; }
Calling SuppressFinalize multiple times
C_sharp : Whenever I write a new class and add some internal fields , I use an underscore prefix like so : Why did the .NET team decide to create an AppDomain interface with the name _AppDomain ? It just bugs me to see it whenever I type an underscore to get my class level fields in intellisense . Why is n't it IAppDomain or something else ? Yes , I am very picky ... I know <code> private readonly int _foo ;
Why is _AppDomain prefixed with an underscore ? Seriously , it bugs me that it is always in my field intellisense
C_sharp : I have a DataTable which I want to check if values in three of the columns are unique . If not , the last column should be filled with the line number of the first appearance of the value-combination.For example , this table : Should lead to this result : I solved this by iterating the DataTable with two nested for loops and comparing the values . While this works fine for a small amount of data , it gets pretty slow when the DataTable contains a lot of rows.My question is : What is the best/fastest solution for this problem , regarding that the amount of data can vary between let 's say 100 and 20000 rows ? Is there a way to do this using LINQ ? ( I 'm not too familiar with it , but I want to learn ! ) <code> ID Name LastName Age Flag -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -1 Bart Simpson 10 -2 Lisa Simpson 8 -3 Bart Simpson 10 -4 Ned Flanders 40 -5 Bart Simpson 10 - Line Name LastName Age Flag -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -1 Bart Simpson 10 -2 Lisa Simpson 8 -3 Bart Simpson 10 14 Ned Flanders 40 -5 Bart Simpson 10 1
Mark non-unique rows in a DataTable
C_sharp : I 'm doing a class that gets a string of a JSON ( that represents an object ) and I 'm deserializing it using JSON.NET from Newtonsoft . As I do n't know exactly the object that I need to serialize what I 'm doing with the JSON.NET library is to get a Dictionary.The thing is that I 'm processing each property differently depending of its type . I can recognize without problems the date or intes by comparing the parsed object JToken.Type with for instance JTokenType.Date.However the type JTokenType.Bytes , seem to not be working . Then I have this problem , I have a string that represents a normal string an a string that represents a byte [ ] . How can I distinguish them ? Either by using the JTokenType class or other types ? Any idea ? Lot of thanksBest regardsI attach here an example of the JSON that I 'm parsing : The last property is a picture ( byte [ ] ) <code> { `` firstName '' : '' Mario '' , '' lastName '' : '' Bross '' , '' users '' : [ { `` name '' : '' Tony '' , '' country '' : '' UK '' , '' telephone '' : '' 663242342 '' } , { `` name '' : '' Ahmed '' , '' country '' : '' UAE '' , '' telephone '' : '' 66934534 '' } , { `` name '' : '' Alejandro '' , '' country '' : '' ES '' , '' telephone '' : '' 666243098 '' } ] , '' firstTable '' : true , '' secondTable '' : false , '' greeting '' : false , '' headerInfo '' : '' This is a test document '' , '' footerInfo '' : '' This page ends here '' , '' date '' : '' 2016-03-29T00:00:00+02:00 '' , '' remark '' : '' Here we have some remarks '' , '' logo '' : '' iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAABCP0lEQVR42u1dB3wU1fa+YIBAQu+9KkV6KGlAEkIntJAEFRURO6IgKioIKBYQRRAEqQIBYvfJ38JTsT0rz/aw8BSFJyJIUUQQC7j/+82cm9xMZnZnd2f7Pb/f+UXD7mZ3dr5zT/nOOYwpUaJEiRIlSpQoUaJEiRIlSpQoUaJEiRIlSpQoUaJEiRIlSpQoUaJEiRIlSpQoUaJEiRIlSpQoUaJEiRIlSpQoUaJEiRIlSpQoUaJEiRIlSpQoUaJEiRIlSpQoUaJEiRIlSpQoUaJEiRIlSpQoUaJEiRIlSpQoUaJEiRIlSpQoUaJEiRIlSpQosZZyPqgSJUqiBNzlfVBlJJQoiQCwy6A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MHLrMwjw6MIUzMzW5N43pJPeDPRxTNXxlShjoBmDagSSOhQTNyGD0IYA1YkSZsIo9CNPYRABcQQZhzwKI86nk/kiAu4EN3oRue0A93lkYNDrMJpeV3RbZlEiM5Vc+q50wrclwItTvh7lPqrbBL0CvpKYMwRmxqCSiUGoTYACsJpKRqEteQqdCIhJZBxEg1RfMhKZBFx3mkmneD+K11MpN9GTXrcr/Z0O5M4LsDehE14AvgYBPoGVnrykQK9EiU1jYGUQqhqMQl0KHRpR+NCMlfRHtCGgwki0Iw/CnbYjbUshCADekkDelF6/If29OhS21KD3k0gnfDy934qGmF6BXokSPw1CnMEoxEuGIZGMQ3UCZS0yEHXISNSTtL6Jyj0Vdem5tcjQ1JDc+ETpZDeCPc4N4BXolShxyCAYWZAVJMNgNA5Cq5AmWGgVSSsbAF6JlaZbx7GyDEwFeCVKQmAQjIbBzEAI78GOnmWi7kCuAK9ESRgbhkCoEiVKlChRokSJEiVKlChRokSJEiVKlChRokSJEiVKlChRokSJEiVKlChRokSJEiVKlChRokSJEiVKlChRokSJEiVKlChRokSJEiVKlChRokSJEiVKlChRokSJEiVKlChRokSJEiVKlChRokSJEgv5f5QbBX6f1PscAAAAAElFTkSuQmCC '' }
Distinguish byte [ ] and string from JSON .NET
C_sharp : I want to do something within the FooDataRepository class once the SaveFooAsync and the all the SaveBarAsync methods have completed . Is there a standard pattern for trying to do a single thing based upon N number of Async calls completing ? <code> public class FooDataRepository { private MyServiceReferenceClient Client { get ; set ; } public void FooClass ( ) { Client = new MyServiceReferenceClient ( ) ; Client.SaveFooCompleted += Client_SaveFooCompleted ; Client.SaveBarCompleted += Client_SaveBarCompleted ; } private void Client_SaveFooCompleted ( Object sender , EventArgs e ) { ... } private void Client_SaveBarCompleted ( Object sender , EventArgs e ) { ... } public void SaveFoo ( Foo foo ) { Client.SaveFooAsync ( foo ) ; foreach ( var bar in foo.Bars ) Client.SaveBarAsync ( bar ) ; } }
Is there a standard pattern to follow when waiting for N number of async methods to complete ?
C_sharp : I 'm trying to set up automated builds on my build agent using MSBuild on the command line . The two projects I 'm focussed on at the moment are a UWP and it 's associated unit test project.To build , I have to use this : Else , I get this error : However , this does not generate a .cer security certificate . So when I run vstest.console.exe , I get this error : Question : Can vstest.console.exe be made to run without a .cer , and if not , how can I get everything building and my tests running as well ? I do n't want devs to use temporary .pfx files . <code> /p : AppxPackageSigningEnabled=false error APPX0101 : A signing key is required in order to package this project . Please specify a PackageCertificateKeyFile or PackageCertificateThumbprint value in the project file . error 0x800B0100 : The app package must be digitally signed for signature validation..
Can vstest.console.exe run an appx without a security certificate
C_sharp : I am trying to serialize a list of descendants . This is what I have now , that works fine : This works fine and I can serialize both Animals . I wonder If it is possible to create an Attribute class where I can pass the list of animals ( instances ) , and will create for me the XmlArrayItems attributes.In general , I am looking for a way to avoid specifying the descendants of Animal everytime I create a new one . I want all descendants of Animal to be serialized , whatever their type . <code> class Animal { } class Zebra : Animal { } class Hippo : Animal { } [ XmlRootAttribute ( `` Zoo '' ) ] class Zoo { [ XmlArrayItem ( typeof ( Zebra ) ) ] [ XmlArrayItem ( typeof ( Hippo ) ) ] public List < Animal > Actions { set ; get ; } }
Xml Serialize List of Descendants
C_sharp : I have some lines of code in c # that Resharper indents like this : Due to my personal coding style , I would like the above to appear with the closing parenthesis ( or brace ) without any indentation , like so : I tried playing with the various options on Resharper , but could n't find any . Is there a way I can make this work ? <code> Console.WriteLine ( `` Hello '' ) ; this.MySuperFunction ( argument1 , argument2 , argument3 ) ; Console.WriteLine ( `` World '' ) ; Console.WriteLine ( `` Hello '' ) ; this.MySuperFunction ( argument1 , argument2 , argument3 ) ; Console.WriteLine ( `` World '' ) ;
Resharper closing parenthesis indentation on function with multiple arguments
C_sharp : To return a double , do I have to cast to double even if types are double ? e.g.Do I have to cast ( double ) ? <code> double a = 32.34 ; double b = 234.24 ; double result = a - b + 1/12 + 3/12 ;
To return a double , do I have to cast to double even if types are double in c # ?
C_sharp : I use VS2015 , C # .I have a problem with Google login . From my debug configuration ( localhost ) everything works fine . After publishing to the server , google login window simply does n't get opened . And no exception is thrown.Here is my code : Of course I added server 's address to the origin uri and also to the authorised redirect uri on the google console for developers . ( just like I did for the localhost ) . I just do n't get it what is wrong , why login windows does n't get opened ? EDIT : Adding class dsAuthorizationBroker ( was missing from my first post - sorry on that one ) : <code> [ AllowAnonymous ] public async Task LoginWithGoogle ( ) { HttpRequest request = System.Web.HttpContext.Current.Request ; string redirectUri = ConfigurationReaderHelper.GetGoogleRedirectUri ( ) ; try { ClientSecrets secrets = new ClientSecrets { ClientId = `` *** '' , ClientSecret = `` *** '' } ; IEnumerable < string > scopes = new [ ] { PlusService.Scope.UserinfoEmail , PlusService.Scope.UserinfoProfile } ; GoogleStorageCredentials storage = new GoogleStorageCredentials ( ) ; dsAuthorizationBroker.RedirectUri = redirectUri ; UserCredential credential = await dsAuthorizationBroker.AuthorizeAsync ( secrets , scopes , `` '' , CancellationToken.None , storage ) ; } catch ( Exception ex ) { throw ex ; } } //just getting value from applicationSettings - web.config public static string GetGoogleRedirectUri ( ) { # if DEBUG return GetValueFromApplicationSettings ( `` RedirectUriDEBUG '' ) ; # elif PRODUKCIJA return GetValueFromApplicationSettings ( `` RedirectUriSERVER '' ) ; # endif } namespace Notes { public class dsAuthorizationBroker : GoogleWebAuthorizationBroker { public static string RedirectUri ; public static async Task < UserCredential > AuthorizeAsync ( ClientSecrets clientSecrets , IEnumerable < string > scopes , string user , CancellationToken taskCancellationToken , IDataStore dataStore = null ) { var initializer = new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = clientSecrets , } ; return await AuthorizeAsyncCore ( initializer , scopes , user , taskCancellationToken , dataStore ) .ConfigureAwait ( false ) ; } private static async Task < UserCredential > AuthorizeAsyncCore ( GoogleAuthorizationCodeFlow.Initializer initializer , IEnumerable < string > scopes , string user , CancellationToken taskCancellationToken , IDataStore dataStore ) { initializer.Scopes = scopes ; initializer.DataStore = dataStore ? ? new FileDataStore ( Folder ) ; var flow = new dsAuthorizationCodeFlow ( initializer ) ; return await new AuthorizationCodeInstalledApp ( flow , new LocalServerCodeReceiver ( ) ) .AuthorizeAsync ( user , taskCancellationToken ) .ConfigureAwait ( false ) ; } } public class dsAuthorizationCodeFlow : GoogleAuthorizationCodeFlow { public dsAuthorizationCodeFlow ( Initializer initializer ) : base ( initializer ) { } public override AuthorizationCodeRequestUrl CreateAuthorizationCodeRequest ( string redirectUri ) { return base.CreateAuthorizationCodeRequest ( dsAuthorizationBroker.RedirectUri ) ; } } }
Google login not working after publish
C_sharp : I made a simple async method to call an SQL stored procedure asynchronously.In my console program , I am calling this method 1000 times in a loop , and sleep for 1ms ( Thread.Sleep ) between each call.I start a StopWatch before entering the loop , and stop it when exiting the loop , and display the time spent in the loop.On my development machine ( Win7 - VS 2012 RC ) , I can see what I was expecting to see : This seems logical , considering that the call to the async method returns almost immediately ( when reaching the first await keyword ) , so there is just a small overhead ( 6ms ) incured while executing the code before the await.However when I run the exact same code on a server machine ( Win2008 R2 SP1 ) on which I have installed .NET Framework 4.5 RC the code is running fine however the execution time is far from the one I am expecting , in no comparison with the one obtained when running the program on my development machine : Meaning that somehow the async method being called is not really called asynchronously and the first await seems to somehow block ? Here is the code of the async method I am calling : And here is the main program testing code ( loop ) : I am running the exact same executable ( console program compiled in Release ) on both machines.I am tyring to figure out why the method is not truly called asynchronously when running the program on the server machine.Any idea ? Thanks ! EDITThe problem has nothing to do with async/await which is working just fine , but is due to the timer resolution ( used by StopWatch ) on the server being 15 time less than on my workstation . The code is not running slower at all , it 's just the resolution of the timer which is leading to incorect elapsed time computation.See answer from James Manning below . <code> Completed in 1006 ms Completed in 15520 ms public async void CallSpAsync ( ) { var cmd = new SqlCommand ( `` sp_mysp '' ) ; { var conn = new SqlConnection ( connectionString ) ; { cmd.Connection = conn ; cmd.CommandType = CommandType.StoredProcedure ; [ ... Filling command parameters here - nothing interesting ... ] await cmd.Connection.OpenAsync ( ) ; await cmd.ExecuteNonQueryAsync ( ) ; cmd.Dispose ( ) ; cmd.Connection.Dispose ( ) ; } } } Stopwatch sw = new Stopwatch ( ) ; sw.Start ( ) ; for ( int i = 0 ; i < 1000 ; i++ ) { CallSpAsync ( ) ; Thread.Sleep ( 1 ) ; } sw.Stop ( ) ;
async method not blocking on desktop but blocking on server ?
C_sharp : I have an string ; It must return ipad because ipad is in the first match ipad at the string.In other case Same string array first match to iPhone . <code> String uA = `` Mozilla/5.0 ( iPad ; CPU OS 8_2 like Mac OS X ) AppleWebKit/600.1.4 ( KHTML , like Gecko ) Mobile/12D508 Twitter for iPhone '' ; String [ ] a= { `` iphone '' , '' ipad '' , '' ipod '' } ; String uA = `` Mozilla/5.0 ( iPhone/iPad ; CPU OS 8_2 like Mac OS X ) AppleWebKit/600.1.4 ( KHTML , like Gecko ) Mobile/12D508 '' ;
How to compare string to String Array in C # ?
C_sharp : I have the following code : Visual Studio highlights this code , saying 'Possible NullReferenceException'by the way , without await Visual Studio does n't show this warningWhy NullReferenceException is possible here ? <code> await _user ? .DisposeAsync ( ) ;
await with null propagation System.NullReferenceException
C_sharp : Using DataTable.Compute , and have built some cases to test : I have changed my code to handle both . But curious to know what 's going on here ? <code> dt.Compute ( `` 0/0 '' , null ) ; //returns NaN when converted to doubledt.Compute ( `` 0/0.00 '' , null ) ; //results in DivideByZero exception
Why 0/0 is NaN but 0/0.00 is n't
C_sharp : Recently I have been researching some conventions in writing functions that return a collection . I was wondering whether the function that actually uses a List < int > should return a List < int > or rather IList < int > , ICollection < int > or IEnumerable < int > . I created some tests for performance and I was quite surprised with the results.Output : I 've tried different order of the measures or making the MakeList ( ) return one of the above interfaces but all of it only confirms that returning a List < int > and processing it as a List < int > is about twice as fast as with the interfaces.However various sources , including this answer claim that you should never return List < > and always use an interface.So my question is : Why is processing a List < int > about twice as fast as the interfaces ? What should we return from a function and how to manage the code if we care about performance ? <code> static List < int > list = MakeList ( ) ; static IList < int > iList = MakeList ( ) ; static ICollection < int > iCollection = MakeList ( ) ; static IEnumerable < int > iEnumerable = MakeList ( ) ; public static TimeSpan Measure ( Action f ) { var stopWatch = new Stopwatch ( ) ; stopWatch.Start ( ) ; f ( ) ; stopWatch.Stop ( ) ; return stopWatch.Elapsed ; } public static List < int > MakeList ( ) { var list = new List < int > ( ) ; for ( int i = 0 ; i < 100 ; ++i ) { list.Add ( i ) ; } return list ; } public static void Main ( ) { var time1 = Measure ( ( ) = > { // Measure time of enumerating List < int > for ( int i = 1000000 ; i > 0 ; i -- ) { foreach ( var item in list ) { var x = item ; } } } ) ; Console.WriteLine ( $ '' List < int > time : { time1 } '' ) ; var time2 = Measure ( ( ) = > { // IList < int > for ( int i = 1000000 ; i > 0 ; i -- ) { foreach ( var item in iList ) { var x = item ; } } } ) ; Console.WriteLine ( $ '' IList < int > time : { time2 } '' ) ; var time3 = Measure ( ( ) = > { // ICollection < int > for ( int i = 1000000 ; i > 0 ; i -- ) { foreach ( var item in iCollection ) { var x = item ; } } } ) ; Console.WriteLine ( $ '' ICollection < int > time : { time3 } '' ) ; var time4 = Measure ( ( ) = > { // IEnumerable < int > for ( int i = 1000000 ; i > 0 ; i -- ) { foreach ( var item in iEnumerable ) { var x = item ; } } } ) ; Console.WriteLine ( $ '' IEnumerable < int > time : { time4 } '' ) ; } List < int > time : 00:00:00.7976577IList < int > time : 00:00:01.5599382ICollection < int > time : 00:00:01.7323919IEnumerable < int > time : 00:00:01.6075277
Enumerating List faster than IList , ICollection and IEnumerable
C_sharp : I have a method called OutputToScreen ( object o ) and it is defined as : In my main calling method , if I do something like : But if I do , I am still not sure why x is not boxed in the second approach , I just saw it on a free video from quickcert . Can someone give good explanation ? Here is an additional question based on comments : If I pass in x.ToString ( ) which is similar to doing : string temp = x.ToString ( ) ; and then passing in temp , does n't boxing still occur when I box x to a string type <code> public void OutputToScreen ( object o ) { Console.WriteLine ( o.ToString ( ) ) ; } int x = 42 ; OutputToScreen ( x ) ; // x will be boxed into an object OutputToScreen ( x.ToString ( ) ) ; // x is not boxed
How passing in x.ToString ( ) into a method which is expecting an object type as opposed to just x prevent boxing ?
C_sharp : Qt has a neat functionality to do timed action with Lambda.An action can be done after a delay with a single line of code : Although I have n't found equivalent in C # .The closest I got was But it 's far from ( visually ) clean . Is there a better way to achieve this ? The use case is sending data on a serial line to some hardware , upon a button click or action , it is often required to send a command , and a packet a few ms later.Solution with a helper function : Called by <code> QTimer : :singleShot ( 10 , [ = ] ( ) { // do some stuff } ) ; Timer timer = new Timer ( ) ; timer.Interval = 10 ; timer.Elapsed += ( tsender , args ) = > { // do some stuff timer.Stop ( ) ; } ; timer.Start ( ) ; public void DelayTask ( int timeMs , Action lambda ) { System.Timers.Timer timer = new System.Timers.Timer ( ) ; timer.Interval = timeMs ; timer.Elapsed += ( tsender , args ) = > { lambda.Invoke ( ) ; } ; timer.AutoReset = false ; timer.Start ( ) ; } DelayTask ( 10 , ( ) = > /* doSomeStuff ... */ ) ;
How to delay a C # Action like QTimer : :singleShot ?
C_sharp : In .NET generic interface ICollection < T > has Count property itself . But it does not inherit any non-generic interface with a Count property . So , now if you want determine count of non-generic IEnumerable , you have to check whether it is implementing ICollection and if not , you have to use reflection to lookup whether it does implement generic ICollection < X > , since you do not know the generic argument X.If ICollection < T > can not inherit from directly from ICollection , why there is not another non-generic interface with Count property only ? Is it just bad design choice ? UPDATE : To make the question more clear , I demonstrate the issue on my current implementation : <code> static int ? FastCountOrZero ( this IEnumerable items ) { if ( items == null ) return 0 ; var collection = items as ICollection ; if ( collection ! = null ) return collection.Count ; var source = items as IQueryable ; if ( source ! = null ) return QueryableEx.Count ( source ) ; // TODO process generic ICollection < > - I think it is not possible without using reflection return items.Cast < object > ( ) .Count ( ) ; }
Why generic ICollection < T > does not inherit some non-generic interface with Count property ?
C_sharp : Copy and paste the following into a new console application in VS. Add references to System.Web and System.Web.Services ( I know console apps do n't need these assemblies , I 'm just showing you a snippet of code that does not work in my web application ) .Although both conditions in the if statement are false , it 's turning out to be true . Anyone know the reason why ? ( Visual Studio 2008 9.0.30729.1 ) .NET 3.5 SP1 <code> using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Web.Services ; using System.Web ; namespace ConsoleApplication8 { class Program { static void Main ( string [ ] args ) { string x = `` qweqweqw '' ; string y = `` { \ '' textMedia\ '' : [ -1 , -1 , -1 , -1 , -1 ] , \ '' textOperand\ '' : [ 1,1,1,1,1 ] , \ '' textString\ '' : [ \ '' \ '' , \ '' \ '' , \ '' \ '' , \ '' \ '' , \ '' \ '' ] , \ '' dateSite\ '' : [ -11 ] , \ '' dateOperand\ '' : [ ] , \ '' dateString\ '' : [ ] , \ '' status\ '' : [ -11,0,0 ] , \ '' media\ '' : [ -11,0,0 ] , \ '' subItem\ '' : true , \ '' context\ '' : false , \ '' branchSearch\ '' : false , \ '' profileIDs\ '' : [ 2,5,18 ] , \ '' profileViewIDs\ '' : [ 48,58,38 ] , \ '' currentSelectedBranch\ '' :0 } '' ; SaveSearch ( x , y ) ; } [ WebMethod ] public static object SaveSearch ( string name , string encodedSearch ) { object response = new { } ; string x = name ; string y = encodedSearch ; // Why does this if statement throw an exception if both equal false ? if ( x.Trim ( ) .Equals ( string.Empty ) || y.Trim ( ) .Equals ( string.Empty ) ) throw new AjaxErrorException ( `` Save Search '' , `` Something went wrong '' , `` JSFunction '' ) ; try { { return new { error = false , name = name , userID = 123 , date = DateTime.Now } ; } } catch ( Exception ex ) { String e ; if ( HttpContext.Current.IsDebuggingEnabled ) e = ex.Message + `` \n\n '' + ex.StackTrace ; else e = `` error error aliens approaching '' ; throw new AjaxErrorException ( `` Save Search '' , e , `` '' ) ; } return response ; } public class AjaxErrorException : System.Exception { public AjaxErrorException ( string title , string details , string function ) : base ( title ) { } string _stackTrace ; public override string StackTrace { get { return _stackTrace ; } } } } }
.net : debugger highlighting line of code not actually being executed
C_sharp : I find myself constantly wanting to pass a Func with a return and no inputs in place of an Action , for examplewhere , I do n't really care about the return value of DoSomething.These types do n't unify , however , and I end up wrapping the callIs there a way to make these types unify without wrapping ? Also , are there good design reasons why they do n't unify ? <code> Func < int > DoSomething = ... ; Task.Run ( DoSomething ) ; Task.Run ( ( ) = > { DoSomething ( ) ; } ) ;
Why do n't Func < ... > and Action unify ?
C_sharp : I 'm looking for suggestions on how to write a query . For each Goal , I want to select the first Task ( sorted by Task.Sequence ) , in addition to any tasks with ShowAlways == true . ( My actual query is more complex , but this query demonstrates the limitations I 'm running into . ) I tried something like this : But this query appears to be too complex.The problem is the line let nextTaskId = ... . If I comment out that , there is no error . ( But I do n't get what I 'm after . ) I 'll readily admit that I do n't understand the details of the error message . About the only other way I can think of to approach this is return all the Tasks and then sort and filter them on the client . But my preference is not to retrieve data I do n't need.Can anyone see any other ways to approach this query ? Note : I 'm using the very latest version of Visual Studio and .NET.UPDATE : I tried a different , but less efficient approach to this query.But this also produced an error : <code> var tasks = ( from a in DbContext.Areas from g in a.Goals from t in g.Tasks let nextTaskId = g.Tasks.OrderBy ( tt = > tt.Sequence ) .Select ( tt = > tt.Id ) .DefaultIfEmpty ( -1 ) .FirstOrDefault ( ) where t.ShowAlways || t.Id == nextTaskId select new CalendarTask { // Member assignment } ) .ToList ( ) ; System.InvalidOperationException : 'Processing of the LINQ expression 'OrderBy < Task , int > ( source : MaterializeCollectionNavigation ( Navigation : Goal.Tasks ( < Tasks > k__BackingField , DbSet < Task > ) Collection ToDependent Task Inverse : Goal , Where < Task > ( source : NavigationExpansionExpression Source : Where < Task > ( source : DbSet < Task > , predicate : ( t0 ) = > Property < Nullable < int > > ( ( Unhandled parameter : ti0 ) .Outer.Inner , `` Id '' ) == Property < Nullable < int > > ( t0 , `` GoalId '' ) ) PendingSelector : ( t0 ) = > NavigationTreeExpression Value : EntityReferenceTask Expression : t0 , predicate : ( i ) = > Property < Nullable < int > > ( NavigationTreeExpression Value : EntityReferenceGoal Expression : ( Unhandled parameter : ti0 ) .Outer.Inner , `` Id '' ) == Property < Nullable < int > > ( i , `` GoalId '' ) ) ) , keySelector : ( tt ) = > tt.Sequence ) ' by 'NavigationExpandingExpressionVisitor ' failed . This may indicate either a bug or a limitation in EF Core . See https : //go.microsoft.com/fwlink/ ? linkid=2101433 for more detailed information . ' var tasks = ( DbContext.Areas .Where ( a = > a.UserId == UserManager.GetUserId ( User ) & & ! a.OnHold ) .SelectMany ( a = > a.Goals ) .Where ( g = > ! g.OnHold ) .Select ( g = > g.Tasks.Where ( tt = > ! tt.OnHold & & ! tt.Completed ) .OrderBy ( tt = > tt.Sequence ) .FirstOrDefault ( ) ) ) .Union ( DbContext.Areas .Where ( a = > a.UserId == UserManager.GetUserId ( User ) & & ! a.OnHold ) .SelectMany ( a = > a.Goals ) .Where ( g = > ! g.OnHold ) .Select ( g = > g.Tasks.Where ( tt = > ! tt.OnHold & & ! tt.Completed & & ( tt.DueDate.HasValue || tt.AlwaysShow ) ) .OrderBy ( tt = > tt.Sequence ) .FirstOrDefault ( ) ) ) .Distinct ( ) .Select ( t = > new CalendarTask { Id = t.Id , Title = t.Title , Goal = t.Goal.Title , CssClass = t.Goal.Area.CssClass , DueDate = t.DueDate , Completed = t.Completed } ) ; System.InvalidOperationException : 'Processing of the LINQ expression 'Where < Task > ( source : MaterializeCollectionNavigation ( Navigation : Goal.Tasks ( < Tasks > k__BackingField , DbSet < Task > ) Collection ToDependent Task Inverse : Goal , Where < Task > ( source : NavigationExpansionExpression Source : Where < Task > ( source : DbSet < Task > , predicate : ( t ) = > Property < Nullable < int > > ( ( Unhandled parameter : ti ) .Inner , `` Id '' ) == Property < Nullable < int > > ( t , `` GoalId '' ) ) PendingSelector : ( t ) = > NavigationTreeExpression Value : EntityReferenceTask Expression : t , predicate : ( i ) = > Property < Nullable < int > > ( NavigationTreeExpression Value : EntityReferenceGoal Expression : ( Unhandled parameter : ti ) .Inner , `` Id '' ) == Property < Nullable < int > > ( i , `` GoalId '' ) ) ) , predicate : ( tt ) = > ! ( tt.OnHold ) & & ! ( tt.Completed ) ) ' by 'NavigationExpandingExpressionVisitor ' failed . This may indicate either a bug or a limitation in EF Core . See https : //go.microsoft.com/fwlink/ ? linkid=2101433 for more detailed information . '
Problem with LINQ query : Select first task from each goal
C_sharp : I found one unpleasant behavior developing with Visual Studio . It was hanging my machine while compiling C # .I have reduced behavior to the next minimal source codeCompiling with ( using Windows 8.1 Pro N x64 ; csc compiler process is running with 32bits ) sightly modifications do n't produce this behavior ( eg . changing decimal by int , reducing one nested level , ... ) , performing a big Select then reducing , works fineExplicit workaround : Although this explicit workaround exists , it not guaranteed that this behavior will not occur again.What 's wrong ? Thank you ! <code> using System.Collections.Generic ; using System.Linq ; namespace memoryOverflowCsharpCompiler { class SomeType { public decimal x ; } class TypeWrapper : Dictionary < int , Dictionary < int , Dictionary < int , SomeType [ ] [ ] > > > { public decimal minimumX ( ) { return base.Values.Min ( a = > a.Values.Min ( b = > b.Values.Min ( c = > c .Sum ( d = > d .Sum ( e = > e.x ) ) ) ) ) ; } } } PROMPT > csc source.cs *** BANG ! overflow memory usage ( up to ~3G ) PROMPT > csc / ? Microsoft ( R ) Visual C # Compiler version 12.0.30501.0Copyright ( C ) Microsoft Corporation . All rights reserved ... . return base.Values.SelectMany ( a = > a.Values.SelectMany ( b = > b.Values.Select ( c = > c. Sum ( d = > d. Sum ( e = > e.x ) ) ) ) ) .Min ( ) ;
C # compiler ( csc.exe ) memory overflow compiling nested types and Linq