text
stringlengths
46
37.3k
title
stringlengths
12
162
C_sharp : When I start writing a method , I usually check for exceptional conditions first in the method , using If-Then-Throw blocks.This style seems to be very clear and easy to understand , but it takes up more space than I think is necessary . I want to be able to handle errors and exceptional conditions in a smart way that enables whoever 's reading these errors to easy take care of them while also keeping the code itself clean.I 've looked a bit at Code Contracts , which seems to me a requirement for certain conditions before and after a method 's execution . That seems to be a tad bit overkill for just a null string , and I 'm not sure if you can have contract clauses within the method itself , for instance , if the path is not null but no file exists at that path.The solution I 'm thinking of using is rolling my own Assert class . This class will basically turn the above If-Then-Throw into a simple one liner.All Assert methods would throw an exception using the exception type and the message in the last argument . The thing is that I 'm not sure if this is good practice . Does it confuse what exceptions are truly for , or what Assert actually means ? Would it make error-handling easier or harder ? <code> public void ReadFile ( string filePath ) { if ( string.IsNullOrEmpty ( filePath ) { throw new ArgumentException ( ... Assert.IsFalse < ArgumentException > ( string.IsNullOrEmpty ( filePath ) , `` The path can not be null or empty . `` ) ;
Handling the usual errors : If-Then-Throw blocks vs. Code Contracts vs. an Assert class
C_sharp : I have some problems understanding a way to get the correct result from my LINQ query.Let me first define the entity ProductFavoriteI have an IEnumerable of some favorites products , named allFavorites , containing objects made in the way I wrote before.This `` list '' can contain elements with duplicates ProductUid , because it is build from different data sources.And again : the items in the `` list '' have at least IsFavorite = true OR IsLastUsed = true.I want to create , using LINQ of course , a resulting list of ProductFavorite objects , but grouping the items by ProductUid , and also grouping the three properties as follows : IsFavorite will be true only if one of the grouped items has this property set to trueIsLastUsed will be true only if one of the grouped items has this property set to trueLastUsedYear will be the maximum value of LastUsedYear of the grouped itemsI 've tried the next syntax , but I 'm not sure it can give me what I want : <code> public class ProductFavorite { public Guid Uid { get ; set ; } public Guid ProductUid { get ; set ; } public bool IsFavorite { get ; set ; } public bool IsLastUsed { get ; set ; } public int LastUsedYear { get ; set ; } } var favorites = from ProductFavorite pf in allFavorites group pf by pf.ProductUid into distinctFavorites select new ProductFavorite ( ) { Uid = Guid.NewGuid ( ) , ProductUid = distinctFavorites.Key , LastYearUsed = distinctFavorites.Max ( l = > l.LastYearUsed ) // ? ? ? , IsFavorite = ... , // ? ? ? IsLastUsed = ... // ? ? ? } ;
LINQ grouping and aggregating data with conditions
C_sharp : Let A be a class whith some property Hello . I would like to filter collections of A instances by this property in many places . Thus I 'd make somewhere a static member of type Expression < Func < A , bool > > which denotes the filtering predicate and I use it in all places where I do a filtering . ( This predicate would be transformed by an ORM to some concrete DB-specific expression. ) Next . There exists a class B with property of type A. I would like to filter collection of B instances by the same logic as was used in the first case ( by property Hello of class A ) .Question . What is the most correct way to implement this and reduce code duplication ? My suggestion . Add three things : 1 ) interface IWithA with property of type A , 2 ) class WithA < T > implementing this interface IWithA and providing property of type T , 3 ) some static property of type Expression < Func < IWithA , bool > > implementing the filtering logic . Demo code is following.The problem with this approach : 1 ) one must always make Select ( x = > new WithA < X > { ... } ) , 2 ) the ORM may not support this.About the answer . I am satisfied with the accepted answer ( by Ivan Stoev ) . I think it is the best possible approach . Also it is helpful to look at the suggestion from Mihail Stancescu ( see it in comments to the question ) . Still I do not understand the answer from user853710 ; may be it is useful also . <code> public static void Main ( ) { var listOfAs = new List < A > ( ) .AsQueryable ( ) ; var query0 = listOfAs .Select ( a = > new WithA < A > { A = a , Smth = a , } ) .Where ( Filter ) ; var listOfBs = new List < B > ( ) .AsQueryable ( ) ; var query1 = listOfBs .Select ( b = > new WithA < B > { A = b.A , Smth = b , } ) .Where ( Filter ) ; } private class A { public int Hello { get ; set ; } } private class B { public A A { get ; set ; } } private interface IWithA { A A { get ; set ; } } private class WithA < T > : IWithA { public A A { get ; set ; } public T Smth { get ; set ; } } private static readonly Expression < Func < IWithA , bool > > Filter = a = > a.A.Hello > 0 ;
How should I share filtering logic between multiple LINQ-where clauses ?
C_sharp : First of all , sorry for the title , but I could n't think about anything better ... My problem can be presented by simple code sample : Why does Console.WriteLine ( Test < byte > .GetInt ( 20 ) ) ; prints 10 , instead of 30 ? I always thought that generics in .NET are resolved by JIT during runtime . Why then jitter is n't smart enough , to find out that there is ToInt32 ( byte ) method , which suits our byte parameter type here ? This behavior makes Convert static class methods call result in boxing/unboxing operations for simple types . <code> public static class Test < T > { public static int GetInt ( T source ) { return Convert.ToInt32 ( source ) ; } } public static class Convert { public static int ToInt32 ( byte source ) { return 30 ; } public static int ToInt32 ( object source ) { return 10 ; } }
Generics and calling overloaded method from difference class - precedence issue
C_sharp : I 'm using ReSharpers [ NotNull ] annotations like this : However , due to the NotNull annotation , ReSharper warns me about the unused precondition check , because the expression is always falseBut , as far as I understand those annotations , they only indicate that the parameter should never be null ; i.e . they do not prohibit callers from passing null , e.g . as inor even less obvious ( more like in real code ) Therefore I feel like it does make sense to include precondition checks for null , but maybe I 'm missing out on a concept or do n't understand it correctly.Does it make sense to include explicit nullability checks for with [ NotNull ] annotated parameters ? <code> public void MyMethod ( [ NotNull ] string a ) { if ( a == null ) // Warning : Expression is always false . { throw new ArgumentNullException ( ) ; } // ... } this.MyMethod ( null ) ; string foo = null ; this.MyMethod ( foo ) ;
Should I add explicit null checks despite ReSharper [ NotNull ] annotations ?
C_sharp : i was looking for trick to get the form name when mouse is place on it . suppose i have one mdi form and many sdi form like form1 , form2 , form3 and all sdi form are opened . suppose i have one timer running on form1 and which will run periodically . i want to show the form name on form1 's label from the timer tick event when mouse is positioned on any SDI form window.this way i try to do it . here is the codethe above code run perfectly but there is some glitch . when i place my mouse on MDI form or on Form1 then form name is showing on form1 but when i place the mouse on Form2 or Form2 then their name is not showing . i am not being able to understand what is the problem in this code . please guide me to fix it . <code> private void timer1_Tick ( object sender , EventArgs e ) { var handle = WindowFromPoint ( Cursor.Position ) ; if ( handle ! = IntPtr.Zero ) { var ctl = Control.FromHandle ( handle ) ; if ( ctl ! = null ) { label1.Text = ctl.Name ; return ; } } label1.Text = `` None '' ; } [ System.Runtime.InteropServices.DllImport ( `` user32.dll '' ) ] private static extern IntPtr WindowFromPoint ( Point pos ) ;
How to detect the form name when mouse is position on any SDI form
C_sharp : I have a c # console application which has some threads to do some work ( download a file ) .each thread may exit the application at any time any where in application , but I 'll show a proper message on console . It 's possible to track them but it does n't make sense to me . I want simply check thread count or something like that to find out which one is the last thread and do something when it is exiting.What 's the best practice to do so ? pseudo code : Thanks <code> if ( lastThread ) { cleanUp ( ) ; Console.ReadLine ( ) ; }
Last thread of a multithreaded application
C_sharp : It was my assumption that the finally block always gets executed as long as the program is running . However , in this console app , the finally block does not seem to get executed.OutputNote : When the exception was thrown , windows askmed me if I wanted to end the appliation , I said 'Yes . ' <code> using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; namespace ConsoleApplication1 { class Program { static void Main ( string [ ] args ) { try { throw new Exception ( ) ; } finally { Console.WriteLine ( `` finally '' ) ; } } } }
Why is n't the finally getting executed ?
C_sharp : How to check , if a word can be made by letters of another word . using every letter only once.Example : if str = `` computer '' ; then <code> //if user enters below words output must be true comp put poet//and if user enters below words output must be false count // since n is not in str root // since there is only single o in str
Check if a string can be made by chars of another string in C #
C_sharp : I have a .NET Core worker application and want to add a custom file logger since Microsoft.Extensions.Logging does not provide this . I do n't want to use an extra package for this ( e.g . Serilog ) .I put information about the log directory and log file into my options class . This options class also has a validator implementing the IValidateOptions interface . This validator gets injected a logger instance to log validation errors if some occured.The file logger provider needs to get injected the options monitor to get access to the directory and file configurations.When running the application I unfortunately get an exceptionSystem.AggregateException : 'Some services are not able to beconstructed'with the contentError while validating the service descriptor 'ServiceType : Microsoft.Extensions.Hosting.IHostApplicationLifetime Lifetime : Singleton ImplementationType : Microsoft.Extensions.Hosting.Internal.ApplicationLifetime ' : A circulardependency was detected for the service of type'Microsoft.Extensions.Logging.ILoggerFactory'.Microsoft.Extensions.Hosting.IHostApplicationLifetime ( Microsoft.Extensions.Hosting.Internal.ApplicationLifetime ) - > Microsoft.Extensions.Logging.ILogger < Microsoft.Extensions.Hosting.Internal.ApplicationLifetime > ( Microsoft.Extensions.Logging.Logger < Microsoft.Extensions.Hosting.Internal.ApplicationLifetime > ) - > Microsoft.Extensions.Logging.ILoggerFactory ( Microsoft.Extensions.Logging.LoggerFactory ) - > System.Collections.Generic.IEnumerable < Microsoft.Extensions.Logging.ILoggerProvider > - > Microsoft.Extensions.Logging.ILoggerProvider ( Ajifsdjfijgsidjfijsdifjisd.FileLoggerProvider ) - > Microsoft.Extensions.Options.IOptionsMonitor < MyLib.MyOptions > ( Microsoft.Extensions.Options.OptionsMonitor < MyLib.MyOptions > ) - > Microsoft.Extensions.Options.IOptionsFactory < MyLib.MyOptions > ( Microsoft.Extensions.Options.OptionsFactory < MyLib.MyOptions > ) - > System.Collections.Generic.IEnumerable < Microsoft.Extensions.Options.IValidateOptions < MyLib.MyOptions > > - > Microsoft.Extensions.Options.IValidateOptions < MyLib.MyOptions > ( MyLib.MyOptionsValidator ) - > Microsoft.Extensions.Logging.ILogger < Microsoft.Extensions.Options.IValidateOptions < MyLib.MyOptions > > ( Microsoft.Extensions.Logging.Logger < Microsoft.Extensions.Options.IValidateOptions < MyLib.MyOptions > > ) - > Microsoft.Extensions.Logging.ILoggerFactoryThis makes sense because when injecting a new logger instance this one gets injected the options . And these will trigger the validator which gets injected a new logger instance . And so it starts again.Logger = > Options = > Validator = > Logger = > Options = > Validator = > Logger = > Options = > Validator = > ... I do n't know how to solve this problem because my file logger needs to get access to the configuration options and my options validator should log validation errors.Any ideas ? If you want to get an overview about the application , this is what I did to reproduce it : Create a new .NET Core Worker projectHead over to the .csproj file and add < FrameworkReference Include= '' Microsoft.AspNetCore.App '' / > to the first item group to gain access to Kestrel and the web stuffI add a library MyLib to the project and reference it in the main projectIn the library I create a options class holding the information for the file logger.I also add a simple options validator sample which makes use of a logger instance.I add the options to the appsettings.json file.In the library I extend the service collection to register the options validation.In the main project I setup the logging part . First I create a new file logger . Since this one ca n't be a `` normal '' service and wo n't be added to the DI container I simply expect the needed options in the constructor.To serve this logger I added a provider.and extend the logging builder to add the file logger.As you would do in a Web API project I added a startup file to configure all the options and setup the services.For the last part I updated the Program file to this.You should get a System.AggregateException because of a circular dependency <code> public class MyOptions { public string DirectoryPath { get ; set ; } public string FileName { get ; set ; } } public class MyOptionsValidator : IValidateOptions < MyOptions > { private readonly ILogger < IValidateOptions < MyOptions > > logger ; public MyOptionsValidator ( ILogger < IValidateOptions < MyOptions > > logger ) { this.logger = logger ; } public ValidateOptionsResult Validate ( string name , MyOptions myOptions ) { if ( string.IsNullOrEmpty ( myOptions.DirectoryPath ) || string.IsNullOrEmpty ( myOptions.FileName ) ) { logger.LogWarning ( `` Invalid '' ) ; return ValidateOptionsResult.Fail ( `` Invalid '' ) ; } return ValidateOptionsResult.Success ; } } `` MyOptions '' : { `` DirectoryPath '' : `` C : \\Logs '' , `` FileName '' : `` log.log '' } public static class IServiceCollectionExtensions { public static IServiceCollection AddMyLib ( this IServiceCollection services ) = > services.AddSingleton < IValidateOptions < MyOptions > , MyOptionsValidator > ( ) ; } internal class FileLogger : ILogger { private readonly string fullLogFilePath ; public FileLogger ( string logDirectoryPath , string logFileName ) { if ( ! Directory.Exists ( logDirectoryPath ) ) Directory.CreateDirectory ( logDirectoryPath ) ; fullLogFilePath = Path.Combine ( logDirectoryPath , logFileName ) ; } public void Log < TState > ( LogLevel logLevel , EventId eventId , TState state , Exception exception , Func < TState , Exception , string > formatter ) { if ( ! IsEnabled ( logLevel ) ) return ; using StreamWriter streamWriter = new StreamWriter ( fullLogFilePath , true ) ; streamWriter.WriteLine ( $ '' [ { DateTime.Now } ] [ { logLevel } ] { formatter ( state , exception ) } { exception ? .StackTrace } '' ) ; } public bool IsEnabled ( LogLevel logLevel ) = > logLevel ! = LogLevel.None ; public IDisposable BeginScope < TState > ( TState state ) = > null ; } internal class FileLoggerProvider : ILoggerProvider { private readonly IOptionsMonitor < MyOptions > myOptionsMonitor ; public FileLoggerProvider ( IOptionsMonitor < MyOptions > myOptionsMonitor ) { this.myOptionsMonitor = myOptionsMonitor ; } public void Dispose ( ) { } public ILogger CreateLogger ( string categoryName ) { MyOptions myOptions = myOptionsMonitor.CurrentValue ; return new FileLogger ( myOptions.DirectoryPath , myOptions.FileName ) ; } } public static class ILoggingBuilderExtensions { public static void AddFileLogger ( this ILoggingBuilder loggingBuilder ) { loggingBuilder.Services.AddSingleton < ILoggerProvider , FileLoggerProvider > ( ) ; } } internal class Startup { private readonly IConfiguration configuration ; public Startup ( IConfiguration configuration ) { this.configuration = configuration ; } public void ConfigureServices ( IServiceCollection services ) { services.AddMyLib ( ) ; IConfigurationSection myOptionsSection = configuration.GetSection ( `` MyOptions '' ) ; services.Configure < MyOptions > ( myOptionsSection ) ; } public void Configure ( IApplicationBuilder applicationBuilder ) { } } public class Program { public static void Main ( string [ ] args ) { CreateHostBuilder ( args ) .Build ( ) .Run ( ) ; } public static IHostBuilder CreateHostBuilder ( string [ ] args ) = > Host.CreateDefaultBuilder ( args ) .ConfigureLogging ( loggingBuilder = > { loggingBuilder .ClearProviders ( ) .AddConsole ( ) .AddEventLog ( ) .AddFileLogger ( ) ; } ) .ConfigureWebHostDefaults ( webHostBuilder = > { webHostBuilder.UseKestrel ( ) .UseStartup < Startup > ( ) ; } ) .ConfigureServices ( ( hostContext , services ) = > { services.AddHostedService < Worker > ( ) ; } ) ; }
Circular dependency exception when creating a custom logger relying on options with a options validator relying on a logger
C_sharp : I 'm hoping someone can identify the language feature ( or bug ) that resulted in the change in behaviour of the program below . It is reproduced from a much larger scenario that was intended to log a message if the delegate supplied to Orchard : :Go was not static.The scenario is : If I compile and run a debug build produced with Visual Studio 2013 , the output is True.If I compile and run a debug build produced with Visual Studio 2015 , the output is False.In both cases , the target .NET Framework is 4.5.If I compile and run a release build produced with Visual Studio 2015 , the output is True ( and thus consistent with Visual Studio 2013 ) .Visual Studio 2015 is the RC version ( if that matters ) .I can see from ildasm the 2013 generated code ... ... is clearly different to the 2015 generated code ... ... but my knowledge of IL and compiler changes is n't sufficient to determine whether this is a new feature or an unintended bug . I can produce the full IL dumps on request , but can anyone tell me from the information I 've supplied what is going on here and whether it is intentional ? Why is the anonymous method considered static in 2013 but non-static in 2015 ? <code> using System ; namespace Sample { public static class Program { public static void Main ( ) { new Apple ( ) ; } } public sealed class Apple { public Apple ( ) { Orchard.Go ( ( ) = > { } ) ; } } internal static class Orchard { public static void Go ( Action action ) { Console.WriteLine ( action.Method.IsStatic ) ; } } } ___ [ MOD ] C : \Sample.exe | M A N I F E S T |___ [ NSP ] Sample | |___ [ CLS ] Sample.Apple | | | .class public auto ansi sealed beforefieldinit | | |___ [ STF ] CS $ 9__CachedAnonymousMethodDelegate1 : private static class [ mscorlib ] System.Action | | |___ [ MET ] .ctor : void ( ) | | | b__0 : void ( ) | | | |___ [ CLS ] Sample.Orchard | | | .class private abstract auto ansi sealed beforefieldinit | | |___ [ STM ] Go : void ( class [ mscorlib ] System.Action ) | | | |___ [ CLS ] Sample.Program | | | .class public abstract auto ansi sealed beforefieldinit | | |___ [ STM ] Main : void ( ) | | | ___ [ MOD ] C : \Sample.exe | M A N I F E S T |___ [ NSP ] Sample | |___ [ CLS ] Sample.Apple | | | .class public auto ansi sealed beforefieldinit | | |___ [ CLS ] c | | | | .class nested private auto ansi serializable sealed beforefieldinit | | | | .custom instance void [ mscorlib ] System.Runtime.CompilerServices.CompilerGeneratedAttribute : :.ctor ( ) = ( 01 00 00 00 ) ... | | | |___ [ STF ] 9 : public static initonly class Sample.Apple/ ' c ' | | | |___ [ STF ] 9__0_0 : public static class [ mscorlib ] System.Action | | | |___ [ STM ] .cctor : void ( ) | | | |___ [ MET ] .ctor : void ( ) | | | | b__0_0 : void ( ) | | | | | |___ [ MET ] .ctor : void ( ) | | | |___ [ CLS ] Sample.Orchard | | | .class private abstract auto ansi sealed beforefieldinit | | |___ [ STM ] Go : void ( class [ mscorlib ] System.Action ) | | | |___ [ CLS ] Sample.Program | | | .class public abstract auto ansi sealed beforefieldinit | | |___ [ STM ] Main : void ( ) | | |
Anonymous method staticness different between 2013 and 2015 debug compilations
C_sharp : I have run into a problem that I 'm not sure how to resolve . I have a method that contains a call from a service that populates a data table such as : So , as you can see , there is n't a way for me to grab just a few cases at a time - it just grabs it all . Right now , I have this method being called in a BackgroundWorker 's DoWork event , and I display another form with a marquee progress bar on it so the user will know that the system is actually doing something . On that form , I have a Cancel button that I subscribe to . Here is the code that does that : I have tried to cancel the BackgroundWorker in the CancelBW event by using CancelAsync ( ) , but then I read more and realize that does n't work and would only work if I could break up that initial call so the BackgroundWorker could check on progress.I have thought about using Thread instead of a BackgroundWorker , but have read that Aborting a thread will cause kittens to spontaneously combust . So , what 's the best way for me to handle this in which a user could cancel a long process ? <code> private void GetCases ( ) { try { //Setup our criteria Web_search_criteria myCriteria = new Web_search_criteria ( ) { Keynum = 9 , //Use Opening Date Key Range_start = `` 20100101 '' , //01-01-2010 Range_end = `` 20121223 '' //12-23-2013 } ; //The myCases object is a datatable that is populated from the GetCasesDT ( ) call . int status = db.server.GetCasesDT ( myCriteria , ref myCases ) ; } catch ( Exception ex ) { XtraMessageBox.Show ( `` Unable to get data : `` + ex.Message ) ; } } backgroundWorker1 = new BackgroundWorker ( ) { WorkerSupportsCancellation = true , WorkerReportsProgress = true } ; //DoWork Event backgroundWorker1.DoWork += backgroundWorker1_DoWork ; //Show the progress bar with subscription to event pb.btnCancel.Click += this.CancelBW ; pb.Show ( ) ; //Run the backgroundworker this.backgroundWorker1.RunWorkerAsync ( ) ; //Do n't lock up the application while ( this.backgroundWorker1.IsBusy ) { Application.DoEvents ( ) ; }
What 's the best way to cancel a long operation ?
C_sharp : Why can I do this : but not this : It complains that I have n't restricted the generic type enough , but then I would think that rule would apply to casting with `` ( T ) '' as well . <code> public T GetMainContentItem < T > ( string moduleKey , string itemKey ) { return ( T ) GetMainContentItem ( moduleKey , itemKey ) ; } public T GetMainContentItem < T > ( string moduleKey , string itemKey ) { return GetMainContentItem ( moduleKey , itemKey ) as T ; }
Why does `` as T '' get an error but casting with ( T ) not get an error ?
C_sharp : i need some help on one line with translating this code : Original in C # : My translation to VB : I get error in line : Error : Value of type Boolean can not be converted to WindowsApplication1.Map_Control.Modal.MapModalTo clarify what am I doing . I am trying to build wpf application and use bing maps . I am following code from this link. , but i am not using Silverlight and i am coding in VB . <code> using System.Collections.ObjectModel ; using Microsoft.Maps.MapControl ; namespace Binding_Bing_Map_Control.Modal { public class MapModal { public Location MapLocation { get ; set ; } public string TooltipText { get ; set ; } public static ObservableCollection < MapModal > getMapRecords ( ) { ObservableCollection < MapModal > MapRecords = new ObservableCollection < MapModal > ( ) ; MapRecords.Add ( new MapModal ( ) { MapLocation = new Location ( 47.610015 , -122.188362 ) , TooltipText = `` Main St , Bellevue , WA 98004 '' } ) ; MapRecords.Add ( new MapModal ( ) { MapLocation = new Location ( 47.603562 , -122.329496 ) , TooltipText = `` James St , Seattle , wa 98104 '' } ) ; MapRecords.Add ( new MapModal ( ) { MapLocation = new Location ( 47.609355 , -122.189970 ) , TooltipText = `` Main St , Bellevue , WA 98004-6405 '' } ) ; MapRecords.Add ( new MapModal ( ) { MapLocation = new Location ( 47.615820 , -122.238973 ) , TooltipText = `` 601 76th Ave , Medina , WA 98039 '' } ) ; return MapRecords ; } } } Imports System.Collections.ObjectModelImports Microsoft.Maps.MapControlNamespace Map_Control.ModalPublic Class MapModal Public Property Location As WPF.Location Public Property TooltipTex As String Public Function getMapRecors ( ) As ObservableCollection ( Of MapModal ) Dim MapRecords As New ObservableCollection ( Of MapModal ) MapRecords.Add ( New MapModal ( ) { Location = New WPF.Location ( 47 , -122 ) , TooltipTex = `` Sample tooltiptext ! '' } ) Return MapRecords End FunctionEnd ClassEnd Namespace MapRecords.Add ( New MapModal ( ) { Location = New WPF.Location ( 47 , -122 ) , TooltipTex = `` Sample tooltiptext ! '' } )
How to translate this line of code from C # to Visual Baisc
C_sharp : For this piece of code : I 'm geting 'Ol ? ' instead of 'Olá'What 's wrong with it ? <code> String content = String.Empty ; ListenerStateObject state = ( ListenerStateObject ) ar.AsyncState ; Socket handler = state.workSocket ; int bytesRead = handler.EndReceive ( ar ) ; if ( bytesRead > 0 ) { state.sb.Append ( Encoding.UTF8.GetString ( state.buffer , 0 , bytesRead ) ) ; content = state.sb.ToString ( ) ; ...
Character encoding
C_sharp : I have been working on a small mathematical scripting engine ( or DSL , if you prefer ) . Making it for fun , its nothing serious . In any case , one of the features I want is the ability to get results from it in a type safe manner . The problem is that there are 5 different types that it can return.Number , bool , Fun , FunN and NamedValue . There is also AnyFun which is a abstract base class for Fun and FunN . The difference between Fun and FunN is that Fun only takes one argument , while FunN takes more then one argument . Figured it was common enough with one argument to warrant a separate type ( could be wrong ) .At the moment , I am using a wrapper type called Result and a class called Matcher to accomplish this ( inspired by pattern matching in languages like F # and Haskell ) . It basically looks like this when you use it.This is my current implementation . It is rigid , though . Adding new types is rather tedious.The thing is that I want to add more types . I want to make so functions can return both numbers and bools , and change Fun to Fun < T > , where T is the return type . This is actually where the main problem lies . I have AnyFun , Fun , FunN , and after introducing this change I would have to deal with AnyFun , Fun < Number > , Fun < bool > , FunN < Number > , FunN < bool > . And even then I would want it to match AnyFun against any function that isnt matched themselves . Like this : Does anyone have any suggestions for a better implementation , that handles adding new types better ? Or are there any other suggestions for how to get the result in a type safe manner ? Also , should I have a common base class for all the return types ( and add a new type for bool ) ? Performance is not an issue , btw.Take care , KerrEDIT : After reading the feedback , I have created this matcher class instead.Its shorter , but the order of the cases matter . For example , in this case the Fun option will never run.But it will if you switch places.Is it possible to improve that ? Are there any other issues with my code ? EDIT 2 : Solved it : D . <code> engine.Eval ( src ) .Match ( ) .Case ( ( Number result ) = > Console.WriteLine ( `` I am a number '' ) ) .Case ( ( bool result ) = > Console.WriteLine ( `` I am a bool '' ) ) .Case ( ( Fun result ) = > Console.WriteLine ( `` I am a function with one argument '' ) ) .Case ( ( AnyFun result ) = > Console.WriteLine ( `` I am any function thats not Fun '' ) ) .Do ( ) ; public class Result { public object Val { get ; private set ; } private Callback < Matcher > _finishMatch { get ; private set ; } public Result ( Number val ) { Val = val ; _finishMatch = ( m ) = > m.OnNum ( val ) ; } public Result ( bool val ) { Val = val ; _finishMatch = ( m ) = > m.OnBool ( val ) ; } ... more constructors for the other result types ... public Matcher Match ( ) { return new Matcher ( this ) ; } // Used to match a result public class Matcher { internal Callback < Number > OnNum { get ; private set ; } internal Callback < bool > OnBool { get ; private set ; } internal Callback < NamedValue > OnNamed { get ; private set ; } internal Callback < AnyFun > OnAnyFun { get ; private set ; } internal Callback < Fun > OnFun { get ; private set ; } internal Callback < FunN > OnFunN { get ; private set ; } internal Callback < object > OnElse { get ; private set ; } private Result _result ; public Matcher ( Result r ) { OnElse = ( ignored ) = > { throw new Exception ( `` Must add a new exception for this ... but there was no case for this : P '' ) ; } ; OnNum = ( val ) = > OnElse ( val ) ; OnBool = ( val ) = > OnElse ( val ) ; OnNamed = ( val ) = > OnElse ( val ) ; OnAnyFun = ( val ) = > OnElse ( val ) ; OnFun = ( val ) = > OnAnyFun ( val ) ; OnFunN = ( val ) = > OnAnyFun ( val ) ; _result = r ; } public Matcher Case ( Callback < Number > fn ) { OnNum = fn ; return this ; } public Matcher Case ( Callback < bool > fn ) { OnBool = fn ; return this ; } ... Case methods for the rest of the return types ... public void Do ( ) { _result._finishMatch ( this ) ; } } } engine.Eval ( src ) .Match ( ) .Case ( ( Fun < Number > result ) = > Console.WriteLine ( `` I am special ! ! ! '' ) ) .Case ( ( AnyFun result ) = > Console.WriteLine ( `` I am a generic function '' ) ) .Do ( ) ; public class Matcher { private Action _onCase ; private Result _result ; public Matcher ( Result r ) { _onCase = null ; _result = r ; } public Matcher Case < T > ( Callback < T > fn ) { if ( _result.Val is T & & _onCase == null ) { _onCase = ( ) = > fn ( ( T ) _result.Val ) ; } return this ; } public void Else ( Callback < object > fn ) { if ( _onCase ! = null ) _onCase ( ) ; else fn ( _result.Val ) ; } public void Do ( ) { if ( _onCase == null ) throw new Exception ( `` Must add a new exception for this ... but there was no case for this : P '' ) ; _onCase ( ) ; } } .Case ( ( AnyFun result ) = > Console.WriteLine ( `` AAANNNNNNNYYYYYYYYYYYYY ! ! ! ! `` ) ) .Case ( ( Fun result ) = > Console.WriteLine ( `` I am alone '' ) ) .Case ( ( Fun result ) = > Console.WriteLine ( `` I am alone '' ) ) .Case ( ( AnyFun result ) = > Console.WriteLine ( `` AAANNNNNNNYYYYYYYYYYYYY ! ! ! ! '' ) )
Type safe way to return values from a scripting language in C #
C_sharp : So I was looking through the implementation of SortedList < TKey , TValue > and the implementation of Add ( which calls Insert shown below ) really surprised me.The Add method does the obvious binary search to determine the index in which the KVP should go , but the Insert seems as if it could be improved significantly ( albeit on larger scales of course ) : If I 'm reading this correctly , and I reserve the right to be wrong at all times , this is an O ( 2n ) operation.It seems to me that the values should be implemented with pointers . Kind of like a LinkedList in relation to the value from the key , but not linked in that it does n't support random access . More so the key is simply linked to its value . The get operation would n't be any slower , and neither would the remove because we have the pointer , but the add operation would be O ( n ) now instead.Can somebody shed some light on why the decision may have gone this direction ? <code> private void Insert ( int index , TKey key , TValue value ) { if ( this._size == this.keys.Length ) this.EnsureCapacity ( this._size + 1 ) ; if ( index < this._size ) { Array.Copy ( ( Array ) this.keys , index , ( Array ) this.keys , index + 1 , this._size - index ) ; Array.Copy ( ( Array ) this.values , index , ( Array ) this.values , index + 1 , this._size - index ) ; } this.keys [ index ] = key ; this.values [ index ] = value ; ++this._size ; ++this.version ; }
Why SortedList < TKey , TValue > does n't use pointers for the values ?
C_sharp : If I have the methodI can successfully call it like this : As I imagine the compiler/runtime can infer the type , However If I change the method to this : Then I must call it in 'full ' , specifying both the input parameter type and the return type : Is there a way I can shorthand this so I dont need to specify the input parameter ( s ) type ? I.E.Thanks <code> void foo < T > ( T bar ) { } string s = string.Empty ; foo ( s ) ; T foo < T , T2 > ( T2 bar ) { ... } string s = string.Empty ; foo < int , string > ( s ) ; foo < int > ( s ) ;
Shorthand when calling generic methods in c #
C_sharp : First of all , basically I believe I just need help in figuring out how to calculate it , math isnt really my strong side.FYI , the MS-Word is most likely not relevant to solve my problem , I basically just mention it so you know the context I am in , but I believe it should be solvable also for people who have no knowledge about MS-Word.I have the problem that Word has the property VerticalPercentScrolled which is an integer.Which isnt as accurate as I need it to be , consider a Word Document with 300 pages and the scrollbar can only have a integer between 0 - 100 ( percent ) , so for example 25 percent of a 300 page document is a rather big range.I have now gone and read the correct value , with the help of UI Automation library - TestStack.White - and can successfully set it to its old value , if some un-desired scrolling happens.Like this : with this code I get a percent value of lets say 9.442248572683356 instead of 9.To reset the value I use the following code : This works like a charm.Now my problem is what if my document gets larger/smaller during the time I stored the oldValue and want to reapply it , my oldValue needs to be adjusted.I can read the following values ( at least those I found so far ) : ScrollPattern.VerticalScrollPercentPropertyScrollPattern.VerticalViewSizePropertyI can also go and look for the scrollbar it self and read the following values : RangeValuePattern.LargeChangePropertyRangeValuePattern.MaximumPropertyRangeValuePattern.MinimumPropertyRangeValuePattern.SmallChangePropertyRangeValuePattern.ValuePropertyTo look for the scrollbar , I use the following code : You may ask yourself , why I dont set the RangeValuePattern.ValueProperty when I am able to access it , the problem there is that Word doesnt update the document when I change this property , the scroll thumb does move but the document doesnt move an inch.I have to set the ScrollPattern.VerticalScrollPercentProperty for it to work.So my question , is how do I calculate the new ScrollPattern.VerticalScrollPercentProperty based on the oldValue , where the document could shrink or grow in size in between ? Edit : Here is a testscenario : After inserting 5 new pagesAnd as said , I need to adjust the scrollPercent - after inserting those pages - so that it is again on the old position.I can tell you that in this testscenario , I would need the new value to beafter changing it to the desired percentValue the scrollBarValue is the only value getting updated and it is than at <code> var hWnd = ( IntPtr ) WordUtils.GetHwnd ( ) ; var processId = Process.GetCurrentProcess ( ) .Id ; var uiApp = TestStack.White.Application.Attach ( ( int ) processId ) ; var uiWindow = uiApp.GetWindow ( WindowHandling.GetWindowText ( hWnd ) , InitializeOption.NoCache ) ; var wf = ( IUIItemContainer ) uiWindow.Get ( SearchCriteria.ByClassName ( `` _WwF '' ) ) ; var wbs= wf.GetMultiple ( SearchCriteria.ByClassName ( `` _WwB '' ) ) ; if ( wbs.Length ! = 1 ) return ; var wb= ( IUIItemContainer ) wbs.First ( ) ; var wgs = wb.GetMultiple ( SearchCriteria.ByClassName ( `` _WwG '' ) ) ; if ( wgs.Length ! = 1 ) return ; var wg = wgs.First ( ) ; var element = wg.AutomationElement ; var oldVerticalPercent = ( double ) element.GetCurrentPropertyValue ( ScrollPattern.VerticalScrollPercentProperty ) ; object scrollPattern ; if ( element.TryGetCurrentPattern ( ScrollPattern.Pattern , out scrollPattern ) ) ( ( ScrollPattern ) scrollPattern ) .SetScrollPercent ( ScrollPattern.NoScroll , oldVerticalPercent ) ; var hWnd = ( IntPtr ) WordUtils.GetHwnd ( ) ; var processId = Process.GetCurrentProcess ( ) .Id ; var uiApp = Ts.Application.Attach ( ( int ) processId ) ; var uiWindow = uiApp.GetWindow ( WindowHandling.GetWindowText ( hWnd ) , InitializeOption.NoCache ) ; var wf = ( IUIItemContainer ) uiWindow.Get ( SearchCriteria.ByClassName ( `` _WwF '' ) ) ; var wbs = wf.GetMultiple ( SearchCriteria.ByClassName ( `` _WwB '' ) ) ; if ( wbs.Length ! = 1 ) return ; var wb = ( IUIItemContainer ) wbs.First ( ) ; var wgs= wb.GetMultiple ( SearchCriteria.ByClassName ( `` _WwG '' ) ) ; if ( wgs.Length ! = 1 ) return ; var nUiScrollBars = wgs.GetMultiple ( SearchCriteria.ByClassName ( `` NUIScrollbar '' ) ) ; if ( scrollBar.Length ! = 1 ) return ; var nUiScrollBar = ( IUIItemContainer ) nUiScrollBars.First ( ) ; var nUiHwndElements = nUiScrollBar.GetMultiple ( SearchCriteria.ByClassName ( `` NetUIHWNDElement '' ) ) ; if ( nUiHwndElements.Length ! = 1 ) return ; var nUiHwndElement = ( IUIItemContainer ) nUiHwndElements.First ( ) ; var netUiScrollBar = nUiHwndElement.GetElement ( SearchCriteria.ByClassName ( `` NetUIScrollBar '' ) ) ; var scrollBarValue = ( double ) netUiScrollBar.GetCurrentPropertyValue ( RangeValuePattern.ValueProperty ) ; scrollPercent 64.86486486486487scrollViewSize 74.394463667820062scrollBarLargeChange 37197scrollBarMaximum 12803scrollBarMinimum 0scrollBarSmallChange 1scrollBarValue 8304 scrollPercent 87.890366182251867 < -- undesired scrolling occured ( see desired values below ) scrollViewSize 9.442248572683356scrollBarLargeChange 4721scrollBarMaximum 45279scrollBarMinimum 0scrollBarSmallChange 1scrollBarValue 39795 < -- undesired scrolling occured ( see desired values below ) scrollPercent 2.3278413357480452 scrollBarValue 1054
Calculate new ScrollPercent - after ViewSize changed
C_sharp : As explained in this question , and these articles , the following is not allowed : Because if it was , and you had this : and then : This is illegal because even though B 's access to X means it knows that C has the desired signature it 's still not allowed to actually access the member.So far , so good . But given the above , what I 'm confused about is why I can do this : And , therefore , this : The definition of the protected keyword says : A protected member is accessible within its class and by derived class instances.But now the protected member on C is being accessed from within A , which is neither `` its class '' nor a `` derived class instance '' , but a parent class . While A obviously has access to the signature , the sibling example seems to indicate that that alone is not supposed to be sufficent , so why is protected granting it access to the member ? <code> public class A { protected virtual int X { get ; private set ; } } public class B : A { public int Add ( A other ) { return X + other.X ; } } public class C : A { protected override int X { get { return 4 ; } } } A c = new C ( ) ; B b = new B ( ) ; b.Add ( c ) ; public class A { protected virtual int X { get ; private set ; } public int Add ( A other ) { return X + other.X ; } } A c = new C ( ) ; A a = new A ( ) ; a.Add ( c ) ;
Why can parents access instances of child class ' protected members , if siblings ca n't ?
C_sharp : When I write this code in VS , it does n't work ( `` Can not implicitly convert 'int ' to 'short ' . An explicit conversion exists . Are you missing a cast ? `` ) : Yet this code is absolutely fine : I know I can make the error go away by casting the entire expression as a short , but can anyone tell me why this happens ? <code> short A = 5 ; short B = 1 < < A ; short A = 1 < < 5 ;
Bitshifting Int16 's only works with literals
C_sharp : I 'm using a third party library which contains a bunch of extension methods on top of IQueryable . To use these extension methods i do n't wish to have my application littered with using statements to the third party namespace in which the extension method resides in.This is so that i can switch it out the library sometime in the near future as easily as possible . However i 'm not sure what 's the best way of doing this . One option i did contemplate was to create my own set of extension methods within the project ( then i can control the namespace ) . The problem with this is i ca n't see how i can maintain the name of the existing extension method . For example : You may see the problem here . Where i am trying to call the third party extension method within mine it actually calls itself creating an infinite loop.I 'd appreciate the help . Thanks <code> namespace MyProject.Extensions { public static class IQueryableExtension { public static IQueryable < T > Fetch < T , K > ( this IQueryable < T > queryable , Expression < Func < T , K > > selector ) { return queryable.Fetch ( selector ) ; } } }
Extension Methods - Changing the Namespace
C_sharp : I have got a struct : And now I can do : It seems the compiler is smart enough to convert Decibel to double , and then use the < operator for doubles ? I had different struct named Duration , which was wrapping TimeSpan . It had implicit conversions for TimeSpan to/from Duration , but the < and > operators are not working for it.Does c # only recognize conversion between primitive types ? <code> public struct Decibel { public readonly double Value ; public Decibel ( double value ) { Value = value ; } public static implicit operator Decibel ( double decibels ) { return new Decibel ( decibels ) ; } public static implicit operator double ( Decibel decibels ) { return decibels.Value ; } } bool x = new Decibel ( 0 ) < new Decibel ( 1 ) ;
What implicit conversions are supported when using < and > operators ?
C_sharp : I have changed the following SystemColors already : I 'm not sure what to call it , but which SystemColor is responsible for what I 'm calling the : `` InactiveSelectedItem '' ? It changes to this color every time I lose focus on the SelectedItem . Would be nice if someone could help me . I used blend already to check but I can not find . The color is # F0F0F0.Example : <code> < ! -- Background of selected item when focussed -- > < SolidColorBrush x : Key= '' { x : Static SystemColors.HighlightBrushKey } '' Color= '' Transparent '' / > < ! -- Background of selected item when not focussed -- > < SolidColorBrush x : Key= '' { x : Static SystemColors.ControlBrushKey } '' Color= '' Transparent '' / >
ListBox SystemColor for Inactive Item ?
C_sharp : I just found out that it is possible to use the keyword var as a class name : Now if I overload the implicit cast operator I can use my class in an interesting manner : In such scenario , is it still possible to somehow make the compiler infer the types ? This blog entry states that it is not possible ( go to the paragraph starting with `` Or , another example . `` ) , but maybe something changed since 2009 ? <code> public class var // no problem here { } namespace MyApp { class Program { static void Main ( string [ ] args ) { var x = 1 ; // var is of type MyApp.var } } public class var { public implicit operator var ( int i ) { return new var ( ) ; } } }
Can you take advantage of implicit type variables with a class named ` var ` ?
C_sharp : I would like to find a way to check to see if a set of values are contained in my variable.I am a transplant to .NET from Delphi . This is fairly easy code to write in Delphi , but I am not sure how to do it in C # . <code> [ Flags ] public enum Combinations { Type1CategoryA = 0x01 , // 00000001 Type1CategoryB = 0x02 , // 00000010 Type1CategoryC = 0x04 , // 00000100 Type2CategoryA = 0x08 , // 00001000 Type2CategoryB = 0x10 , // 00010000 Type2CategoryC = 0x20 , // 00100000 Type3 = 0x40 // 01000000 } bool CheckForCategoryB ( byte combinations ) { // This is where I am making up syntax if ( combinations in [ Combinations.Type1CategoryB , Combinations.Type2CategoryB ] ) return true ; return false ; // End made up syntax }
Set In enum for C #
C_sharp : I 've run my code through code coverage and the line below shows 1 block as not covered.Can anyone tell me which part of that line is n't executing ? An Example to play with : and the test method <code> public abstract class Base { public abstract IExample CreateEntity < TExample > ( ) where TExample : IExample , new ( ) ; } public class Class1 : Base { public override IExample CreateEntity < TExample > ( ) { IExample temp = new TExample ( ) ; return temp ; } } public interface IExample { } public class TEx : IExample { } [ TestMethod ] public void TestMethod1 ( ) { Class1 ex = new Class1 ( ) ; ex.CreateEntity < TEx > ( ) ; }
Creation of a new instance of generic type parameter not getting code coverage
C_sharp : Targeting .net 4.0 , I 'm trying to build the following classes : As the code comment above indicates , the compiler gives an error : Can not implicitly convert type 'Shared.Configuration.ConfigurationElementCollection < TElement , TParent > ' to 'Shared.Configuration.ConfigurationElementCollection < Shared.Configuration.ParentedConfigElement < TParent > , TParent > I do n't expect this error , because the compiler also knows that TElement is a Shared.Configuration.ParentedConfigElement < TParent > due to the generic type constraint I specified.Still , I figure I will expressly cast the type to get past this issue : Unfortunately , I get the same compiler error . Why is this happening ? What did I do wrong ? And without resorting to dynamic types , what can I do to fix this ? <code> public class ConfigurationElementCollection < TElement , TParent > where TElement : ParentedConfigElement < TParent > , new ( ) where TParent : class { public TParent ParentElement { get ; set ; } protected ConfigurationElement CreateNewElement ( ) { //************************************************** //COMPILER GIVES TYPE CONVERSION ERROR ON THIS LINE ! //************************************************** return new TElement { ParentCollection = this } ; } } public class ParentedConfigElement < TParent > : ConfigurationElement where TParent : class { internal ConfigurationElementCollection < ParentedConfigElement < TParent > , TParent > ParentCollection { get ; set ; } protected TParent Parent { get { return ParentCollection ! = null ? ParentCollection.ParentElement : null ; } } } ( ConfigurationElementCollection < ParentedConfigElement < TParent > , TParent > ) this ;
Invalid Cast of Type Constrained C # Generic
C_sharp : Here is my test code : the extension method GetInstructions is from here : https : //gist.github.com/jbevain/104001Here is run result as the screenshot shown : NON-ASYNC calls got correct generic parameters , but ASYNC calls can not .My question is : where are the generic parameters stored for ASYNC calls ? Thanks a lot . <code> using System ; using System.Linq ; using System.Reflection ; using System.Threading.Tasks ; namespace ConsoleApp1 { class Program { static void Main ( string [ ] args ) { typeof ( TestClass ) .GetMethods ( ) .Where ( method = > method.Name == `` Say '' || method.Name == `` Hello '' ) .ToList ( ) .ForEach ( method = > { var calls = method.GetInstructions ( ) .Select ( x = > x.Operand as MethodInfo ) .Where ( x = > x ! = null ) .ToList ( ) ; Console.WriteLine ( method ) ; calls.ForEach ( call = > { Console.WriteLine ( $ '' \t { call } '' ) ; call.GetGenericArguments ( ) .ToList ( ) .ForEach ( arg = > Console.WriteLine ( $ '' \t\t { arg.FullName } '' ) ) ; } ) ; } ) ; Console.ReadLine ( ) ; } } class TestClass { public async Task Say ( ) { await HelloWorld.Say < IFoo > ( ) ; HelloWorld.Hello < IBar > ( ) ; } public void Hello ( ) { HelloWorld.Say < IFoo > ( ) .RunSynchronously ( ) ; HelloWorld.Hello < IBar > ( ) ; } } class HelloWorld { public static async Task Say < T > ( ) where T : IBase { await Task.Run ( ( ) = > Console.WriteLine ( $ '' Hello from { typeof ( T ) } . `` ) ) .ConfigureAwait ( false ) ; } public static void Hello < T > ( ) where T : IBase { Console.WriteLine ( $ '' Hello from { typeof ( T ) } . `` ) ; } } interface IBase { Task Hello ( ) ; } interface IFoo : IBase { } interface IBar : IBase { } } System.Threading.Tasks.Task Say ( ) System.Runtime.CompilerServices.AsyncTaskMethodBuilder Create ( ) Void Start [ < Say > d__0 ] ( < Say > d__0 ByRef ) ConsoleApp1.TestClass+ < Say > d__0 System.Threading.Tasks.Task get_Task ( ) Void Hello ( ) System.Threading.Tasks.Task Say [ IFoo ] ( ) ConsoleApp1.IFoo Void RunSynchronously ( ) Void Hello [ IBar ] ( ) ConsoleApp1.IBar
Where are the generic parameters saved for Async calls ? Where to find its name or other information ?
C_sharp : How could I write this C # code in F # or Haskel , or a similar functional language ? <code> var lines = File.ReadAllLines ( @ '' \\ad1\\Users\aanodide\Desktop\APIUserGuide.txt '' ) ; // XSDs are lines 375-471var slice = lines.Skip ( 374 ) .Take ( 471-375+1 ) ; var kvp = new List < KeyValuePair < string , List < string > > > ( ) ; slice.Aggregate ( kvp , ( seed , line ) = > { if ( line.StartsWith ( `` https '' ) ) kvp.Last ( ) .Value.Add ( line ) ; else kvp.Add ( new KeyValuePair < string , List < string > > ( line , new List < string > ( ) ) ) ; } return kvp ; } ) ;
How does this C # code get done in functional languages ( F # ? Haskel ? )
C_sharp : I have a DataGrid simplified looking like this : My ViewModel looks something like this : Now I want changes to datagrid cells being stored immediately to the database . How to do that in MVVM ? Currently I listen to the OnCellEditEnding event of the DataGrid and save the record in the code-behind . But that is pretty ugly : <code> < DataGrid AutoGenerateColumns= '' False '' ItemsSource= '' { Binding Parts } '' SelectedItem= '' { Binding SelectedPart } '' > < DataGrid.Columns > < DataGridTextColumn Header= '' Name '' Binding= '' { Binding Path=Name , Mode=TwoWay } '' / > < DataGridTemplateColumn Header= '' PartType '' > < DataGridTemplateColumn.CellEditingTemplate > < DataTemplate > < ComboBox ItemsSource= '' { Binding RelativeSource= { RelativeSource AncestorType= { x : Type DataGrid } } , Path=DataContext.PartTypes } '' SelectedItem= '' { Binding PartType , Mode=TwoWay , UpdateSourceTrigger=LostFocus } '' / > < /DataTemplate > < /DataGridTemplateColumn.CellEditingTemplate > < DataGridTemplateColumn.CellTemplate > < DataTemplate > < TextBlock Text= '' { Binding PartType } '' / > < /DataTemplate > < /DataGridTemplateColumn.CellTemplate > < /DataGridTemplateColumn > < /DataGrid.Columns > < /DataGrid > public class PartListViewModel { private ObservableCollection < Part > _parts ; public ObservableCollection < Part > Parts { get { return _parts ; } set { _parts = value ; OnPropertyChanged ( `` Parts '' ) ; } } private Part _selectedPart ; public Part SelectedPart { get { return _selectedPart ; } set { _selectedPart = value ; OnPropertyChanged ( `` SelectedPart '' ) ; } } } private void DataGrid_OnCellEditEnding ( object sender , DataGridCellEditEndingEventArgs e ) { var viewModel = ( PartListViewModel ) DataContext ; viewModel.SavePart ( ( Part ) e.Row.Item ) ; }
WPF DataGrid : Save cell changes immediately with MVVM
C_sharp : I am wondering if it makes any sense to have both `` class '' and `` new ( ) '' constraints when defining a generic class . As in the following example : Both constraints specify that T should be a reference type . While the `` class '' constraint does not imply that a implicit constructor exists , the `` new ( ) '' constraint does require a `` class '' with an additional public constructor definition.My final ( formulation for the ) question is : do I have any benefits from defining a generic class as in the above statement , or does `` new ( ) '' encapsulate both constraints ? <code> class MyParanoidClass < T > where T : class , new ( ) { //content }
Is it pointless to have both `` class '' and `` new ( ) '' constraints in a generic class ?
C_sharp : I 've seen several articles talking about not generating too many System.Random instances too closely together because they 'll be seeded with the same value from the system clock and thus return the same set of numbers : https : //stackoverflow.com/a/2706537/2891835https : //codeblog.jonskeet.uk/2009/11/04/revisiting-randomness/https : //docs.microsoft.com/en-us/dotnet/api/system.random ? view=netframework-4.8 # instantiating-the-random-number-generatorThat appears to be true for .net framework 4.8.Looking at the source code for .net core , however , it looks like instances of System.Random generated on the same thread are seeded from a [ ThreadStatic ] generator.So it would seem to me that , in .net core , you are now safe to do something like : Is this true ? Am I missing something ? Note : Assume we 're talking about a single thread here ( although I 'm not sure it matters because it looks like .net core uses bcrypt or something to seed the global generator per-thread ? ) .EDIT : This is now tracked in this ticket . <code> Random [ ] randoms = new Random [ 1000 ] ; for ( int i = 0 ; i < randoms.Length ; i++ ) { randoms [ i ] = new Random ( ) ; } // use Random instances and they 'll all have distinct generated patterns
Do multiple instances of System.Random still use the same seed in .Net Core ?
C_sharp : I 'm currently working through the Pluralsight C # 5.0 course , and I 'm relatively new to programming.I previously thought I understood the concept of Data Types on a basic level , Int/Array/Strings etc.In this course it starts to introduce C # 's huge emphasis on Types , and creating your own custom types.One of the course code snippets which I 've included below , is refusing to sink in and I was hopingsomeone could provide some clarity or a different way of thinking about it.Program.cs : GradeStatistics.cs : Grades : I 'm finding it particularly difficult to understand what exactly GradeStatistics is.In the course it is referred to as not only a class , but as a variable , and furthermore alsobeing returned as an object in Grades.Any clarity is appreciated , as I 'm finding it a little difficult to follow with all of the above terms being thrown around . <code> GradeStatistics stats = book.ComputeStatistics ( ) ; namespace Grades { public class GradeStatistics { public GradeStatistics ( ) { HighestGrade = 0 ; LowestGrade = float.MaxValue ; } public float AverageGrade ; public float HighestGrade ; public float LowestGrade ; } } public GradeStatistics ComputeStatistics ( ) { GradeStatistics stats = new GradeStatistics ( ) ; float sum = 0f ; foreach ( float grade in grades ) { stats.HighestGrade = Math.Max ( grade , stats.HighestGrade ) ; stats.LowestGrade = Math.Min ( grade , stats.LowestGrade ) ; sum += grade ; } stats.AverageGrade = sum / grades.Count ; return stats ; }
Type confusion : A type is class , a variable and an object ?
C_sharp : I have a recording program that stays TopMost all the time except when I open a Modern app ( Windows 8 ) or the Start Screen.It is possible to make a desktop application stay on top of modern apps , like the Magnifying Glass tool : Now , the problem is that using the TopMost option and/or the API call in a WPF window wo n't work with modern apps.What I 'm trying : <code> static readonly IntPtr HWND_TOPMOST = new IntPtr ( -1 ) ; static readonly IntPtr HWND_NOTOPMOST = new IntPtr ( -2 ) ; static readonly IntPtr HWND_TOP = new IntPtr ( 0 ) ; static readonly IntPtr HWND_BOTTOM = new IntPtr ( 1 ) ; const UInt32 SWP_NOSIZE = 0x0001 ; const UInt32 SWP_NOMOVE = 0x0002 ; const UInt32 TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE ; [ DllImport ( `` user32.dll '' ) ] [ return : MarshalAs ( UnmanagedType.Bool ) ] public static extern bool SetWindowPos ( IntPtr hWnd , IntPtr hWndInsertAfter , int X , int Y , int cx , int cy , uint uFlags ) ; //OnLoaded event handler : var source = PresentationSource.FromVisual ( this ) as HwndSource ; SetWindowPos ( source.Handle , HWND_TOPMOST , 0 , 0 , 0 , 0 , TOPMOST_FLAGS ) ;
Top most even for Modern Apps
C_sharp : I am attempting to create a serialization interface ( similar to Cocoa 's NSCoding protocol ) so that I can get a quick binary representation of a class to send across a network or store in a database . However , some cases ( especially involving image encoding ) have many async-only methods that require awaiting . However , if the bytes do not get written in order then of course the whole representation is corrupted . I must make sure that the current object is finished serializing before I continue to the next object . Here is the main loop of what I am doing.Archiver just uses MemoryStream and BitmapWriter under the hood to write either values that BinaryWriter can accept directly , or ISerializable objects , and then spits out the result as a byte array . ISerializable is just an interface with two methods ( Serialize and Deserialize ) . They both return Task so that they can be awaited . The problem is when I have a serialization method that does n't have any async components . I can do one of two things : A ) I can tack on async to that class 's serialization methods anyway and put up with the compiler warning saying that it will execute synchronously ( I do n't like to have compiler warnings ) .B ) Manually return an empty task at the end of the method ( return Task.Run ( ( ) = > { } ) ; ) . However , this looks and smells really weird.Both A and B seem to execute without a problem , but are there any problems with this approach that I may have missed ? I am not aware of a binary serializer in Windows Runtime ( I included the tag just to dispel any confusion ) . Perhaps there is an option C that I can consider ? Actually I did n't want to make the serialization methods async , but for some reason task.Wait ( ) was not waiting , and I was getting a null reference exception from trying to use an object created with CreateAsync before it was ready.EDIT I thought of an option C. I could just wrap the entire method in an await Task.Run ( ... ) call . Would this be normal ? <code> public async static Task < byte [ ] > Serialize ( this IList < ISerializable > list ) { using ( Archiver archiver = new Archiver ( ) ) { archiver.Write ( list.Count ) ; foreach ( ISerializable value in list ) { await archiver.Write ( value ) ; } return archiver.Result ; } }
How can I handle an interface method that may or may not be async ?
C_sharp : Let 's say we have : Then we 'd like to instantiate Foo with an object initializer : The syntax of initializing BarPropertyInA baffles me , because the code compiles without warnings and , when run , throws NullReferenceException . I do n't recognize that syntax , but it seems to have the same effect when used with a field , rather than a property.Disassembling the compiled code yields this : Which looks like : So is this supposed to be some syntactic sugar for initializing property's/field 's members , provided that the property/field is initialized in the constructor ? <code> class Foo { public int IntPropertyInFoo { get ; set ; } public Bar BarPropertyInA { get ; set ; } } class Bar { public string StringPropertyInBar { get ; set ; } } public static void Main ( string [ ] args ) { var foo = new Foo { IntPropertyInFoo = 123 , BarPropertyInA = // Ommiting new and type name - why does it compile ? { StringPropertyInBar = `` something '' } } ; } .method public hidebysig static void Main ( string [ ] args ) cil managed { .entrypoint // Code size 34 ( 0x22 ) .maxstack 3 .locals init ( [ 0 ] class Test.Foo foo ) IL_0000 : nop IL_0001 : newobj instance void Test.Foo : :.ctor ( ) IL_0006 : dup IL_0007 : ldc.i4.s 123 IL_0009 : callvirt instance void Test.Foo : :set_IntPropertyInFoo ( int32 ) IL_000e : nop IL_000f : dup IL_0010 : callvirt instance class Test.Bar Test.Foo : :get_BarPropertyInA ( ) IL_0015 : ldstr `` something '' IL_001a : callvirt instance void Test.Bar : :set_StringPropertyInBar ( string ) IL_001f : nop IL_0020 : stloc.0 IL_0021 : ret } // end of method Program : :Main public static void Main ( string [ ] args ) { var foo = new Foo { IntPropertyInFoo = 123 } ; foo.BarPropertyInA.StringPropertyInBar = `` something '' ; }
Unrecognized C # syntax
C_sharp : I 've two similar projects . One is a Silverlight project and the other one a WPF . Both of them containing some namespaces and plenty of custom user controls . As the controls are distributed over many namespaces , I have to define quite a few namespaces , when I 'm using them . So I started to define the XML namespaces in the AssemblyInfo.cs : Now I have to define only one namespace in each file : Unfortunately this only works in Silverlight . My question is , how do I get this to work in a WPF project ? In the WPF project I get errors like this : <code> [ assembly : XmlnsPrefix ( `` http : //ui.example.com/xaml/touch '' , `` cui '' ) ] [ assembly : XmlnsDefinition ( `` http : //ui.example.com/xaml/touch '' , `` example_ui.controls '' ) ] [ assembly : XmlnsDefinition ( `` http : //ui.example.com/xaml/touch '' , `` example_ui.themes '' ) ] xmlns : cui= '' http : //ui.example.com/xaml/touch '' Error 5 The tag 'LookUpField ' does not exist in XML namespace 'http : //ui.example.com/xaml/touch ' . Line 7 Position 14 . D : \src\prototype\lookup-control\lookup-control\MainWindow.xaml 7 14 lookup-control
Why is XAML ( WPF ) not searching in my XML namespace definitions for the controls ?
C_sharp : I 've been looking into Entity Framework 7 source code on github and I 've found following property initialization in TableExpressionBase.csI have never seen such usage of = > operator in C # . I 've also looked what is new in C # 6.0 , however I have n't found this construct . Can someone explain what is the purpose of it ? Thanks . <code> public override ExpressionType NodeType = > ExpressionType.Extension ;
Initialization with = > ( such that )
C_sharp : I have a list of Func defining an ordering : I can order the results with something like ... I 'm trying to figure how to do the above when the list can contain any number of sequential orderings . Is it possible ? <code> var ordering = new List < Func < Person , IComparable > > { x = > x.Surname , x = > x.FirstName } ; people = people.OrderBy ( ordering [ 0 ] ) .ThenBy ( ordering [ 1 ] ) ;
Linq to Objects ordering by arbitrary number of parameters
C_sharp : I was working on a solution with multiple projects and I updated Newtonsoft.Json in a one of the projects ( a class library ) . This caused some errors in another project ( an ASP.Net WebApi project ) because it also needed the reference to Newtonsoft.Json to be updated . The error was thrown at run-time not compile-time and I had to manually install Newtonsoft.Json on each of the projects within the solution.This lead me to wonder if it is possible to update all third party libraries at solution level ? I know you can create a folder to store the libraries and add that to the source control but I would like to avoid that . I want Nuget to download the libraries after fetching the solution from the repository . I was wondering if it is possible to : Create a new project in the solution called something like www.solution.com.thirdparty Add reference to all third party software using nugetExpose the all third party libraries via www.solution.com.thirdpartyI do n't know how can I do the third step and I would also know if there is a better way to do this ? <code> Install-Package Newtonsoft.Json
How to ensure that all projects in a c # solution use same versions of third party library ?
C_sharp : I am using LINQ .Find ( ) and it 's not stopping when it finds a match . I have : Any ideas ? I 'm going nuts over here.Thanks ! <code> List < ipFound > ipList = new List < ipFound > ( ) ; ipFound ipTemp = ipList.Find ( x = > x.ipAddress == srcIP ) ; if ( ipTemp == null ) { // this is always null } public class ipFound { public System.Net.IPAddress ipAddress ; public int bytesSent ; public int bytesReceived ; public int bytesTotal ; }
c # : Not finding object in list
C_sharp : Here 's the story so far : I 'm doing a C # winforms application to facilitate specifying equipment for hire quotations.In it , I have a List < T > of ~1500 stock items.These items have a property called AutospecQty that has a get accessor that needs to execute some code that is specific to each item . This code will refer to various other items in the list.So , for example , one item ( let 's call it Item0001 ) has this get accessor that may need to execute some code that may look something like this : Which is all well and good , but these bits of code are likely to change on a weekly basis , so I 'm trying to avoid redeploying that often . Also , each item could ( will ) have wildly different code . Some will be querying the list , some will be doing some long-ass math functions , some will be simple addition as above ... some will depend on variables not contained in the list.What I 'd like to do is to store the code for each item in a table in my database , then when the app starts just pull the relevant code out and bung it in a list , ready to be executed when the time comes.Most of the examples I 've seen on the internot regarding executing a string as code seem quite long-winded , convoluted , and/or not particularly novice-coder friendly ( I 'm a complete amateur ) , and do n't seem to take into account being passed variables.So the questions are : Is there an easier/simpler way of achieving what I 'm trying to do ? If 1=false ( I 'm guessing that 's the case ) , is it worth the effort of all the potential problems of this approach , or would my time be better spent writing an automatic update feature into the application and just keeping it all inside the main app ( so the user would just have to let the app update itself once a week ) ? Another ( probably bad ) idea I had was shifting all the autospec code out to a separate DLL , and either just redeploying that when necessary , or is it even possible to reference a single DLL on a shared network drive ? I guess this is some pretty dangerous territory whichever way I go . Can someone tell me if I 'm opening a can of worms best left well and truly shut ? Is there a better way of going about this whole thing ? I have a habit of overcomplicating things that I 'm trying to kick : PJust as additional info , the autospec code will not be user-input . It 'll be me updating it every week ( no-one else has access to it ) , so hopefully that will mitigate some security concerns at least.Apologies if I 've explained this badly.Thanks in advance <code> [ some code to get the following items from the list here ] if ( Item0002.Value + Item0003.Value > Item0004.Value ) { return Item0002.Value } else { return Item0004.Value }
c # executing a string as code ... is it worth the effort ?
C_sharp : I have a C # application that calls : It is set to target x86 , and when I run it I can see from Task Manager that it is a 32-bit process . However that line of code is strangely going to the 64-bit hive at HKCU\Software\MyApp , instead of the 32-bit hive at HKCU\Software\Wow6432Node\MyApp . Any ideas ? I also started two instances of Powershell , one 32-bit and one 64-bit , and ran the below but both return the values at the 64-bit hive too.Any ideas what might have gone wrong here ? I have triple-checked that the registry settings at the 32 and 64 bit hives are different from regedit too . <code> Microsoft.Win32.Registry.CurrentUser.OpenSubKey ( @ '' Software\MyApp '' ) get-itemproperty -Path Registry : :HKEY_CURRENT_USER\Software\MyApp
Why does my 32-bit application not access the 32-bit registry hive ?
C_sharp : I have the following regex : I 'm using it to find matches within a string : This used to yield the results I wanted ; however , my goal has since changed . This is the desired behavior now : Suppose the string entered is 'stuff/ { thing : aa/bb/cccc } { thing : cccc } ' I want formatTokens to be : Right now , this is what I get : Note especially that `` cccc '' does not appear twice even though it was entered twice.I think the problems are 1 ) the recapture in the regex and 2 ) the concat configuration ( which is from when I wanted everything separated ) , but so far I have n't been able to find a combination that yields what I want . Can someone shed some light on the proper regex/concat combination to yield the desired results above ? <code> @ '' { thing : ( ? : ( ( \w ) \2* ) ( [ ^ } ] * ? ) ) + } '' MatchCollection matches = regex.Matches ( string ) ; IEnumerable formatTokens = matches [ 0 ] .Groups [ 3 ] .Captures .OfType < Capture > ( ) .Where ( i = > i.Length > 0 ) .Select ( i = > i.Value ) .Concat ( matches [ 0 ] .Groups [ 1 ] .Captures.OfType < Capture > ( ) .Select ( i = > i.Value ) ) ; formatTokens [ 0 ] == `` aa/bb/cccc '' formatTokens [ 1 ] == `` cccc '' formatTokens [ 0 ] == `` / '' formatTokens [ 1 ] == `` / '' formatTokens [ 2 ] == `` cccc '' formatTokens [ 3 ] == `` bb '' formatTokens [ 4 ] == `` aa ''
Regex and proper capture using .matches .Concat in C #
C_sharp : I have some XMLs that represent permutation between for example , members of 4 sets ( A , B , C , D ) . Suppose that A= { A1 , A2 } , B= { B1 } , C= { C1 , C2 } and D= { D1 , D2 , D3 } but current XML is not normal because this members combined in non-regular way in each answer . `` set '' Attribute shows name of set and `` member '' shows each member of each set . This XML likes below : and I wan na to put each permutation in a specific answer . Each answer should be start with only one member of A and End with one member of D and use only one member of sets B and C between them.for example answer A1A2B1C1D2 should be separate to A1B1C1D2 , A2B1C1D2 and answer A1B1C1C2C3D1D3 should be separate to A1B1C1D1 , A1B1C1D3 , A1B1C2D1 , A1B1C2D3 , A1B1C3D1 and A1B1C3D3 final XML likes such as below XML : I hope that my question be clear and you can help me.Thanks <code> < root > < phrase permutation=ABCD > < ans number=1 > < word set=A member=A1/ > < word set=A member=A2/ > < word set=B member=B1/ > < word set=C member=C1/ > < word set=D member=D2/ > < /ans > < ans number=2 > < word set=A member=A1/ > < word set=B member=B1/ > < word set=C member=C1/ > < word set=C member=C2/ > < word set=C member=C3/ > < word set=D member=D1/ > < word set=D member=D3/ > < /ans > < /phrase > < /root > < root > < phrase permutation=ABCD > < ans number=1 > < word set=A member=A1/ > < word set=B member=B1/ > < word set=C member=C1/ > < word set=D member=D2/ > < /ans > < ans number=2 > < word set=A member=A2/ > < word set=B member=B1/ > < word set=C member=C1/ > < word set=D member=D2/ > < /ans > < ans number=3 > < word set=A member=A1/ > < word set=B member=B1/ > < word set=C member=C1/ > < word set=D member=D1/ > < /ans > < ans number=4 > < word set=A member=A1/ > < word set=B member=B1/ > < word set=C member=C1/ > < word set=D member=D3/ > < /ans > < ans number=5 > < word set=A member=A1/ > < word set=B member=B1/ > < word set=C member=C2/ > < word set=D member=D1/ > < /ans > < ans number=6 > < word set=A member=A1/ > < word set=B member=B1/ > < word set=C member=C2/ > < word set=D member=D3/ > < /ans > < ans number=7 > < word set=A member=A1/ > < word set=B member=B1/ > < word set=C member=C3/ > < word set=D member=D1/ > < /ans > < ans number=8 > < word set=A member=A1/ > < word set=B member=B1/ > < word set=C member=C3/ > < word set=D member=D3/ > < /ans > < /phrase > < /root >
XML Elements Normalizing
C_sharp : For serialization purpose , we are trying to generate the delegate to update some object property values on the fly and store them into a list for further use.Everything works quite well as long as we do not try to deserialize structs.We based our code on this article about open delegate : http : //codeblog.jonskeet.uk/2008/08/09/making-reflection-fly-and-exploring-delegates/And here is our code to deal with property setter in a class based object.As you have guessed , it does not work with struct.I found this post talking about how to deal with open delegate in struct : How can I create an open Delegate from a struct 's instance method ? ( Actually , I found way more post than this one , but this one has a `` simple '' solution which does not use IL code generation for example ... ) But , for now , everytime I try to bind a methodinfo of a property setter to a delegate using a ref parameter , I get an exception.Here is the current code I use : The problem appear when executing the following line : Which is , at least for me , really the same as the one used in the linked post above : Where : Anybody has an idea about why does it generate an exception on my side and not in the linked thread ? Is it linked to the C # runtime version ? I am working on unity so it 's a mono framework almost equivalent to 3.5 ... Anyway , thanks for reading and do not hesitate if I am doing something wrong in the question layout or syntaxe ! Cheers , flo . <code> private static System.Action < object , object > ToOpenActionDelegate < T , TParam > ( System.Reflection.MethodInfo methodInfo ) where T : class { System.Type parameterType = typeof ( TParam ) ; // Convert the slow MethodInfo into a fast , strongly typed , open delegate System.Action < T , TParam > action = ( System.Action < T , TParam > ) System.Delegate.CreateDelegate ( typeof ( System.Action < T , TParam > ) , methodInfo ) ; // Convert the strong typed delegate into some object delegate ! System.Action < object , object > ret = ( object target , object param ) = > action ( target as T , ( TParam ) System.Convert.ChangeType ( param , parameterType ) ) ; return ret ; } public delegate void RefAction < T , TParam > ( ref T arg , TParam param ) where T : class ; private static RefAction < object , object > ToOpenActionDelegate < T , TParam > ( System.Reflection.MethodInfo methodInfo ) where T : class { // Convert the slow MethodInfo into a fast , strongly typed , open delegate System.Type objectType = typeof ( T ) ; System.Type parameterType = typeof ( TParam ) ; RefAction < object , object > ret ; if ( objectType.IsValueType ) { RefAction < T , TParam > propertySetter = ( RefAction < T , TParam > ) System.Delegate.CreateDelegate ( typeof ( RefAction < T , TParam > ) , methodInfo ) ; // we are trying to set some struct internal value . ret = ( ref object target , object param ) = > { T boxed = ( T ) target ; propertySetter ( ref boxed , ( TParam ) System.Convert.ChangeType ( param , parameterType ) ) ; target = boxed ; } ; } else { System.Action < T , TParam > action = ( System.Action < T , TParam > ) System.Delegate.CreateDelegate ( typeof ( System.Action < T , TParam > ) , methodInfo ) ; ret = ( ref object target , object param ) = > action ( target as T , ( TParam ) System.Convert.ChangeType ( param , parameterType ) ) ; } return ret ; } RefAction < T , TParam > propertySetter = ( RefAction < T , TParam > ) System.Delegate.CreateDelegate ( typeof ( RefAction < T , TParam > ) , methodInfo ) ; SomeMethodHandler d = ( SomeMethodHandler ) Delegate.CreateDelegate ( typeof ( SomeMethodHandler ) , method ) ; delegate int SomeMethodHandler ( ref A instance ) ; public struct A { private int _Value ; public int Value { get { return _Value ; } set { _Value = value ; } } private int SomeMethod ( ) { return _Value ; } }
Using Open Delegate to access a struct property setter generate exception
C_sharp : I have an expression that I use a few times in several LINQ queries so I separated it out into it 's own method that returns the expression . The lambda portion of the function is kind of messy looking . Anyone want to take a crack at refactoring it and making it more readable and/or smaller ? A quick English description of what it 's doing is it is checking the boolean sent and checking either the Message.FromUser or the Message.ToUser based on that boolean.If the user is looking at his/her outbox , sent is true and it will see if x.FromUser.Username == username and x.SenderDeleted == false.If the user is looking at his/her inbox then it does the same logic , but sent is false and it checks x.ToUser and x.RecipientDeleted instead.Maybe this is the easiest way but I 'm open to some refactoring.ANSWER EDITI really liked Davy8 's answer but I decided to take a step further and do two expressions instead of one expression with a nested function . Now I have the following methods : So now my queries look like this : I would say those are some very English readable queries , thanks guys ! Reference : http : //www.codetunnel.com/blog/post/64/how-to-simplify-complex-linq-expressions <code> private Expression < Func < Message , bool > > UserSelector ( string username , bool sent ) { return x = > ( ( sent ? x.FromUser : x.ToUser ) .Username.ToLower ( ) == username.ToLower ( ) ) & & ( sent ? ! x.SenderDeleted : ! x.RecipientDeleted ) ; } /// < summary > /// Expression to determine if a message belongs to a user . /// < /summary > /// < param name= '' username '' > The name of the user. < /param > /// < param name= '' sent '' > True if retrieving sent messages. < /param > /// < returns > An expression to be used in a LINQ query. < /returns > private Expression < Func < Message , bool > > MessageBelongsToUser ( string username , bool sent ) { return x = > ( sent ? x.FromUser : x.ToUser ) .Username.Equals ( username , StringComparison.OrdinalIgnoreCase ) ; } /// < summary > /// Expression to determine if a message has been deleted by the user . /// < /summary > /// < param name= '' username '' > The name of the user. < /param > /// < param name= '' sent '' > True if retrieving sent messages. < /param > /// < returns > An expression to be used in a LINQ query. < /returns > private Expression < Func < Message , bool > > UserDidNotDeleteMessage ( string username , bool sent ) { return x = > sent ? ! x.SenderDeleted : ! x.RecipientDeleted ; } /// < summary > /// Retrieves a list of messages from the data context for a user . /// < /summary > /// < param name= '' username '' > The name of the user. < /param > /// < param name= '' page '' > The page number. < /param > /// < param name= '' itemsPerPage '' > The number of items to display per page. < /param > /// < param name= '' sent '' > True if retrieving sent messages. < /param > /// < returns > An enumerable list of messages. < /returns > public IEnumerable < Message > GetMessagesBy_Username ( string username , int page , int itemsPerPage , bool sent ) { var query = _dataContext.Messages .Where ( MessageBelongsToUser ( username , sent ) ) .Where ( UserDidNotDeleteMessage ( username , sent ) ) .OrderByDescending ( x = > x.SentDate ) .Skip ( itemsPerPage * ( page - 1 ) ) .Take ( itemsPerPage ) ; return query ; } /// < summary > /// Retrieves the total number of messages for the user . /// < /summary > /// < param name= '' username '' > The name of the user. < /param > /// < param name= '' sent '' > True if retrieving the number of messages sent. < /param > /// < returns > The total number of messages. < /returns > public int GetMessageCountBy_Username ( string username , bool sent ) { var query = _dataContext.Messages .Where ( MessageBelongsToUser ( username , sent ) ) .Where ( UserDidNotDeleteMessage ( username , sent ) ) .Count ( ) ; return query ; }
How might I clean up this lambda ?
C_sharp : I just answered a question about whether a Task can update the UI . As I played with my code , I realized I 'm not clear myself on a few things.If I have a windows form with one control txtHello on it , I 'm able to update the UI from a Task , it seems , if I immediately do it on Task.Run : However if I Thread.Sleep for even 5 milliseconds , the expected CrossThread error is thrown : I 'm not sure why that happens . Is there some sort of optimization for an extremely short running Task ? <code> public partial class Form1 : Form { public Form1 ( ) { InitializeComponent ( ) ; Task.Run ( ( ) = > { txtHello.Text = `` Hello '' ; } ) ; } } public partial class Form1 : Form { public Form1 ( ) { InitializeComponent ( ) ; Task.Run ( ( ) = > { Thread.Sleep ( 5 ) ; txtHello.Text = `` Hello '' ; //kaboom } ) ; } }
Background Task sometimes able to update UI ?
C_sharp : I am using DirectShowLib-2005 - DxSnap example to display and capture the image from Webcam.Everything works fine with the example.But when i try to merge it with my application ( i tried to call that form from my main form ) it is working for the first time . Once i close and open the capture window , it is not displaying the video properly.But the capturing of the image works perfectly all the time . Even after restarting the PC , its still the same.I have not changed anything in the DxSnap form . <code> public partial class frmMain : Form { public frmMain ( ) { InitializeComponent ( ) ; } /// < summary > /// The main entry point for the application . /// < /summary > [ STAThread ] private static void Main ( ) { Application.Run ( new frmMain ( ) ) ; } private void button1_Click ( object sender , EventArgs e ) { frmdxSnap frmdxSnap = new frmdxSnap ( ) ; frmdxSnap.ShowDialog ( this ) ; } }
Dxsnap not displaying the video properly after first time open
C_sharp : I 'm ( now ) trying to use ANTLR4 and C # to design a language , and so far I 've been fiddling around with it . In the process , I decided to try and create a simple mathematical expression evaluator . In the process , I created the following ANTLR grammar for it : When I try to generate C # code from it using this command : I get these odd errors : What might be causing these errors , and how can I fix them ? My best guess at the moment is that Visual Studio is inserting odd characters onto the beginning of the file , and I ca n't remove them . <code> grammar Calculator ; @ parser : :members { protected const int EOF = Eof ; } @ lexer : :members { protected const int EOF = EOF ; protected const int HIDDEN = Hidden ; } program : expr+ ; expr : expr op= ( '* ' | '/ ' ) expr | expr op= ( '+ ' | '- ' ) expr | INT | ' ( ' expression ' ) ' ; INT : [ 0-9 ] + ; MUL : '* ' ; DIV : '/ ' ; ADD : '+ ' ; SUB : '- ' ; WS : ( ' ' | '\r ' | '\n ' ) - > channel ( HIDDEN ) ; java -jar C : \ ... \antlr-4.2-complete.jar -DLanguage=CSharp .\ ... \Grammar.g4 error ( 50 ) : C : \Users\Ethan\Documents\Visual Studio 2015\Projects\CypressLang\CypressLang\Source\.\Grammar\CypressGrammar.g4:1:0 : syntax error : ' ï ' came as a complete surprise to me error ( 50 ) : C : \Users\Ethan\Documents\Visual Studio 2015\Projects\CypressLang\CypressLang\Source\.\Grammar\CypressGrammar.g4:1:1 : syntax error : ' » ' came as a complete surprise to me error ( 50 ) : C : \Users\Ethan\Documents\Visual Studio 2015\Projects\CypressLang\CypressLang\Source\.\Grammar\CypressGrammar.g4:1:2 : syntax error : '¿ ' came as a complete surprise to me error ( 50 ) : C : \Users\Ethan\Documents\Visual Studio 2015\Projects\CypressLang\CypressLang\Source\.\Grammar\CypressGrammar.g4:1:3 : syntax error : mismatched input 'grammar ' expecting SEMI
What are these odd errors that occur when I attempt to generate C # with ANTLR4 ?
C_sharp : Usually , I like the challenges of regular expressions and even better - solving them.But it seems I have a case that I ca n't figure out.I have a string of values that are separated by a semi-colon like CSV line that can look like this one:123-234 ; FOO-456 ; 45-67 ; FOO-FOO ; 890 ; FOO-123 ; 11-22 ; 123 ; 123 ; 44-55 ; 098-567 ; 890 ; 123-FOO ; In this line I would like to match all integers and integer ranges in order to extract them later . It is possible that only single value ( no semi-colon ) .After a lot of searching I managed to write this expression : ( ? : ^| ; ) ( ? < range > \d+-\d+ ) ( ? : $ | ; ) | ( ? : ^| ; ) ( ? < integer > \d+ ) ( ? : $ | ; ) The test strings I 'm using:123123-234 ; FOO-456 ; 45-67 ; FOO-FOO ; 890 ; FOO-123 ; 11-22 ; 123 ; 123 ; 44-55 ; 098-567 ; 890 ; 123-FOO ; 123-456123-FOOFOO-123FOO-FOOLines 1 and 3 are correctly matched , and lines 4,5 6 are not.In line 2 , only one value of two is correctly matched.Here is a link to regex101.com that illustrates it : https : //regex101.com/r/zA7uI9/5I would also need to select integers and the ranges separately ( in different groups ) . Note : I found a question that could help me and tried its answer ( by adapting it ) but it did n't work . Regular expression for matching numbers and ranges of numbersHave you got any idea on what I 'm missing ? The language that will `` use '' this regex is C # , but I do n't know if it 's a useful information for my problem.added by barlopHere are the matches the current regex gives him , as shown by that regex101.com linkand for this test string of his 123-234 ; FOO-456 ; 45-67 ; FOO-FOO ; 890 ; FOO-123 ; 11-22 ; 123 ; 123 ; 44-55 ; 098-567 ; 89 so his regex seems to be missing out one of the 123s , and the 44-45 , and the 89 at the end . <code> 123-23445-6789011-22123098-567
How to match both numbers and range of numbers in a CSV-like string with regex ?
C_sharp : I am a developer who works primarily with embedded devices ( programmed with C and assembly ) . My C # and OOP knowledge is very limited ( although I can fake my way through it when necessary ) . I have five devices that interface with a PC via USB . The PC does some calculations and sends a result to the device . The same calculations are performed for each device , but the calculations are done differently . For each device , I have a C # Windows Forms application that does some work and sends data back and forth to the device . Currently , I 'm trying to get the five different applications merged into one so we can easily make changes , add new devices easily , and have a standard user interface . My problem is that I do n't exactly know the best way to do it since I do n't know which device will be used until run time . I 'm trying to avoid a bunch of if statements and I would like to be able to put each device in a separate file . Here is some psudo-code of what I 'm talking about.I 'm not really sure , but I 'm thinking I could use an interface or maybe inherit the Device1 class for the Device class and override the methods ... But I do n't know how I would have one generic way of saying CurrentDevice.DoWork1 ( ) since CurrentDevice could be Device1 or Device2.Any ideas would be greatly appreciated . I 'm using Visual Studio 2008 with .NET 3.5 on Windows XP SP3 and Windows 7.I hope I described the problem well enough . If not , or if I did n't mention something that I should , please let me know . I 'm new to stackoverflow and C # .Thank you , Michael <code> class Device //This is what EVERY device can do { ... DoWork1 ( ) ; DoWork2 ( ) ; DoWork3 ( ) ; ... } class Device1 { ... DoWork1 ( ) ; //This is how the work is done for this deviceDoWork2 ( ) ; DoWork3 ( ) ; ... } class Device2 { ... DoWork1 ( ) ; //This is how the work is done for this device ( not the same way as Device1 ) DoWork2 ( ) ; DoWork3 ( ) ; } public partial class frmMain : Form { private ( some kind of object or something ) CurrentDevice ; public frmMain ( ) { ... //Determine what device ( could be one of five ) is currently being usedCurrentDevice = ( which device is currently being used ) //Could be CurrentDevice = new Device1 ( ) ; } } private void Button1_Click ( ) { CurrentDevice.DoWork1 ( ) ; //But this could be Device1.DoWork1 ( ) or Device2.DoWork1 ( ) , depending on what device is currently being used ( which was determined in the frmMain constructor ) }
How would one implement many classes that have the same methods that do things different ?
C_sharp : C # 2008 SP1I have created an updater for our clients application . The way the updater works is to download all the updated files and store them in a temporary folder then check the file hashes . If everything is ok it will copy the files to the applications installation folder . Once this is been completed it will delete all the updated files in the temporary directory.My problem : I am looking for a directory that will be available for XP , Vista , and Win7 . I was thinking about the 'temp ' directory . However , when I do this : There is no enum for temp directory . What would be the next best thing to store these temporary files ? Many thanks for any advice , <code> Environment.SpecialFolder .
How do I get a path suitable for storing temporary files ?
C_sharp : I have a class that instantiates two classes which implement interfaces . I want one class to notify another class that something is OK . I could do it with an Action and then use private variables in the class but wondered if there was a direct way of doing it with properties so that when a property 's value changes it updates a property on another class.For example : <code> public class MyClass { public ILogger Logger { get ; set ; } public ILogic Logic { get ; set ; } private Form MyWinform ; public void Setup ( ) { MyWinform = new MyWinform ( ) ; MyWinform.StartBatch += Logger.CreateFile ; //Create file when user presses start //How can I set a property on ILogic to be AllOk once ILogger says so ? ? //I could use an Action so that once all is ok I call IDecidedAlOK in ILogger which //can then assign a private bool variable inside the class Logic.ItsOKMethodSoSetVariableToTrue = Logger.IDecidedAllOKMethod ; } public void DataIn ( string Value ) { Logic.DataIn ( Value ) ; } public void CreateInstances ( ) { Logger = new FileLogger ( ) ; Logic = new MyLogic ( ) ; } } public class MyLogic : ILogic { public void DataIn ( string Value ) { //I want to check that all is ok before I do anything //if ( ! AllOK ) //return ; //Do stuff } }
Action < T > equivalent for properties
C_sharp : I am trying to write an extension method that checks if an object is sub class of T.Here is what I did , but not accepted by visual studio.Any idea how can i write this ? <code> public static bool IsChildOf < T > ( this object obj ) { return ( typeof ( obj ) .IsSubclassOf ( typeof ( T ) ) ) ; } [ Test ( ) ] public void IsChildOfTest ( ) { var dog = new Dog ( ) ; var isAnimal = dog.IsChildOf < Animal > ( ) ; Assert.That ( isAnimal ) ; }
Extension method to check if an object is sub class of T
C_sharp : Question 1 > Should I check NULL in the following case ? Question 2 > I just start to transfer to C # from C++.When coding in C++ , I know when the checking should be done.However , I am totally lost in the C # world . So the question is : is therea general rule that can tell me when I MUST check for NULL ? Thank you <code> public interface INewClass { } public class NewClass : INewClass { } public void FunMeA ( INewClass obj ) { NewClass n = ( NewClass ) obj ; ... // Should I check ( n == null ) here ? // call methods defined inside INewClass ( updated from NewClass to INewClass ) ... } A concrete example , public void FunMeB ( IAsyncResult itfAR ) { AsyncResult ar = ( AsyncResult ) itfAR ; ... // Should I check ( ar == null ) here ? // access ar.AsyncDelegate ... }
Should we check NULL when cast IClass to Class ?
C_sharp : I have the enum structure as follows : Now I want to get a list of MyEnum , i.e. , List < MyEnum > that contains all the One , Two Three . Again , I am looking for a one liner that does the thing . I came out with a LINQ query but it was unsatisfactory because it was a bit too long , I think : A better suggestion ? <code> public enum MyEnum { One=1 , Two=2 , Three=3 } Enum.GetNames ( typeof ( MyEnum ) ) .Select ( exEnum = > ( MyEnum ) Enum.Parse ( typeof ( MyEnum ) , exEnum ) ) .ToList ( ) ;
Get a List of available Enums
C_sharp : I have two classes.Class A : And Class B : They do n't share the same interface or abstract class.A and B have two distinct hierarcy and I ca n't change that at the moment.I want to write a single procedute that works for A and B and use QQ and WW methods.Can I do that ? Can you suggest any document I can study ? Tanks <code> class A ( ) { public void QQ ( ) { } public void WW ( ) { } } class B ( ) { public void QQ ( ) { } public void WW ( ) { } }
two class with common methods and properties
C_sharp : In one sentence , what i ultimately need to know is how to share objects between mid-tier functions w/ out requiring the application tier to to pass the data model objects.I 'm working on building a mid-tier layer in our current environment for the company I am working for . Currently we are using primarily .NET for programming and have built custom data models around all of our various database systems ( ranging from Oracle , OpenLDAP , MSSQL , and others ) .I 'm running into issues trying to pull our model from the application tier and move it into a series of mid-tier libraries . The main issue I 'm running into is that the application tier has the ability to hang on to a cached object throughout the duration of a process and make updates based on the cached data , but the Mid-Tier operations do not.I 'm trying to keep the model objects out of the application as much as possible so that when we make a change to the underlying database structure , we can edit and redeploy the mid-tier easily and multiple applications will not need to be rebuilt . I 'll give a brief update of what the issue is in pseudo-code , since that is what us developers understand best : ) On a side note , options I 've considered are building a home grown caching layer , which takes a lot of time and is a very difficult concept to sell to management . Use a different modeling layer that has built in caching support such as nHibernate : This would also be hard to sell to management , because this option would also take a very long time tear apart our entire custom model and replace it w/ a third party solution . Additionally , not a lot of vendors support our large array of databases . For example , .NET has LINQ to ActiveDirectory , but not a LINQ to OpenLDAP.Anyway , sorry for the novel , but it 's a more of an enterprise architecture type question , and not a simple code question such as 'How do I get the current date and time in .NET ? 'EditSorry , I forgot to add some very important information in my original post . I feel very bad because Cheeso went through a lot of trouble to write a very in depth response which would have fixed my issue were there not more to the problem ( which I stupidly did not include ) .The main reason I 'm facing the current issue is in concern to data replication . The first function makes a write to one server and then the next function makes a read from another server which has not received the replicated data yet . So essentially , my code is faster than the data replication process.I could resolve this by always reading and writing to the same LDAP server , but my admins would probably murder me for that . The specifically set up a server that is only used for writing and then 4 other servers , behind a load balancer , that are only used for reading . I 'm in no way an LDAP administrator , so I 'm not aware if that is standard procedure . <code> main { MidTierServices.UpdateCustomerName ( `` testaccount '' , `` John '' , `` Smith '' ) ; // since the data takes up to 4 seconds to be replicated from // write server to read server , the function below is going to // grab old data that does not contain the first name and last // name update ... . John Smith will be overwritten w/ previous // data MidTierServices.UpdateCustomerPassword ( `` testaccount '' , `` jfjfjkeijfej '' ) ; } MidTierServices { void UpdateCustomerName ( string username , string first , string last ) { Customer custObj = DataRepository.GetCustomer ( username ) ; /******************* validation checks and business logic go here ... *******************/ custObj.FirstName = first ; custObj.LastName = last ; DataRepository.Update ( custObj ) ; } void UpdateCustomerPassword ( string username , string password ) { // does not contain first and last updates Customer custObj = DataRepository.GetCustomer ( username ) ; /******************* validation checks and business logic go here ... *******************/ custObj.Password = password ; // overwrites changes made by other functions since data is stale DataRepository.Update ( custObj ) ; } }
Mid-Tier Help Needed
C_sharp : While I 'm working on parallelism of our framework , I 've confronted a strange condition which I ca n't imagine why ! I simplified the situation to describe it easy.consider this code : which the personList is shared between multiple threads.In what circumstances is it possible for person to be null and I get the NullReferenceException for person.Name ? As I know , the person is considered as a local variable here and if the we get into the foreach block , so we have iterated the personList successfully , so person should not be null in any circumstances or any parallel scenario.Even if the personList is changed by another thread , or the referenced person is disposed , the person variable should have a value . Because no one has access to change where the person is referenced to.Is it any scenario to explain the situation ? <code> foreach ( var person in personList ) { if ( person.Name == `` Mehran '' ) break ; }
Modification of a local variable to null , via another thread , how is that possible
C_sharp : I use recursive function to do somethingSo , I want that tbOut.Text = `` Done ! `` ; will be done only after all iterations ends . At now it 's happenning at the same time while iterations under process . If I run this function like thatthe result still the same . How to wait when this function will ends completely ? <code> public async void walk ( StorageFolder folder ) { IReadOnlyList < StorageFolder > subDirs = null ; subDirs = await folder.GetFoldersAsync ( ) ; foreach ( var subDir in subDirs ) { var dirPath = new Profile ( ) { FolderPath = subDir.Path } ; db.Insert ( dirPath ) ; walk ( subDir ) ; } tbOut.Text = `` Done ! `` ; } walk ( fd ) ; tbOut.Text = `` Done ! `` ;
How to wait all asynchronous operations ?
C_sharp : I am not exactly sure how to make this question readable/understandable , but hear my out and I hope you will understand my issue when we get to the end ( at the very least , it is easily reproduceable ) .I try to call a method used for validating results in UnitTests . It has the following signature : What this means is , that it takes the following inputAny object that is enumerable , and contains objects of the same Type as the intput for 2 ) .A Func ( usually encapsulating lambda expressions ) that takes an object of the same Type as the `` contents '' of 1 ) and returns an object of the same Type as the Type of the contents of the array provided in 3 ) .An array of objects of the same Type as that of the output of the Func in 2 ) .So , an actual execution of this method could look like this : At least , that is how I would like it to look like , but I run into the well known compiler error : `` The type arguments for the method ' X ' can not be inferred from the usage . `` , and that is what I do not understand . It should have all the info needed as far as I can see , or perhaps it is another version of the `` Covariance and Contravariance '' problem ? So for now I am forced to do it like this instead : Can anyone point out why this scenario can not be inferred by the compiler ? <code> void AssertPropertyValues < TEnumerable , TElement , TProperty > ( TEnumerable enumerable , Func < TElement , TProperty > propertyPointer , params TProperty [ ] expectedValues ) where TEnumerable : System.Collections.Generic.IList < TElement > AssertPropertyValues ( item.ItemGroups , itemGroup = > itemGroup.Name , `` Name1 '' , `` Name2 '' , `` Name3 '' ) ; AssertPropertyValues ( item.ItemGroups , ( ItemGroup itemGroup ) = > itemGroup.Name , `` Name1 '' , `` Name2 '' , `` Name3 '' ) ;
Why does method type inference fail to infer a type parameter ?
C_sharp : I am creating my first ASP.NET MVC project . I have started with connecting TFS and adding bugs in to TFS via C # .This code shown above works fine . But is it possible to achieve same result using a SQL Server stored procedure ? Is there any way to connect to TFS and add bug in to TFS using a stored procedure ? I have my database and from sql stored procedure I wanted to connect to TFS and create WorkItem . Via C # I have done as seen above example . But I need any example if same thing can be achieved from a stored procedure . <code> var tfsURI = new Uri ( `` http : //test:8080/tfs '' ) ; var networkCredential1 = new NetworkCredential ( `` test '' , `` test ! `` ) ; ICredentials credential = ( ICredentials ) networkCredential1 ; Microsoft.VisualStudio.Services.Common.WindowsCredential winCred = new Microsoft.VisualStudio.Services.Common.WindowsCredential ( credential ) ; VssCredentials vssCredentials = new VssCredentials ( winCred ) ; using ( TfsTeamProjectCollection collection = new TfsTeamProjectCollection ( tfsURI , vssCredentials ) ) { collection.EnsureAuthenticated ( ) ; WorkItemStore workItemStore = collection.GetService < WorkItemStore > ( ) ; Project teamProject = workItemStore.Projects [ `` Test '' ] ; WorkItemType workItemType = teamProject.WorkItemTypes [ `` Bug '' ] ; WorkItem Defect = new WorkItem ( workItemType ) ; FileInfo fi = new FileInfo ( @ '' C : \\Document.docx '' ) ; Attachment tfsAttachment = new Attachment ( fi.FullName ) ; Defect.Attachments.Add ( tfsAttachment ) ; Defect.Title = `` Testing from VS to TFS Bug '' ; Defect.Description = `` Testing from VS to entered Bug in to TFS . `` ; Defect.Fields [ `` Assigned To '' ] .Value = `` Test '' ; Defect.Save ( ) ; }
Calling Team Foundation Server ( TFS ) APIs via SQL Server stored procedure
C_sharp : I 'm working with some legacy code right now which usually used try + catch in combination with Convert.ToDecimal ( someString ) ( for instance ) to try and convert strings to decimals . For some reasons I have to use the setting that - when debugging - I stop at every thrown exception ( not only user-unhandled ones ) and so this got annoying and I changed it to use TryParse methods whenever possible.Now I 'm in a situation where there 's an object value and a target Type , and all I want to know is if I can convert the value into the target type . Right now this is done as follows : The actual result is not important and is not used further.While this code is working right now , as I said , it gets a bit annoying and so I wonder : Is there another way of doing the above without having to catch an exception ? I thought of something like IsAssignableFrom on a Type , but this does n't seem to be applicable in my case ( I do n't want to assign , I want to know if explicitly converting is possible ) . <code> try { Convert.ChangeType ( val , targetType ) ; } catch { // Do something else }
More elegant way of finding out if I can convert a value into a certain type
C_sharp : In the following method , Does the use of const provide any benefit over just declaring the string as a string ? Woudl it not be interned anyway ? <code> public void InspectList ( IList < int > values ) { if ( values ! = null ) { const string format = `` Element At { 0 } '' ; foreach ( int i in values ) { Log ( string.Format ( format , i ) ) ; } } }
Use of const in a method
C_sharp : I am developing a website in which I 'm using forms authentication.We have 2 log in pages : one for user , another for admin.I added this code into webconfig file for user.I am using this code for user side when user successfully logged in.I am not using the default user membership database . I have my own database in SQL Server 2005.I want same thing for admin , but the default url is Admin.aspx & login url is adminlogin.aspx for admin.How can i assign in web config file for admin ? Is it the right way to do that or any one have some better concept for that ? <code> < forms loginUrl= '' Login.aspx '' defaultUrl= '' Home.aspx '' > FormsAuthentication.RedirectFromLoginPage ( UserName.Text , chkPersistCookie.Checked )
Forms Authentication for different roles ?
C_sharp : I have multiple projects in my solution , all .NET Core 3.1 . One of them is my core project ( “ A Project ” ) where I just have basic model classes with no methods or database access . For demonstration purposes , below are simplified versions of my Address.cs and User.cs files : In another project ( “ B Project ” ) , I will be building the actual functionality . This project already has ASP.NET Core Identity setup with an ApplicationUser class , which derives from IdentityUser and adds some custom properties . This is where I run into my problem . The Address.User property has to be set to an instance of ApplicationUser , but ApplicationUser lives in the B Project.Obviously , I do n't have ASP.NET Core Identity set up as a dependency within my A Project , so I ca n't move the ApplicationUser class into that project . Further , I can not assign the ApplicationUser to the Address.User property since ApplicationUser doesn ’ t derive from User.Having done some research , I found a couple of different suggestions . One proposal is to use a separate project for the ASP.NET Core Identity components and then reference it alongside my A Project from within my B Project . Another soul suggested creating my own UserStore . I do n't want my A Project to be dependent upon anything . But I don ’ t have enough experience to decide what option is preferable for my scenario . <code> public class Address { public int Id { get ; set ; } public string AddressText { get ; set ; } public virtual User User { get ; set ; } } public class User { public int UserId { get ; set ; } public int UserName { get ; set ; } public ICollection < Address > { get ; set ; } }
Inherit ( ? ) IdentityUser from another project
C_sharp : The following C # function : compiles unsurprisingly to this : But the equivalent F # function : compiles to this : ( Both are in release mode ) . There 's an extra nop at the beginning which I 'm not too curious about , but the interesting thing is the extra ldnull and tail . instructions.My guess ( probably wrong ) is that ldnull is necessary in case the function is void so it still returns something ( unit ) , but that does n't explain what is the purpose of the tail . instruction . And what happens if the function does push something on the stack , is n't it stuck with an extra null that does n't get popped ? <code> T ResultOfFunc < T > ( Func < T > f ) { return f ( ) ; } IL_0000 : ldarg.1 IL_0001 : callvirt 05 00 00 0A IL_0006 : ret let resultOfFunc func = func ( ) IL_0000 : nop IL_0001 : ldarg.0 IL_0002 : ldnull IL_0003 : tail . IL_0005 : callvirt 04 00 00 0A IL_000A : ret
What is the purpose of the extra ldnull and tail . in F # implementation vs C # ?
C_sharp : Can you clarify me why in this piece of code : I get the error : `` Only assignment , call , increment , decrement , and new object expressions can be used as a statement . `` IView defines the ShowDialog ( ) method . <code> private Dictionary < Type , Type > viewTypeMap = new Dictionary < Type , Type > ( ) ; public void ShowView < TView > ( ViewModelBase viewModel , bool showDialog = false ) where TView : IView { var view = Activator.CreateInstance ( viewTypeMap [ typeof ( TView ) ] ) ; ( IView ) view.ShowDialog ( ) ; }
Can not perform explicit cast
C_sharp : My Project : Web API project - ASP .NET Framework 4.8Problem ? The code flow is as follows:1 . ) The API is called - > it must call another API - > 2 . ) Get JWT authentication token - > 3 . ) Calls the desired method.The problem is if my API is called 100 times , I will make 100 calls for the GetJwtToken ( ) method and another 100 for the desired method itself , which seems like an overhead on the auth server . The token itself has a lifespan of 2 hours.Are there any documented best practices on how to manage a Web API JWT token in another Web API ? What have I tried ? I 've tried the following solutions and I 'm still not sure whether they could be considered good practices.One static class with two static properties Token and ValidTo and one static method GetJwtToken ( ) that updates those properties . Before each call to the desired external API method , we check the ValidTo property and update the Token value if it has expired , via the static method.In our service , we have one static private field Token.The method that calls the external API method is surrounded by a try catch blocks . The Catch ( WebException ex ) expects an Unauthorized exception if the token has expired . I check for HTTP Status Code 401 - Unauthorized.In case we go into that if clause we update the Token property by calling the GetJwtToken ( ) method inside the catch block and then calling recursively the method again . In this way , we update the token only when it has expired and an unauthorized exception was thrown.Another idea that I got , but did n't test isActionFilterAttribute with overridden OnActionExecuting ( HttpActionContext actionContext ) method . Before we go into the Web API controller the action attribute has already checked whether we have Token and if it has expired . The problem here was I am not sure where to save the Token property . Possibly as a static value in another class.Are there any other ways to manage a JWT Token of a Web API inside another Web API and what is considered best practices ? Some code snippets , pseudo-code , or articles would be appreciated.Edit1 : I 've read this question , but it does n't help me , since it 's about how to manage the token on the front end part . The project here is Web API it 's all on the server-side.Edit2 : Edited some sentences here and there so it 's more readable.Edit3 : Added one more option that I thought about . <code> if ( response.StatusCode == HttpStatusCode.Unauthorized )
Best practices for managing Web API JWT token in another Web API
C_sharp : I 'm using Visual Studio 2010 SP1 , Target framework is 2.0 , Platform target : Any CPU , testing under Windows 7 x64 SP1.I 'm experiencing strange performance behavior.Without an app.config , or with the following app.config , it makes my program run slowly ( Stopwatch shows ~0.11 s ) The following app.config makes my program run x5 times faster ( Stopwatch shows ~0.02 s ) This is the test program code : I 'm sitting for hours and ca n't figure out what is happening here.Have you any idea ? <code> < ? xml version= '' 1.0 '' ? > < configuration > < startup > < supportedRuntime version= '' v2.0.50727 '' / > < /startup > < /configuration > < ? xml version= '' 1.0 '' ? > < configuration > < startup > < supportedRuntime version= '' v4.0.30319 '' sku= '' .NETFramework , Version=v4.0 '' / > < /startup > < /configuration > using System ; using System.Collections.Generic ; using System.Text ; using System.Diagnostics ; class Program { static void Main ( string [ ] args ) { Stopwatch sw = new Stopwatch ( ) ; while ( true ) { sw.Reset ( ) ; sw.Start ( ) ; for ( int i = 0 ; i < 1000000 ; i++ ) { `` blablabla '' .IndexOf ( `` ngrhotbegmhroes '' , StringComparison.OrdinalIgnoreCase ) ; } Console.WriteLine ( sw.Elapsed ) ; } } }
Strange performance behavior
C_sharp : I 'm trying to build a framework that allows people to extend our core functionality by implementing an interface . Below is a dumbed down example of this interface.Recently , we 've decided to modify this interface ( I know I should n't break dependent code , but the truth is we do n't have any 3rd parties implementing this interface yet , so we have a chance for a `` do-over '' to implement this interface correctly ) .We need to add 2 more parameters to this interface for our software to work correctly . Two ways we 're thinking of are just adding them to the signature like this : or by creating a parameter object like thisand adding them to the end of the method like so : I 'm looking for some sort of guidance on which way is the `` most '' correct way to proceed . I can see pros and cons in both categories , but I do n't want my biases to lead me down the wrong path.Some of my main concerns are : Extensibility of the software - I want the user to be able to do things I have n't thought of yet by implementing the interfaceMaintainability - Ideally , I 'd like to never have to touch the code that is responsible for calling GetData ( ) againClean API - I do n't want the solution I arrive at to make a 3rd party developer cringe I do n't even know what question to ask online to get guidance for this issue . I have a feeling that the answer is `` it depends '' ( on things like how related p1-p5 are to the purpose of the GetData ( ) function ) , but can someone point me to a list of questions I should ask to help me evaluate whether one solution is better than the other ? Related : Post 1Post 2 <code> public interface MyInterface { IData GetData ( string p1 , char p2 , double p3 ) ; } public interface MyInterface { IData GetData ( string p1 , char p2 , double p3 , bool p4 , DateTime p5 ) ; } public class MyParameters { public bool p4 { get ; set ; } public DateTime p5 { get ; set ; } } public interface MyInterface { IData GetData ( string p1 , char p2 , double p3 , MyParameters p4 ) ; }
Method Parameters vs Parameter Object
C_sharp : Is there a different way to do what I want to do here ? If there 's not , I do n't really see all that much point in implicit types ... <code> var x = new { a = `` foobar '' , b = 42 } ; List < x.GetType ( ) > y ;
Why ca n't I do this with implicit types in C # ?
C_sharp : I have my code which makes a webservice Call based on type of request . To do that , I have following code ; So as per open close principle , I can subclass like : Now my client class will look something like this : Now , I still have to use if and else , and will have to change my code if there are any new request type.So , it 's definitely , not closed to modification.Am I missing any thing with respect to SOLID ? Can I use dependency injection , to resolve the types at Run time ? <code> public class Client { IRequest request ; public Client ( string requestType ) { request = new EnrolmentRequest ( ) ; if ( requestType == `` Enrol '' ) { request.DoEnrolment ( ) ; } else if ( requestType == `` ReEnrol '' ) { request.DoReEnrolment ( ) ; } else if ( requestType == `` DeleteEnrolment '' ) { request.DeleteEnrolment ( ) ; } else if ( requestType == `` UpdateEnrolment '' ) { request.UpdateEnrolment ( ) ; } } } Class EnrolmentRequest : IRequest { CallService ( ) ; } Class ReEnrolmentRequest : IRequest { CallService ( ) ; } Class UpdateEnrolmentRequest : IRequest { CallService ( ) ; } public class Client { public Client ( string requestType ) { IRequest request ; if ( requestType == `` Enrol '' ) { request = new EnrolmentRequest ( ) ; request.CallService ( ) ; } else if ( requestType == `` ReEnrol '' ) { request = new REnrolmentRequest ( ) ; request.CallService ( ) ; } else if ( requestType == `` DeleteEnrolment '' ) { request = new UpdateEnrolmentRequest ( ) ; request.CallService ( ) ; } else if ( requestType == `` UpdateEnrolment '' ) { request = new UpdateEnrolmentRequest ( ) ; request.CallService ( ) ; } } }
How to resolve type at run time to avoid multipe if else
C_sharp : Just i have a bit of confusion in understanding static reference.incase of instance reference we can understand when i declare What if the case of Static class ? can i mean it when i declareUpdate : Since class is blueprint and objects are physical entities ; Incase of static class when i declare staticClass.MyMethod or staticClass.MyField = value , am i directly interacting with heap ? ( As no instance is allowed for static class ) . <code> Car myCar = new Car ( ) ; Car yourCar = new Car ( ) ; -- -- -- -- -- -- -- - -- -- -- -- -- -- -- stack Managed Heap -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -myCar -- -- -- - > points to Car -- -- -YourCar -- -- -- - > points to Car -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - staticClass.MyMethod ( ) -- -- -- -- -- -- -- -- -Managed Heap -- -- -- -- -- -- -- -- staticClass ( Memory Address ) -- -- -- -- -- -- -- -- -
C # - Static class call means `` content at address ? ``
C_sharp : In an Interview , Interviewer asked to me.. thatI have a code which written in side the try and catch block likesuppose we got an error on code line 3then this will not go in the catch blockbut If I got error on any other line except line 3 it go in catch blockis this possible that if error occur on a particular line then it is not go in the catch block ? <code> try { //code line 1 //code line 2 //code line3 -- if error occur on this line then did not go in the catch block //code line 4 //code line 5 } catch ( ) { throw }
On Error catch block did not call
C_sharp : This question is about when you do and do n't need to include generic type specification arguments . It 's a bit lengthy , so please bear with it.If you have the following ( contrived ) classes ... The following method ... Can be called with or without having to specify the type argument TUser ... So far , so good.But if you add a couple more ( again , contrived ) classes ... And a method ... When calling this method , it is mandatory to include the type arguments ... If you do n't specify the type arguments , you will get a compiler error of The type arguments for method 'DoThingsWithUserDisplay ( TDisplay ) ' can not be inferred from the usage . Try specifying the type arguments explicitly.I think that the compiler should/could be smart enough to figure this out ... or is there a subtle reason why not ? <code> public abstract class UserBase { public void DoSomethingWithUser ( ) { } } public class FirstTimeUser : UserBase { /* TODO : some implementation */ } private static void DoThingsWithUser < TUser > ( TUser user ) where TUser : UserBase { user.DoSomethingWithUser ( ) ; } var user = new FirstTimeUser ( ) ; DoThingsWithUser < FirstTimeUser > ( user ) ; DoThingsWithUser ( user ) ; // also valid , and less typing required ! public abstract class UserDisplayBase < T > where T : UserBase { public T User { get ; protected set ; } } public class FirstTimeUserDisplay : UserDisplayBase < FirstTimeUser > { public FirstTimeUserDisplay ( ) { User = new FirstTimeUser ( ) ; } } private static void DoThingsWithUserDisplay < TDisplay , TUser > ( TDisplay userDisplay ) where TDisplay : UserDisplayBase < TUser > where TUser : UserBase { userDisplay.User.DoSomethingWithUser ( ) ; } var userDisplay = new FirstTimeUserDisplay ( ) ; DoThingsWithUserDisplay < FirstTimeUserDisplay , FirstTimeUser > ( userDisplay ) ; // Type arguments required !
Generic type specification arguments - sometimes optional , but not always
C_sharp : With great surprised I observed the following behavior today : Given a classand this codewhile initializing foos to new List < Foo > { new Foo ( ) , new Foo ( ) , new Foo ( ) } makes the loop write `` 555 '' .My question : Why does this happen and is there a way to circumvent this whithout using .ToList ( ) ( which needs a comment , since it does not seem to be needed here ) . <code> class Foo { prop int FooNumber { get ; set ; } } IEnumerable < Foo > foos = Enumerable.Range ( 0,3 ) .Select ( new Foo ( ) ) ; foreach ( var foo in foos ) foo.Bar = 5 ; foreach ( var foo in foos ) Console.Write ( foo.Bar ) ; // Writes 000
Changing Properties of IEnumerator < T > .Current
C_sharp : I have the following method signature : The delegate and the arguments are saved to a collection for future invoking.Is there any way i can check whether the arguments array satisfies the delegate requirements without invoking it ? Thanks.EDIT : Thanks for the reflection implementation , but i searching for a built-in way to do this . I do n't want to reinvert the wheel , the .NET Framework already have this checking implemented inside Delegate.DynamicInvoke ( ) somewhere , implementation that handles all those crazy special cases that only Microsoft 's developers can think about , and passed Unit Testing and QA . Is there any way to use this built-in implementation ? Thanks . <code> public static void InvokeInFuture ( Delegate method , params object [ ] args ) { // ... }
Checking whether an ` object [ ] args ` satisfies a Delegate instance ?
C_sharp : VB.NET Code : Returns : 113,25 : -163,5C # Code : returns 0 : 0I do n't get it , would appreciate an explanation . <code> Module Module1Sub Main ( ) Dim x , y As Single x = 0 + ( 512 / 2 - 407 ) / 256 * 192 * -1 y = 0 + ( 512 / 2 - 474 ) / 256 * 192 Console.WriteLine ( x.ToString + `` : `` + y.ToString ) Console.ReadLine ( ) End SubEnd Module class Program { static void Main ( string [ ] args ) { float x , y ; x = 0 + ( 512 / 2 - 407 ) / 256 * 192 * -1 ; y = 0 + ( 512 / 2 - 474 ) / 256 * 192 ; Console.WriteLine ( x + `` : `` + y ) ; Console.ReadLine ( ) ; } }
Why is this code returning different values ? ( C # and VB.NET )
C_sharp : I 'd like to enforce a struct to always be valid regarding a certain contract , enforced by the constructor . However the contract is violated by the default operator.Consider the following , for example : As a workaround I changed my struct to a class so I can ensure the constructor is always called when initializing a new instance . But I wonder , is there absolutely no way to obtain the same behavior with a struct ? <code> struct NonNullInteger { private readonly int _value ; public int Value { get { return _value ; } } public NonNullInteger ( int value ) { if ( value == 0 ) { throw new ArgumentOutOfRangeException ( `` value '' ) ; } _value = value ; } } // Somewhere else : var i = new NonNullInteger ( 0 ) ; // Will throw , contract respectedvar j = default ( NonNullInteger ) ; // Will not throw , contract broken
How can I enforce a contract within a struct
C_sharp : What is going on with this C # code ? I 'm not even sure why it compiles . Specifically , what 's going on where it 's setting Class1Prop attempting to use the object initializer syntax ? It seems like invalid syntax but it compiles and produces a null reference error at runtime . <code> void Main ( ) { var foo = new Class1 { Class1Prop = { Class2Prop = `` one '' } } ; } public class Class1 { public Class2 Class1Prop { get ; set ; } } public class Class2 { public string Class2Prop { get ; set ; } }
What is happening with this C # object initializer code ?
C_sharp : Wracking my brain around this to no avail , wonder if anyone can be of help ? Getting a really frustrating casting issue that im sure will have a quick answer , but is probably just happening due to my limited understanding of generic type inference or something.Thanks in advance ! Scenario is a number of `` Step '' ViewModels for a Wizard site . I 'm creating Builder classes for each , and using a factory to grab the specific builder for the step that gets posted back to me , which is a Collection of IStepViewModel's.The failing test ! The problem ! Unable to cast object of type 'Company.Namespace.SpecificViewModelBuilder ' to type 'Company.Namespace.Builders.IStepModelBuilder ` 1 [ Company.Namespace.IStepViewModel ] '.Factory Impl as follows using Castle.WindsorRegistration of this : Stacktrace : System.InvalidCastException was unhandled by user code HResult=-2147467262 Message=Unable to cast object of type 'Company.Namespace.SpecificViewModelBuilder ' to type 'Company.Namespace.IStepModelBuilder ` 1 [ Company.Namespace.IStepViewModel ] ' . Source=DynamicProxyGenAssembly2 StackTrace : at Castle.Proxies.IStepViewModelBuilderFactoryProxy.Create [ T ] ( T stepViewModel ) at Tests.Infrastructure.ViewModelBuilderFactoryTests.TestResolution ( ) in c : \Project\Infrastructure\ViewModelBuilderFactoryTests.cs : line 61 InnerException : EDIT : IModelBuilder < T > interface <code> public interface IStepViewModelBuilderFactory { IStepModelBuilder < T > Create < T > ( T stepViewModel ) where T : IStepViewModel ; void Release < T > ( IStepModelBuilder < T > stepViewModelBuilder ) where T : IStepViewModel ; } public interface IStepViewModel { } public interface IStepModelBuilder < TStepViewModel > : IModelBuilder < TStepViewModel > where TStepViewModel : IStepViewModel { } public class SpecificViewModelBuilder : IStepModelBuilder < SpecificStepViewModel > { } public class SpecificStepViewModel : StepViewModel { } public abstract class StepViewModel : IStepViewModel { } [ Test ] public void TestResolution ( ) { var factory = this.container.Resolve < IStepViewModelBuilderFactory > ( ) ; IStepViewModel viewModel = new SpecificStepViewModel ( ) ; var builder = factory.Create ( viewModel ) ; // Here Assert.That ( builder , Is.Not.Null ) ; } public class StepViewModelSelector : DefaultTypedFactoryComponentSelector { protected override Type GetComponentType ( System.Reflection.MethodInfo method , object [ ] arguments ) { var arg = arguments [ 0 ] .GetType ( ) ; var specType = typeof ( IModelBuilder < > ) .MakeGenericType ( arg ) ; return specType ; } } container.AddFacility < TypedFactoryFacility > ( ) ; ... . container .Register ( Classes .FromAssemblyContaining < StepViewModelSelector > ( ) .BasedOn < StepViewModelSelector > ( ) ) ; container .Register ( Component .For < IStepViewModelBuilderFactory > ( ) .AsFactory ( c = > c.SelectedWith < StepViewModelSelector > ( ) ) ) ; public interface IModelBuilder < TViewModel > { TViewModel Build ( ) ; TViewModel Rebuild ( TViewModel model ) ; }
ViewModelBuilder generics casting issue
C_sharp : I have recently noticed a curiosity ( at least for me ) . I thought that the null-coalescing operator would take the precedence over any mathematical operation but obviously i was wrong . I thought following two variables would have the same value at the end : But v2.Value is ( the desired ) 1 whereas v1.Value is still 0 . Why ? Demo <code> double ? previousValue = null ; double ? v1 = 1 + previousValue ? ? 0 ; double ? v2 = 1 + ( previousValue ? ? 0 ) ;
Why do i need to put the null-coalescing operator in brackets ?
C_sharp : Within an async method , any local variables are stored away so that when whatever thread continues after the await will have access to the values . Is there any way to indicate which values are really needed after the await ? For example : So I have declared 7 local variables , but only use 2 of them after the await , is there any attribute I can decorate my variables with to indicate that I intend to only use firstName and city after the await completes ? Note : This is a contrived example , but it seems like it might be beneficial to be able to curb the storage of potentially large data chunks if they are not needed when the next thread comes to finish the work . <code> var firstName = `` Karl '' ; var lastName = `` Anderson '' ; var street1 = `` 123 Nowhere Street '' ; var street2 = `` Apt 1-A '' ; var city = `` Beverly Hills '' ; var state = `` California '' ; var zip = `` 90210 '' ; await MyTaskHere ( ) ; Console.WriteLine ( firstName ) ; Console.WriteLine ( city ) ;
Can I specify which variables I want to persist beyond the completion of an await continuation ?
C_sharp : I was trying to implement the following FFT filter kernel : This formula is missing with two squares under the sqrt.Source codeOnly concentrate on the algorithm and the formula at this time.OutputThe problem with this filter is , it can only rotate between 0-90 degrees , and does n't work outside that range.How can I make it rotate for any angle between 0-360 degrees ? <code> public partial class Form1 : Form { public Form1 ( ) { InitializeComponent ( ) ; Bitmap image = DataConverter2d.ReadGray ( StandardImage.LenaGray ) ; Array2d < double > dImage = DataConverter2d.ToDouble ( image ) ; int newWidth = Tools.ToNextPowerOfTwo ( dImage.Width ) * 2 ; int newHeight = Tools.ToNextPowerOfTwo ( dImage.Height ) * 2 ; double n = 6 ; double f0 = 0.5 ; double theta = 60 ; double a = 0.4 ; Array2d < Complex > kernel2d = CustomFft ( newWidth , newHeight , n , f0 , theta , a ) ; dImage.PadTo ( newWidth , newHeight ) ; Array2d < Complex > cImage = DataConverter2d.ToComplex ( dImage ) ; Array2d < Complex > fImage = FourierTransform.ForwardFft ( cImage ) ; // FFT convolution ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... . Array2d < Complex > fOutput = new Array2d < Complex > ( newWidth , newHeight ) ; for ( int x = 0 ; x < newWidth ; x++ ) { for ( int y = 0 ; y < newHeight ; y++ ) { fOutput [ x , y ] = fImage [ x , y ] * kernel2d [ x , y ] ; } } Array2d < Complex > cOutput = FourierTransform.InverseFft ( fOutput ) ; Array2d < double > dOutput = Rescale2d.Rescale ( DataConverter2d.ToDouble ( cOutput ) ) ; dOutput.CropBy ( ( newWidth - image.Width ) / 2 , ( newHeight - image.Height ) / 2 ) ; Bitmap output = DataConverter2d.ToBitmap ( dOutput , image.PixelFormat ) ; Array2d < Complex > cKernel = FourierTransform.InverseFft ( kernel2d ) ; cKernel = FourierTransform.RemoveFFTShift ( cKernel ) ; Array2d < double > dKernel = DataConverter2d.ToDouble ( cKernel ) ; Array2d < double > dLimitedKernel = Rescale2d.Limit ( dKernel ) ; Bitmap kernel = DataConverter2d.ToBitmap ( dLimitedKernel , image.PixelFormat ) ; pictureBox1.Image = image ; pictureBox2.Image = kernel ; pictureBox3.Image = output ; } private double Basic ( double u , double v , double n , double f0 , double rad , double a , double b ) { double ua = u + f0 * Math.Cos ( rad ) ; double va = v + f0 * Math.Sin ( rad ) ; double ut = ua * Math.Cos ( rad ) + va * Math.Sin ( rad ) ; double vt = ( -1 ) * ua * Math.Sin ( rad ) + va * Math.Cos ( rad ) ; double p = ut/a ; double q = vt/b ; double sqrt = Math.Sqrt ( p*p + q*q ) ; return 1.0 / ( 1.0+ 0.414 * Math.Pow ( sqrt , 2*n ) ) ; } private double Custom ( double u , double v , double n , double f0 , double theta , double a ) { double rad1 = ( Math.PI / 180 ) * ( 90-theta ) ; double rad2 = rad1 + Math.PI ; double b = ( a / 5.0 ) / ( 2*n ) ; double ka = Basic ( u , v , n , f0 , rad1 , a , b ) ; double kb = Basic ( u , v , n , f0 , rad2 , a , b ) ; return Math.Max ( ka , kb ) ; } private Array2d < Complex > CustomFft ( double sizeX , double sizeY , double n , double f0 , double theta , double a ) { double halfX = sizeX / 2 ; double halfY = sizeY / 2 ; Array2d < Complex > kernel = new Array2d < Complex > ( ( int ) sizeX , ( int ) sizeY ) ; for ( double y = 0 ; y < sizeY ; y++ ) { double v = y / sizeY ; for ( double x = 0 ; x < sizeX ; x++ ) { double u = x / sizeX ; double kw = Custom ( u , v , n , f0 , theta , a ) ; kernel [ ( int ) x , ( int ) y ] = new Complex ( kw , 0 ) ; } } return kernel ; } }
Band-pass filter ca n't rotate more than 90 degrees
C_sharp : I want to be able to initialize a class just like I initialize a string : I really do n't know what exactly string str = `` hello '' ; does . I assume `` hello '' gets translated by the compiler into new System.String ( `` hello '' ) ; but I 'm not sure . Maybe is just not possible or maybe I 'm missing something very elemental ; if that 's the case excuse my ignorance : ) . What I 'm trying to make is a class that works just like a string but stores the string in a file automatically.Ok , here 's my code after reading you answers : What do you think ? <code> string str = `` hello '' ; MyClass class = `` hello '' ; class StringOnFile { private static string Extension = `` .htm '' ; private string _FullPath ; public bool Preserve = false ; public string FullPath { get { return _FullPath ; } } public static implicit operator StringOnFile ( string value ) { StringOnFile This = new StringOnFile ( ) ; int path = 0 ; do { path++ ; This._FullPath = Path.GetFullPath ( path.ToString ( ) + Extension ) ; } while ( File.Exists ( This._FullPath ) ) ; using ( StreamWriter sw = File.CreateText ( This._FullPath ) ) { sw.Write ( value ) ; } return This ; } public static implicit operator string ( StringOnFile stringOnFile ) { using ( StreamReader sr = File.OpenText ( stringOnFile._FullPath ) ) { return sr.ReadToEnd ( ) ; } } ~StringOnFile ( ) { if ( ! Preserve ) File.Delete ( FullPath ) ; } }
How can I make a class in C # that I can initialize just like a string ?
C_sharp : If I haveandIs this the same ? Is the compiler able to remove s ? How about ? Thanks . <code> private string Foo ( string decrypted ) { return decrypted.Substring ( blah ) ; } private string Foo ( string decrypted ) { string s = decrypted.Substring ( blah ) ; return s ; } private string Foo ( string decrypted ) { string s = decrypted.Substring ( blah ) ; string t = s ; return t ; }
compiler optimisation when returning strings
C_sharp : I have a working real time monitoring program but it 's class architecture is too complex . And this disturbs me really much . Let me start by explaining the program.User InteractionThis is a monitoring program with user interaction . Which means , user can select different dimensions , different metrics , include them , exlude them or group them and everytime real-time chart changes according to user 's decisions.Example Log Data from DBThe ConversionSo every row is important with it 's every column . And it has to be on the client-side like this . Because user can choose to see Successful OrderFunctions or All the functions on WebServer2 or All Failed Request etc . I need all the relations between these columns to do these.Another thing is these are the values that comes from Database . I also have lookups for these values which holds the Text 's that users need to see . Like Req is Request , Resp is Response.I know you can see this question as a general one . But I 'm trying to find a way . May be this kind of class architecture has a name in the industry . I 'm just here for some advices to lead me in to a right way.Thanks a lot <code> Req Success OrderFunction 5 60ms WebServer2Req Failed OrderFunction 2 176ms WebServer5Resp Success SuggestFunction 8 45ms WebServer2
Class Architecture of Monitoring Log Data
C_sharp : Please take a look at these lines:1. in this case I type where statement directly in methodExecuted sql query is : 2. in this case I used Func for generic where clauseExecuted sql query is : as you can see , in case 2 where clause which is WHERE 1 = [ Extent1 ] . [ Id ] is missing and therefore whole records are stored in memory . do you have any idea why where clause is not translated in sql query ? I want to use Func < t , bool > in .Where ( ) so it would be generic and no need to create functions for each query.is there any way to use .Where ( Func < t , bool > ) and also see the translated where clause in sql query ? <code> public List < User > GetUsers ( ) { return _entity.Where ( x = > x.Id == 1 ) .ToList ( ) ; } SELECT [ Extent1 ] . [ Id ] AS [ Id ] , [ Extent1 ] . [ Username ] AS [ Username ] , [ Extent1 ] . [ Password ] AS [ Password ] , [ Extent1 ] . [ Email ] AS [ Email ] , [ Extent2 ] . [ Id ] AS [ Id1 ] FROM [ dbo ] . [ Account_Users ] AS [ Extent1 ] LEFT OUTER JOIN [ dbo ] . [ Account_Profiles ] AS [ Extent2 ] ON [ Extent1 ] . [ Id ] = [ Extent2 ] . [ UserId ] WHERE 1 = [ Extent1 ] . [ Id ] public List < User > GetUsers ( Func < User , bool > where ) { return _entity.Where ( where ) .ToList ( ) ; } var users = _acc.GetUsers ( x = > x.Id == 1 ) ; SELECT [ Extent1 ] . [ Id ] AS [ Id ] , [ Extent1 ] . [ Username ] AS [ Username ] , [ Extent1 ] . [ Password ] AS [ Password ] , [ Extent1 ] . [ Email ] AS [ Email ] , [ Extent2 ] . [ Id ] AS [ Id1 ] FROM [ dbo ] . [ Account_Users ] AS [ Extent1 ] LEFT OUTER JOIN [ dbo ] . [ Account_Profiles ] AS [ Extent2 ] ON [ Extent1 ] . [ Id ] = [ Extent2 ] . [ UserId ]
Func < t , bool > vs Manually expression performance in C # lambda
C_sharp : I use the MS Sync Framework to sync my SQL Server instance with a local SQL CE file to make it possible working offline with my Windows app.I use GUIDs as keys . On my table I have a unique index on 2 columns : user_id and setting_id : Now I do the following : I create a new record in this table in both databases - SQL Server and SQL CE with the same user_id and setting_id.This should work and merge the data together since this can happen in real life . But I get an error when syncing saying the unique key constraint led to an error . The key pair already exists in the table.A duplicate value can not be inserted into a unique index . [ Table name = user_settings , Constraint name = unique_userid_settingid ] Why ca n't MS sync handle that ? It should not try to insert the key pair again . It should update the value if needed . <code> usersettings table -- -- -- -- -- -- -- -- -- id PK - > I also tried it without this column . Same resultuser_id FK setting_id FKvalue
Microsoft Sync Framework unique index error
C_sharp : This power series is valid for [ 0 , pi/2 ] and it is 10 times slower than the built in sine function in release mode . 1ms vs 10ms.But when I copy paste mysin code into the function I get practically the same time in release and my code is about 4 times faster when in debug mode.What is the deal here ? How do I make this sort of calculations faster ? I am guessing the code automatically recognizes that sin algorithm should not be called but copy paste into the loop . How do I make the compiler do the same for me.One more question , would c++ do the same optimization for its default sin/cos function ? If not how would I make sure that it does . Edit : I tested it and my sine function ( with 4 extra if conditions added to expand the domain to all real ) runs about 25 % faster ( albeit inaccurate ) than the default sin function . And in fact , the copy pasted version runs slower than when I write it as a separate function . <code> const double pi = 3.1415926535897 ; static double mysin ( double x ) { return ( ( ( ( ( ( -0.000140298 * x - 0.00021075890 ) * x + 0.008703147 ) * x - 0.0003853080 ) * x - 0.16641544 ) * x - 0.00010117316 ) * x + 1.000023121 ) * x ; } static void Main ( string [ ] args ) { Stopwatch sw = new Stopwatch ( ) ; double a = 0 ; double [ ] arg = new double [ 1000000 ] ; for ( int i = 0 ; i < 1000000 ; i++ ) { arg [ i ] = ( pi / 2000000 ) ; } sw.Restart ( ) ; for ( int i = 0 ; i < 1000000 ; i++ ) { a = a + Math.Sin ( arg [ i ] ) ; } sw.Stop ( ) ; double t1 = ( double ) ( sw.Elapsed.TotalMilliseconds ) ; a = 0 ; sw.Restart ( ) ; for ( int i = 0 ; i < 1000000 ; i++ ) { a = a + mysin ( arg [ i ] ) ; } sw.Stop ( ) ; double t2 = ( double ) ( sw.Elapsed.TotalMilliseconds ) ; Console.WriteLine ( `` { 0 } \n { 1 } \n '' , t1 , t2 ) ; Console.Read ( ) ; } a = 0 ; sw.Restart ( ) ; for ( int i = 0 ; i < 1000000 ; i++ ) { double x = arg [ i ] ; a = a + ( ( ( ( ( ( -0.000140298 * x - 0.00021075890 ) * x + 0.008703147 ) * x - 0.0003853080 ) * x - 0.16641544 ) * x - 0.00010117316 ) * x + 1.000023121 ) * x ; //a = a + mysin ( arg [ i ] ) ; }
Why is my sine algorithm much slower than the default ?
C_sharp : I am using C # and LINQ , I have some Date in type DateAt the moment I am using this script to order a list by date of start , from the earlier to the latest.With the following code my events are not sorted : What could be wrong here ? <code> events.OrderBy ( x = > x.DateTimeStart ) .ToList ( ) ; return events.AsQueryable ( ) ;
How to order Dates in Linq ?
C_sharp : Is there a more elegant solution for adding an item to an IEnumerable than this ? Some context : <code> myNewIEnumerable = myIEnumerable.Concat ( Enumerable.Repeat ( item , 1 ) ) ; public void printStrings ( IEnumerable < string > myStrings ) { Console.WriteLine ( `` The beginning . `` ) ; foreach ( var s in myStrings ) Console.WriteLine ( s ) ; Console.WriteLine ( `` The end . `` ) ; } ... var result = someMethodDeliveringAnIEnumerableOfStrings ( ) ; printStrings ( result.Concat ( Enumerable.Repeat ( `` finished '' , 1 ) ) ) ;
Adding single item to enumerable
C_sharp : Suppose you have a method with the following signature : When calling this method , is there a way to specify a value for bar and not foo ? It would look something like ... ... which would translate to ... ... at compile-time . Is this possible ? <code> public void SomeMethod ( bool foo = false , bool bar = true ) { /* ... */ } SomeMethod ( _ , false ) ; SometMethod ( false , false ) ;
Optional Specification of some C # Optional Parameters
C_sharp : I have a winform code which run after a button click : Question : Why do I see one MessageBox at a time when delay=1 : But If I change delay to : 1,2,3 —I see - 3 Message Boxes without even clicking any Messagebox ? Thanks to @ Noseratio for pointing that behaviour at first place . <code> void button1_Click ( object sender , EventArgs e ) { AAA ( ) ; } async Task BBB ( int delay ) { await Task.Delay ( TimeSpan.FromSeconds ( delay ) ) ; MessageBox.Show ( `` hello '' ) ; } async Task AAA ( ) { var task1 = BBB ( 1 ) ; // < -- - notice delay=1 ; var task2 = BBB ( 1 ) ; // < -- - notice delay=1 ; var task3 = BBB ( 1 ) ; // < -- - notice delay=1 ; await Task.WhenAll ( task1 , task2 , task3 ) ; } var task1 = BBB ( 1 ) ; var task2 = BBB ( 2 ) ; var task3 = BBB ( 3 ) ;
async-await 's continuations bursts — behave differently ?
C_sharp : I have the following example : The question is why in the second `` Equals '' call I 'm redirected to Object.Equals instead of Hello.Equals even though I 'm specifying the exact type in generic argument ? <code> namespace ComparisonExample { class Program { static void Main ( string [ ] args ) { var hello1 = new Hello ( ) ; var hello2 = new Hello ( ) ; // calls Hello.Equals var compareExplicitly = hello1.Equals ( hello2 ) ; // calls Object.Equals var compareWithGenerics = ObjectsEqual < Hello > ( hello1 , hello2 ) ; } private static bool ObjectsEqual < TValue > ( TValue value1 , TValue value2 ) { return value1.Equals ( value2 ) ; } } class Hello : IEquatable < Hello > { public bool Equals ( Hello other ) { return true ; // does n't matter } } }
Why `` Equals '' method resolution with generics differs from explicit calls
C_sharp : I was wondering how field pinning is expressed in .Net 's IL language , so I took a look at the example code : This generates the IL : I 'm not seeing anything here , that would explicitly tell the GC to pin the array , which instruction is actually responsible for pinning ? Also , are there other basic operations which involve pinning `` under the hood '' ? <code> struct S { public fixed int buf [ 8 ] ; } S s = default ( S ) ; public void MyMethod ( ) { fixed ( int* ptr = s.buf ) { *ptr = 2 ; } } .method private hidebysig instance void MyMethod ( ) cil managed { // Method begins at RVA 0x2050 // Code size 25 ( 0x19 ) .maxstack 2 .locals init ( [ 0 ] int32 & pinned ) IL_0000 : ldarg.0 // Load argument 0 onto the stack IL_0001 : ldflda valuetype C/S C : :s // Push the address of field of object obj on the stack IL_0006 : ldflda valuetype C/S/ ' < buf > e__FixedBuffer ' C/S : :buf // Push the address of field of object obj on the stack IL_000b : ldflda int32 C/S/ ' < buf > e__FixedBuffer ' : :FixedElementField // Push the address of field of object obj on the stack IL_0010 : stloc.0 // Pop a value from stack into local variable 0 IL_0011 : ldloc.0 // Load local variable 0 onto stack IL_0012 : conv.i // Convert to native int , pushing native int on stack IL_0013 : ldc.i4.2 // Push 2 onto the stack as int32 IL_0014 : stind.i4 // Store value of type int32 into memory at address IL_0015 : ldc.i4.0 // Push 0 onto the stack as int32 IL_0016 : conv.u // Convert to native unsigned int , pushing native int on stack IL_0017 : stloc.0 // Pop a value from stack into local variable 0 IL_0018 : ret // Return from method , possibly with a value } // end of method C : :MyMethod
How is pinning represented in IL
C_sharp : I was wondering what would happen if I added a list to itself . Maybe a stack overflow , maybe a compiler error ? So I executed the code and checked the local variables : The list seems to contain an infinite number of list instances . Why is there no stack overflow ? Are the lists just pointers to the original list ? But even if the lists are just pointers , do pointers not also occupy memory too ? <code> List < object > lstobj = new List < object > ( ) ; lstobj.Add ( lstobj ) ;
Add an object list to itself ?